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 $IPV6RE);
18 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
21 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
22 my $pvefw_conf_dir = "/etc/pve/firewall";
23 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
25 # dynamically include PVE::QemuServer and PVE::OpenVZ
26 # to avoid dependency problems
29 require PVE
::QemuServer
;
30 $have_qemu_server = 1;
36 $have_pve_manager = 1;
39 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
40 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
41 my $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
43 my $max_alias_name_length = 64;
44 my $max_ipset_name_length = 64;
45 my $max_group_name_length = 20;
47 PVE
::JSONSchema
::register_format
('IPv4orCIDR', \
&pve_verify_ipv4_or_cidr
);
48 sub pve_verify_ipv4_or_cidr
{
49 my ($cidr, $noerr) = @_;
51 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
52 return $cidr if Net
::IP-
>new($cidr);
53 return undef if $noerr;
54 die Net
::IP
::Error
() . "\n";
56 return undef if $noerr;
57 die "value does not look like a valid IP address or CIDR network\n";
60 PVE
::JSONSchema
::register_format
('IPv4orCIDRorAlias', \
&pve_verify_ipv4_or_cidr_or_alias
);
61 sub pve_verify_ipv4_or_cidr_or_alias
{
62 my ($cidr, $noerr) = @_;
64 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
66 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
67 return $cidr if Net
::IP-
>new($cidr);
68 return undef if $noerr;
69 die Net
::IP
::Error
() . "\n";
71 return undef if $noerr;
72 die "value does not look like a valid IP address or CIDR network\n";
75 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
76 description
=> "IP set name.",
78 pattern
=> $ipset_name_pattern,
80 maxLength
=> $max_ipset_name_length,
83 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
84 description
=> "Alias name.",
86 pattern
=> $ip_alias_pattern,
88 maxLength
=> $max_alias_name_length,
91 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
92 description
=> "Log level.",
94 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
98 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
99 description
=> "Security Group name.",
101 pattern
=> $security_group_name_pattern,
103 maxLength
=> $max_group_name_length,
106 my $feature_ipset_nomatch = 0;
108 my (undef, undef, $release) = POSIX
::uname
();
109 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
110 my ($major, $minor) = ($1, $2);
111 $feature_ipset_nomatch = 1 if ($major > 3) ||
112 ($major == 3 && $minor >= 7);
119 my $nodename = PVE
::INotify
::nodename
();
121 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
123 my $default_log_level = 'nolog'; # avoid logs by default
125 my $log_level_hash = {
136 # imported/converted from: /usr/share/shorewall/macro.*
137 my $pve_fw_macros = {
140 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
141 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
144 "Auth (identd) traffic",
145 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
148 "Border Gateway Protocol traffic",
149 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
152 "BitTorrent traffic for BitTorrent 3.1 and earlier",
153 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
154 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
157 "BitTorrent traffic for BitTorrent 3.2 and later",
158 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
159 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
162 "Concurrent Versions System pserver traffic",
163 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
166 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
167 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
168 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
169 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
172 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
173 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
174 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
177 "Distributed Checksum Clearinghouse spam filtering mechanism",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
181 "Forwarded DHCP traffic",
182 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
185 "Domain Name System traffic (upd and tcp)",
186 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
187 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
190 "Distributed Compiler service",
191 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
194 "File Transfer Protocol",
195 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
198 "Finger protocol (RFC 742)",
199 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
202 "GNUnet secure peer-to-peer networking traffic",
203 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
204 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
205 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
206 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
209 "Generic Routing Encapsulation tunneling protocol",
210 { action
=> 'PARAM', proto
=> '47' },
213 "Git distributed revision control traffic",
214 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
217 "OpenPGP HTTP keyserver protocol traffic",
218 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
221 "Hypertext Transfer Protocol (WWW)",
222 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
225 "Hypertext Transfer Protocol (WWW) over SSL",
226 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
229 "Internet Cache Protocol V2 (Squid) traffic",
230 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
233 "AOL Instant Messenger traffic",
234 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
237 "Internet Message Access Protocol",
238 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
241 "Internet Message Access Protocol over SSL",
242 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
245 "IPIP capsulation traffic",
246 { action
=> 'PARAM', proto
=> '94' },
250 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
251 { action
=> 'PARAM', proto
=> '50' },
254 "IPsec authentication (AH) traffic",
255 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
256 { action
=> 'PARAM', proto
=> '51' },
259 "IPsec traffic and Nat-Traversal",
260 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
261 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
262 { action
=> 'PARAM', proto
=> '50' },
265 "Internet Relay Chat traffic",
266 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
269 "HP Jetdirect printing",
270 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
273 "Layer 2 Tunneling Protocol traffic",
274 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
277 "Lightweight Directory Access Protocol traffic",
278 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
281 "Secure Lightweight Directory Access Protocol traffic",
282 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
285 "Microsoft Notification Protocol",
286 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
289 "Microsoft SQL Server",
290 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
293 "Mail traffic (SMTP, SMTPS, Submission)",
294 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
295 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
296 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
299 "Munin networked resource monitoring traffic",
300 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
304 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
307 "NNTP traffic (Usenet).",
308 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
311 "Encrypted NNTP traffic (Usenet)",
312 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
315 "Network Time Protocol (ntpd)",
316 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
319 "OSPF multicast traffic",
320 { action
=> 'PARAM', proto
=> '89' },
324 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
327 "Symantec PCAnywere (tm)",
328 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
336 "Encrypted POP3 traffic",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
340 "Point-to-Point Tunneling Protocol",
341 { action
=> 'PARAM', proto
=> '47' },
342 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
346 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
350 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
353 "Line Printer protocol printing",
354 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
357 "Microsoft Remote Desktop Protocol traffic",
358 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
361 "Routing Information Protocol (bidirectional)",
362 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
365 "BIND remote management protocol",
366 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
369 "Razor Antispam System",
370 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
373 "Remote time retrieval (rdate)",
374 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
378 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
381 "SANE network scanning",
382 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
385 "Microsoft SMB traffic",
386 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
387 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
388 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
389 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
392 "Samba Web Administration Tool",
393 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
396 "Simple Mail Transfer Protocol",
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
400 "Encrypted Simple Mail Transfer Protocol",
401 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
404 "Simple Network Management Protocol",
405 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
406 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
409 "Spam Assassin SPAMD traffic",
410 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
413 "Secure shell traffic",
414 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
417 "Subversion server (svnserve)",
418 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
421 "SixXS IPv6 Deployment and Tunnel Broker",
422 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
423 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
424 { action
=> 'PARAM', proto
=> '41' },
425 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
428 "Squid web proxy traffic",
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
432 "Mail message submission traffic",
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
436 "Syslog protocol (RFC 5424) traffic",
437 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
438 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
441 "Trivial File Transfer Protocol traffic",
442 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
450 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
453 "RFC 868 Time protocol",
454 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
457 "Traceroute (for up to 30 hops) traffic",
458 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
459 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
462 "VNC traffic for VNC display's 0 - 99",
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
466 "VNC traffic from Vncservers to Vncviewers in listen mode",
467 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
470 "WWW traffic (HTTP and HTTPS)",
471 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
472 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
475 "Web Cache/Proxy traffic (port 8080)",
476 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
480 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
483 "Whois (nicname, RFC 3912) traffic",
484 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
488 my $pve_fw_parsed_macros;
489 my $pve_fw_macro_descr;
490 my $pve_fw_preferred_macro_names = {};
492 my $pve_std_chains = {};
493 $pve_std_chains->{4} = {
494 'PVEFW-SET-ACCEPT-MARK' => [
495 "-j MARK --set-mark 1",
497 'PVEFW-DropBroadcast' => [
498 # same as shorewall 'Broadcast'
499 # simply DROP BROADCAST/MULTICAST/ANYCAST
500 # we can use this to reduce logging
501 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
502 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
503 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
504 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
507 # same as shorewall 'reject'
508 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
509 { action
=> 'DROP', source
=> '224.0.0.0/4' },
510 { action
=> 'DROP', proto
=> 'icmp' },
511 "-p tcp -j REJECT --reject-with tcp-reset",
512 "-p udp -j REJECT --reject-with icmp-port-unreachable",
513 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
514 "-j REJECT --reject-with icmp-host-prohibited",
517 # same as shorewall 'Drop', which is equal to DROP,
518 # but REJECT/DROP some packages to reduce logging,
519 # and ACCEPT critical ICMP types
520 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
521 # we are not interested in BROADCAST/MULTICAST/ANYCAST
522 { action
=> 'PVEFW-DropBroadcast' },
523 # ACCEPT critical ICMP types
524 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
525 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
526 # Drop packets with INVALID state
527 "-m conntrack --ctstate INVALID -j DROP",
528 # Drop Microsoft SMB noise
529 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
530 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
531 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
532 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
533 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
534 # Drop new/NotSyn traffic so that it doesn't get logged
535 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
537 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
540 # same as shorewall 'Reject', which is equal to Reject,
541 # but REJECT/DROP some packages to reduce logging,
542 # and ACCEPT critical ICMP types
543 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
544 # we are not interested in BROADCAST/MULTICAST/ANYCAST
545 { action
=> 'PVEFW-DropBroadcast' },
546 # ACCEPT critical ICMP types
547 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
548 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
549 # Drop packets with INVALID state
550 "-m conntrack --ctstate INVALID -j DROP",
551 # Drop Microsoft SMB noise
552 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
553 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
554 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
555 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
556 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
557 # Drop new/NotSyn traffic so that it doesn't get logged
558 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
560 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
562 'PVEFW-tcpflags' => [
563 # same as shorewall tcpflags action.
564 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
565 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
566 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
567 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
568 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
569 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
572 # same as shorewall smurfs action
573 # Filter packets for smurfs (packets with a broadcast address as the source).
574 "-s 0.0.0.0/32 -j RETURN",
575 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
576 "-s 224.0.0.0/4 -g PVEFW-smurflog",
580 # iptables -p icmp -h
581 my $icmp_type_names = {
584 'destination-unreachable' => 1,
585 'network-unreachable' => 1,
586 'host-unreachable' => 1,
587 'protocol-unreachable' => 1,
588 'port-unreachable' => 1,
589 'fragmentation-needed' => 1,
590 'source-route-failed' => 1,
591 'network-unknown' => 1,
593 'network-prohibited' => 1,
594 'host-prohibited' => 1,
595 'TOS-network-unreachable' => 1,
596 'TOS-host-unreachable' => 1,
597 'communication-prohibited' => 1,
598 'host-precedence-violation' => 1,
599 'precedence-cutoff' => 1,
600 'source-quench' => 1,
602 'network-redirect' => 1,
603 'host-redirect' => 1,
604 'TOS-network-redirect' => 1,
605 'TOS-host-redirect' => 1,
607 'router-advertisement' => 1,
608 'router-solicitation' => 1,
609 'time-exceeded' => 1,
610 'ttl-zero-during-transit' => 1,
611 'ttl-zero-during-reassembly' => 1,
612 'parameter-problem' => 1,
613 'ip-header-bad' => 1,
614 'required-option-missing' => 1,
615 'timestamp-request' => 1,
616 'timestamp-reply' => 1,
617 'address-mask-request' => 1,
618 'address-mask-reply' => 1,
621 sub init_firewall_macros
{
623 $pve_fw_parsed_macros = {};
625 foreach my $k (keys %$pve_fw_macros) {
626 my $lc_name = lc($k);
627 my $macro = $pve_fw_macros->{$k};
628 if (!ref($macro->[0])) {
629 $pve_fw_macro_descr->{$k} = shift @$macro;
631 $pve_fw_preferred_macro_names->{$lc_name} = $k;
632 $pve_fw_parsed_macros->{$k} = $macro;
636 init_firewall_macros
();
639 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
644 sub get_etc_services
{
646 return $etc_services if $etc_services;
648 my $filename = "/etc/services";
650 my $fh = IO
::File-
>new($filename, O_RDONLY
);
652 warn "unable to read '$filename' - $!\n";
658 while (my $line = <$fh>) {
660 next if $line =~m/^#/;
661 next if ($line =~m/^\s*$/);
663 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
664 $services->{byid
}->{$2}->{name
} = $1;
665 $services->{byid
}->{$2}->{port
} = $2;
666 $services->{byid
}->{$2}->{$3} = 1;
667 $services->{byname
}->{$1} = $services->{byid
}->{$2};
673 $etc_services = $services;
676 return $etc_services;
681 sub get_etc_protocols
{
682 return $etc_protocols if $etc_protocols;
684 my $filename = "/etc/protocols";
686 my $fh = IO
::File-
>new($filename, O_RDONLY
);
688 warn "unable to read '$filename' - $!\n";
694 while (my $line = <$fh>) {
696 next if $line =~m/^#/;
697 next if ($line =~m/^\s*$/);
699 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
700 $protocols->{byid
}->{$2}->{name
} = $1;
701 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
707 $etc_protocols = $protocols;
709 return $etc_protocols;
712 my $ipv4_mask_hash_localnet = {
714 '255.255.128.0' => 17,
715 '255.255.192.0' => 18,
716 '255.255.224.0' => 19,
717 '255.255.240.0' => 20,
718 '255.255.248.0' => 21,
719 '255.255.252.0' => 22,
720 '255.255.254.0' => 23,
721 '255.255.255.0' => 24,
722 '255.255.255.128' => 25,
723 '255.255.255.192' => 26,
724 '255.255.255.224' => 27,
725 '255.255.255.240' => 28,
726 '255.255.255.248' => 29,
727 '255.255.255.252' => 30,
733 my ($new_value) = @_;
735 $__local_network = $new_value if defined($new_value);
737 return $__local_network if defined($__local_network);
740 my $nodename = PVE
::INotify
::nodename
();
742 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
744 my $testip = Net
::IP-
>new($ip);
746 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
747 foreach my $entry (@$routes) {
748 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
749 next if !defined($mask);
750 return if $mask eq '0.0.0.0';
751 my $cidr = "$entry->{dest}/$mask";
752 my $testnet = Net
::IP-
>new($cidr);
753 if ($testnet->overlaps($testip)) {
754 $__local_network = $cidr;
761 return $__local_network;
764 # ipset names are limited to 31 characters, and we use '_swap'
765 # suffix for atomic update, for example PVEFW-${VMID}-${ipset_name}_swap
767 my $max_iptables_ipset_name_length = 31 - length("_swap");
769 sub compute_ipset_chain_name
{
770 my ($vmid, $ipset_name) = @_;
772 $vmid = 0 if !defined($vmid);
774 my $id = "$vmid-${ipset_name}";
777 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
778 $id = PVE
::Tools
::fnv31a_hex
($id);
784 sub compute_ipfilter_ipset_name
{
787 return "ipfilter-$iface";
790 sub parse_address_list
{
793 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
794 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
798 if ($str =~ m/^${ip_alias_pattern}$/) {
799 die "alias name too long\n" if length($str) > $max_alias_name_length;
807 foreach my $elem (split(/,/, $str)) {
809 my $ip = Net
::IP-
>new($elem);
811 my $err = Net
::IP
::Error
();
812 die "invalid IP address: $err\n";
814 $iprange = 1 if $elem =~ m/-/;
816 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
818 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
819 if $ipversion && ($new_ipversion != $ipversion);
821 $ipversion = $new_ipversion;
824 die "you can't use a range in a list\n" if $iprange && $count > 1;
829 sub parse_port_name_number_or_range
{
832 my $services = PVE
::Firewall
::get_etc_services
();
836 foreach my $item (split(/,/, $str)) {
838 if ($item =~ m/^(\d+):(\d+)$/) {
839 my ($port1, $port2) = ($1, $2);
840 die "invalid port '$port1'\n" if $port1 > 65535;
841 die "invalid port '$port2'\n" if $port2 > 65535;
842 } elsif ($item =~ m/^(\d+)$/) {
844 die "invalid port '$port'\n" if $port > 65535;
846 if ($icmp_type_names->{$item}) {
849 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
854 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
859 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
860 sub pve_fw_verify_port_spec
{
863 parse_port_name_number_or_range
($portstr);
868 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
869 sub pve_fw_verify_addr_spec
{
872 parse_address_list
($list);
877 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
878 sub pve_fw_verify_protocol_spec
{
881 my $protocols = get_etc_protocols
();
883 die "unknown protocol '$proto'\n" if $proto &&
884 !(defined($protocols->{byname
}->{$proto}) ||
885 defined($protocols->{byid
}->{$proto}));
891 # helper function for API
893 sub copy_opject_with_digest
{
896 my $sha = Digest
::SHA-
>new('sha1');
899 foreach my $k (sort keys %$object) {
900 my $v = $object->{$k};
901 next if !defined($v);
903 $sha->add($k, ':', $v, "\n");
906 my $digest = $sha->hexdigest;
908 $res->{digest
} = $digest;
910 return wantarray ?
($res, $digest) : $res;
913 sub copy_list_with_digest
{
916 my $sha = Digest
::SHA-
>new('sha1');
919 foreach my $entry (@$list) {
921 foreach my $k (sort keys %$entry) {
922 my $v = $entry->{$k};
923 next if !defined($v);
925 # Note: digest ignores refs ($rule->{errors})
926 $sha->add($k, ':', $v, "\n") if !ref($v); ;
931 my $digest = $sha->hexdigest;
933 foreach my $entry (@$res) {
934 $entry->{digest
} = $digest;
937 return wantarray ?
($res, $digest) : $res;
940 my $rule_properties = {
942 description
=> "Update rule at position <pos>.",
947 digest
=> get_standard_option
('pve-config-digest'),
951 enum
=> ['in', 'out', 'group'],
954 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
957 pattern
=> $security_group_name_pattern,
966 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
968 type
=> 'string', format
=> 'pve-fw-addr-spec',
972 type
=> 'string', format
=> 'pve-fw-addr-spec',
976 type
=> 'string', format
=> 'pve-fw-protocol-spec',
984 type
=> 'string', format
=> 'pve-fw-port-spec',
988 type
=> 'string', format
=> 'pve-fw-port-spec',
997 sub add_rule_properties
{
998 my ($properties) = @_;
1000 foreach my $k (keys %$rule_properties) {
1001 my $h = $rule_properties->{$k};
1002 # copy data, so that we can modify later without side effects
1003 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1009 sub delete_rule_properties
{
1010 my ($rule, $delete_str) = @_;
1012 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1013 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1014 if !defined($rule_properties->{$opt});
1015 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1016 if $opt eq 'type' || $opt eq 'action';
1017 delete $rule->{$opt};
1023 my $apply_macro = sub {
1024 my ($macro_name, $param, $verify) = @_;
1026 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1027 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1031 foreach my $templ (@$macro_rules) {
1033 my $param_used = {};
1034 foreach my $k (keys %$templ) {
1035 my $v = $templ->{$k};
1036 if ($v eq 'PARAM') {
1038 $param_used->{$k} = 1;
1039 } elsif ($v eq 'DEST') {
1040 $v = $param->{dest
};
1041 $param_used->{dest
} = 1;
1042 } elsif ($v eq 'SOURCE') {
1043 $v = $param->{source
};
1044 $param_used->{source
} = 1;
1048 my $msg = "missing parameter '$k' in macro '$macro_name'";
1049 raise_param_exc
({ macro => $msg }) if $verify;
1054 foreach my $k (keys %$param) {
1055 next if $k eq 'macro';
1056 next if !defined($param->{$k});
1057 next if $param_used->{$k};
1058 if (defined($rule->{$k})) {
1059 if ($rule->{$k} ne $param->{$k}) {
1060 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1061 raise_param_exc
({ $k => $msg }) if $verify;
1065 $rule->{$k} = $param->{$k};
1068 push @$rules, $rule;
1074 my $rule_env_iface_lookup = {
1083 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1085 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1087 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1088 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1090 my $errors = $rule->{errors
} || {};
1092 my $error_count = 0;
1094 my $add_error = sub {
1095 my ($param, $msg) = @_;
1097 raise_param_exc
({ $param => $msg }) if !$noerr;
1099 $errors->{$param} = $msg if !$errors->{$param};
1102 my $check_ipset_or_alias_property = sub {
1105 if (my $value = $rule->{$name}) {
1106 if ($value =~ m/^\+/) {
1107 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1108 &$add_error($name, "no such ipset '$1'")
1109 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1112 &$add_error($name, "invalid ipset name '$value'");
1114 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1115 my $alias = lc($value);
1116 &$add_error($name, "no such alias '$value'")
1117 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1119 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1120 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1122 $ipversion = $e->{ipversion
};
1127 my $type = $rule->{type
};
1128 my $action = $rule->{action
};
1130 &$add_error('type', "missing property") if !$type;
1131 &$add_error('action', "missing property") if !$action;
1134 if ($type eq 'in' || $type eq 'out') {
1135 &$add_error('action', "unknown action '$action'")
1136 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1137 } elsif ($type eq 'group') {
1138 &$add_error('type', "security groups not allowed")
1140 &$add_error('action', "invalid characters in security group name")
1141 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1143 &$add_error('type', "unknown rule type '$type'");
1147 if ($rule->{iface
}) {
1148 &$add_error('type', "parameter -i not allowed for this rule type")
1150 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1151 &$add_error('iface', $@) if $@;
1152 if ($rule_env eq 'vm') {
1153 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1154 if $rule->{iface
} !~ m/^net(\d+)$/;
1155 } elsif ($rule_env eq 'ct') {
1156 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1157 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1161 if ($rule->{macro}) {
1162 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1163 $rule->{macro} = $preferred_name;
1165 &$add_error('macro', "unknown macro '$rule->{macro}'");
1169 if ($rule->{proto
}) {
1170 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1171 &$add_error('proto', $@) if $@;
1174 if ($rule->{dport
}) {
1175 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1176 &$add_error('dport', $@) if $@;
1177 &$add_error('proto', "missing property - 'dport' requires this property")
1181 if ($rule->{sport
}) {
1182 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1183 &$add_error('sport', $@) if $@;
1184 &$add_error('proto', "missing property - 'sport' requires this property")
1190 if ($rule->{source
}) {
1191 eval { $ipversion = parse_address_list
($rule->{source
}); };
1192 &$add_error('source', $@) if $@;
1193 &$check_ipset_or_alias_property('source');
1196 if ($rule->{dest
}) {
1198 my $dest_ipversion = parse_address_list
($rule->{dest
});
1199 die "detected mixed ipv4/ipv6 adresses in rule\n"
1200 if defined($ipversion) && ($dest_ipversion != $ipversion);
1201 $ipversion = $dest_ipversion;
1203 &$add_error('dest', $@) if $@;
1204 &$check_ipset_or_alias_property('dest');
1207 if ($rule->{macro} && !$error_count) {
1208 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1210 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1211 my $eh = $err->{errors
};
1212 foreach my $p (keys %$eh) {
1213 &$add_error($p, $eh->{$p});
1216 &$add_error('macro', "$err");
1221 $rule->{errors
} = $errors if $error_count;
1222 $rule->{ipversion
} = $ipversion if $ipversion;
1227 sub copy_rule_data
{
1228 my ($rule, $param) = @_;
1230 foreach my $k (keys %$rule_properties) {
1231 if (defined(my $v = $param->{$k})) {
1232 if ($v eq '' || $v eq '-') {
1243 sub rules_modify_permissions
{
1244 my ($rule_env) = @_;
1246 if ($rule_env eq 'host') {
1248 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1250 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1252 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1254 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1256 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1263 sub rules_audit_permissions
{
1264 my ($rule_env) = @_;
1266 if ($rule_env eq 'host') {
1268 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1270 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1272 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1274 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1276 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1284 my $bridge_firewall_enabled = 0;
1286 sub enable_bridge_firewall
{
1288 return if $bridge_firewall_enabled; # only once
1290 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1291 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1293 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1294 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1296 $bridge_firewall_enabled = 1;
1299 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1301 sub iptables_restore_cmdlist
{
1304 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1307 sub ipset_restore_cmdlist
{
1310 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1313 sub iptables_get_chains
{
1317 # check what chains we want to track
1318 my $is_pvefw_chain = sub {
1321 return 1 if $name =~ m/^PVEFW-\S+$/;
1323 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1325 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1327 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1329 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1330 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1342 return if $line =~ m/^#/;
1343 return if $line =~ m/^\s*$/;
1345 if ($line =~ m/^\*(\S+)$/) {
1350 return if $table ne 'filter';
1352 if ($line =~ m/^:(\S+)\s/) {
1354 return if !&$is_pvefw_chain($chain);
1355 $res->{$chain} = "unknown";
1356 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1357 my ($chain, $sig) = ($1, $2);
1358 return if !&$is_pvefw_chain($chain);
1359 $res->{$chain} = $sig;
1360 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1363 # simply ignore the rest
1368 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1370 return wantarray ?
($res, $hooks) : $res;
1373 sub iptables_chain_digest
{
1375 my $digest = Digest
::SHA-
>new('sha1');
1376 foreach my $rule (@$rules) { # order is important
1377 $digest->add($rule);
1379 return $digest->b64digest;
1382 sub ipset_chain_digest
{
1385 my $digest = Digest
::SHA-
>new('sha1');
1386 foreach my $rule (sort @$rules) { # note: sorted
1387 $digest->add($rule);
1389 return $digest->b64digest;
1392 sub ipset_get_chains
{
1400 return if $line =~ m/^#/;
1401 return if $line =~ m/^\s*$/;
1402 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1404 $line =~ s/\s+$//; # delete trailing white space
1405 push @{$chains->{$chain}}, $line;
1407 # simply ignore the rest
1412 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1414 # compute digest for each chain
1415 foreach my $chain (keys %$chains) {
1416 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1422 sub ruleset_generate_cmdstr
{
1423 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1425 return if defined($rule->{enable
}) && !$rule->{enable
};
1426 return if $rule->{errors
};
1428 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1430 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1431 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1435 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1436 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1438 my $source = $rule->{source
};
1439 my $dest = $rule->{dest
};
1442 if ($source =~ m/^\+/) {
1443 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1445 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1446 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1447 push @cmd, "-m set --match-set ${ipset_chain} src";
1448 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1449 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1450 push @cmd, "-m set --match-set ${ipset_chain} src";
1452 die "no such ipset '$name'\n";
1455 die "invalid security group name '$source'\n";
1457 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1458 my $alias = lc($source);
1459 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1460 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1461 die "no such alias '$source'\n" if !$e;
1462 push @cmd, "-s $e->{cidr}";
1463 } elsif ($source =~ m/\-/){
1464 push @cmd, "-m iprange --src-range $source";
1466 push @cmd, "-s $source";
1471 if ($dest =~ m/^\+/) {
1472 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1474 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1475 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1476 push @cmd, "-m set --match-set ${ipset_chain} dst";
1477 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1478 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1479 push @cmd, "-m set --match-set ${ipset_chain} dst";
1481 die "no such ipset '$name'\n";
1484 die "invalid security group name '$dest'\n";
1486 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1487 my $alias = lc($dest);
1488 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1489 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1490 die "no such alias '$dest'\n" if !$e;
1491 push @cmd, "-d $e->{cidr}";
1492 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1493 push @cmd, "-m iprange --dst-range $dest";
1495 push @cmd, "-d $dest";
1499 if ($rule->{proto
}) {
1500 push @cmd, "-p $rule->{proto}";
1503 $multiport++ if $nbdport > 1;
1504 $multiport++ if $nbsport > 1;
1506 push @cmd, "--match multiport" if $multiport;
1508 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1509 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1511 if ($rule->{dport
}) {
1512 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1513 # Note: we use dport to store --icmp-type
1514 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1515 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1518 if ($multiport == 2) {
1519 push @cmd, "--ports $rule->{dport}";
1521 push @cmd, "--dports $rule->{dport}";
1524 push @cmd, "--dport $rule->{dport}";
1529 if ($rule->{sport
}) {
1531 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1533 push @cmd, "--sport $rule->{sport}";
1536 } elsif ($rule->{dport
} || $rule->{sport
}) {
1537 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1538 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1541 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1543 if (my $action = $rule->{action
}) {
1544 $action = $actions->{$action} if defined($actions->{$action});
1545 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1546 push @cmd, $goto ?
"-g $action" : "-j $action";
1549 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1552 sub ruleset_generate_rule
{
1553 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1557 if ($rule->{macro}) {
1558 $rules = &$apply_macro($rule->{macro}, $rule);
1563 # update all or nothing
1566 foreach my $tmp (@$rules) {
1567 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1568 push @cmds, $cmdstr;
1572 foreach my $cmdstr (@cmds) {
1573 ruleset_addrule
($ruleset, $chain, $cmdstr);
1577 sub ruleset_generate_rule_insert
{
1578 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1580 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1582 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1583 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1587 sub ruleset_create_chain
{
1588 my ($ruleset, $chain) = @_;
1590 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1591 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1593 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1595 $ruleset->{$chain} = [];
1598 sub ruleset_chain_exist
{
1599 my ($ruleset, $chain) = @_;
1601 return $ruleset->{$chain} ?
1 : undef;
1604 sub ruleset_addrule
{
1605 my ($ruleset, $chain, $rule) = @_;
1607 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1609 push @{$ruleset->{$chain}}, "-A $chain $rule";
1612 sub ruleset_insertrule
{
1613 my ($ruleset, $chain, $rule) = @_;
1615 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1617 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1620 sub get_log_rule_base
{
1621 my ($chain, $vmid, $msg, $loglevel) = @_;
1623 die "internal error - no log level" if !defined($loglevel);
1625 $vmid = 0 if !defined($vmid);
1627 # Note: we use special format for prefix to pass further
1628 # info to log daemon (VMID, LOGVELEL and CHAIN)
1630 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1633 sub ruleset_addlog {
1634 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1636 return if !defined($loglevel);
1638 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1640 $logrule = "$rule $logrule" if defined($rule);
1642 ruleset_addrule($ruleset, $chain, $logrule);
1645 sub ruleset_add_chain_policy {
1646 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1648 if ($policy eq 'ACCEPT') {
1650 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1651 { ACCEPT => $accept_action});
1653 } elsif ($policy eq 'DROP') {
1655 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1657 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1659 ruleset_addrule($ruleset, $chain, "-j DROP
");
1660 } elsif ($policy eq 'REJECT') {
1661 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1663 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1665 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1668 die "internal error
: unknown policy
'$policy'";
1672 sub ruleset_chain_add_conn_filters {
1673 my ($ruleset, $chain, $accept) = @_;
1675 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1676 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1679 sub ruleset_chain_add_input_filters {
1680 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1682 if ($cluster_conf->{ipset}->{blacklist}){
1683 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1684 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1685 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1686 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1688 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1689 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1692 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1693 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1696 if ($options->{tcpflags}) {
1697 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1701 sub ruleset_create_vm_chain {
1702 my ($ruleset, $chain, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1704 ruleset_create_chain($ruleset, $chain);
1705 my $accept = generate_nfqueue($options);
1707 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1708 if ($direction eq 'OUT') {
1709 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1710 proto => 'udp', sport => 68, dport => 67 });
1712 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1713 proto => 'udp', sport => 67, dport => 68 });
1717 if ($direction eq 'OUT') {
1718 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1719 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1721 if ($ipfilter_ipset) {
1722 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
1724 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1728 sub ruleset_add_group_rule {
1729 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1731 my $group = $rule->{action};
1732 my $group_chain = "GROUP-
$group-$direction";
1733 if(!ruleset_chain_exist($ruleset, $group_chain)){
1734 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1737 if ($direction eq 'OUT' && $rule->{iface_out}) {
1738 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1739 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1740 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1742 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1745 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1748 sub ruleset_generate_vm_rules {
1749 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
1751 my $lc_direction = lc($direction);
1753 my $in_accept = generate_nfqueue($options);
1755 foreach my $rule (@$rules) {
1756 next if $rule->{iface} && $rule->{iface} ne $netid;
1757 next if !$rule->{enable} || $rule->{errors};
1758 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
1760 if ($rule->{type} eq 'group') {
1761 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1762 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
1764 next if $rule->{type} ne $lc_direction;
1766 if ($direction eq 'OUT') {
1767 ruleset_generate_rule($ruleset, $chain, $rule,
1768 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1769 undef, $cluster_conf, $vmfw_conf);
1771 ruleset_generate_rule($ruleset, $chain, $rule,
1772 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1773 undef, $cluster_conf, $vmfw_conf);
1781 sub generate_nfqueue {
1784 if ($options->{ips}) {
1785 my $action = "NFQUEUE
";
1786 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1787 if (defined($3) && defined($1)) {
1788 $action .= " --queue-balance
$1:$3";
1789 } elsif (defined($1)) {
1790 $action .= " --queue-num
$1";
1793 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1800 sub ruleset_generate_vm_ipsrules {
1801 my ($ruleset, $options, $direction, $iface) = @_;
1803 if ($options->{ips} && $direction eq 'IN') {
1804 my $nfqueue = generate_nfqueue($options);
1806 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1807 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1810 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1814 sub generate_venet_rules_direction {
1815 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction, $ipversion) = @_;
1817 my $lc_direction = lc($direction);
1819 my $rules = $vmfw_conf->{rules};
1821 my $options = $vmfw_conf->{options};
1822 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1824 my $chain = "venet0-
$vmid-$direction";
1826 ruleset_create_vm_chain($ruleset, $chain, $options, undef, undef, $direction);
1828 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction, undef, $ipversion);
1833 if ($direction eq 'OUT') {
1834 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1836 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1839 my $accept = generate_nfqueue($options);
1840 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1841 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1843 if ($direction eq 'OUT') {
1844 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1847 iface_in => 'venet0'});
1849 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1852 iface_out => 'venet0'});
1856 sub generate_tap_rules_direction {
1857 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
1859 my $lc_direction = lc($direction);
1861 my $rules = $vmfw_conf->{rules};
1863 my $options = $vmfw_conf->{options};
1864 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1866 my $tapchain = "$iface-$direction";
1868 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
1869 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name)
1870 if $vmfw_conf->{ipset}->{$ipfilter_name};
1872 # create chain with mac and ip filter
1873 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $ipfilter_ipset, $direction);
1875 if ($options->{enable}) {
1876 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
1878 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1883 if ($direction eq 'OUT') {
1884 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1886 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1889 my $accept = generate_nfqueue($options);
1890 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1891 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1893 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
1894 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, 'ACCEPT', $loglevel, $accept_action);
1897 # plug the tap chain to bridge chain
1898 if ($direction eq 'IN') {
1899 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
1900 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1902 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
1903 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
1907 sub enable_host_firewall {
1908 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
1910 my $options = $hostfw_conf->{options};
1911 my $cluster_options = $cluster_conf->{options};
1912 my $rules = $hostfw_conf->{rules};
1913 my $cluster_rules = $cluster_conf->{rules};
1915 # host inbound firewall
1916 my $chain = "PVEFW-HOST-IN
";
1917 ruleset_create_chain($ruleset, $chain);
1919 my $loglevel = get_option_log_level($options, "log_level_in
");
1921 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1923 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1924 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1926 # we use RETURN because we need to check also tap rules
1927 my $accept_action = 'RETURN';
1929 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1931 # add host rules first, so that cluster wide rules can be overwritten
1932 foreach my $rule (@$rules, @$cluster_rules) {
1933 next if !$rule->{enable} || $rule->{errors};
1935 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1938 if ($rule->{type} eq 'group') {
1939 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
1940 } elsif ($rule->{type} eq 'in') {
1941 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1942 undef, $cluster_conf, $hostfw_conf);
1946 delete $rule->{iface_in};
1949 # allow standard traffic for management ipset (includes cluster network)
1950 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
");
1951 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
1952 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1953 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1954 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1955 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
1957 my $localnet = local_network();
1961 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1962 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
1963 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
1966 # implement input policy
1967 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1968 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1970 # host outbound firewall
1971 $chain = "PVEFW-HOST-OUT
";
1972 ruleset_create_chain($ruleset, $chain);
1974 $loglevel = get_option_log_level($options, "log_level_out
");
1976 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1978 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1980 # we use RETURN because we may want to check other thigs later
1981 $accept_action = 'RETURN';
1983 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1985 # add host rules first, so that cluster wide rules can be overwritten
1986 foreach my $rule (@$rules, @$cluster_rules) {
1987 next if !$rule->{enable} || $rule->{errors};
1989 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1991 if ($rule->{type} eq 'group') {
1992 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
1993 } elsif ($rule->{type} eq 'out') {
1994 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1995 undef, $cluster_conf, $hostfw_conf);
1999 delete $rule->{iface_out};
2002 # allow standard traffic on cluster network
2004 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2005 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2006 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2007 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2009 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2010 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2011 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2014 # implement output policy
2015 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2016 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
2018 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2019 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2022 sub generate_group_rules {
2023 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2025 my $rules = $cluster_conf->{groups}->{$group};
2028 warn "no such security group
'$group'\n";
2029 $rules = []; # create empty chain
2032 my $chain = "GROUP-
${group
}-IN
";
2034 ruleset_create_chain($ruleset, $chain);
2035 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2037 foreach my $rule (@$rules) {
2038 next if $rule->{type} ne 'in';
2039 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2040 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
2043 $chain = "GROUP-
${group
}-OUT
";
2045 ruleset_create_chain($ruleset, $chain);
2046 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2048 foreach my $rule (@$rules) {
2049 next if $rule->{type} ne 'out';
2050 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2051 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2052 # check also other tap rules later
2053 ruleset_generate_rule($ruleset, $chain, $rule,
2054 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
2059 my $valid_netdev_names = {};
2060 for (my $i = 0; $i < $MAX_NETS; $i++) {
2061 $valid_netdev_names->{"net
$i"} = 1;
2065 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2067 my $orig_line = $line;
2071 # we can add single line comments to the end of the rule
2072 if ($line =~ s/#\s*(.*?)\s*$//) {
2073 $rule->{comment} = decode('utf8', $1);
2076 # we can disable a rule when prefixed with '|'
2078 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2080 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2081 die "unable to parse rule
: $line\n";
2083 $rule->{type} = lc($1);
2084 $rule->{action} = $2;
2086 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2087 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2088 $rule->{macro} = $1;
2089 $rule->{action} = $2;
2093 while (length($line)) {
2094 if ($line =~ s/^-i (\S+)\s*//) {
2095 $rule->{iface} = $1;
2099 last if $rule->{type} eq 'group';
2101 if ($line =~ s/^-p (\S+)\s*//) {
2102 $rule->{proto} = $1;
2106 if ($line =~ s/^-dport (\S+)\s*//) {
2107 $rule->{dport} = $1;
2111 if ($line =~ s/^-sport (\S+)\s*//) {
2112 $rule->{sport} = $1;
2115 if ($line =~ s/^-source (\S+)\s*//) {
2116 $rule->{source} = $1;
2119 if ($line =~ s/^-dest (\S+)\s*//) {
2127 die "unable to parse rule parameters
: $line\n" if length($line);
2129 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2130 if ($verbose && $rule->{errors}) {
2131 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2132 foreach my $p (keys %{$rule->{errors}}) {
2133 warn " $p: $rule->{errors
}->{$p}\n";
2140 sub parse_vmfw_option {
2145 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2147 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2150 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2152 $value = $2 ? lc($3) : '';
2153 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2156 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2160 die "can
't parse option '$line'\n"
2163 return ($opt, $value);
2166 sub parse_hostfw_option {
2171 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2173 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2176 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2178 $value = $2 ? lc($3) : '';
2179 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2183 die "can't parse option
'$line'\n"
2186 return ($opt, $value);
2189 sub parse_clusterfw_option {
2194 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2197 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2201 die "can
't parse option '$line'\n"
2204 return ($opt, $value);
2208 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2210 if ($cidr !~ m/^\d/) {
2211 my $alias = lc($cidr);
2212 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2213 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2214 return $e->{cidr} if $e;
2216 die "no such alias '$cidr'\n";
2225 # we can add single line comments to the end of the line
2226 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2228 if ($line =~ m/^(\S+)\s(\S+)$/) {
2229 my ($name, $cidr) = ($1, $2);
2232 pve_verify_ipv4_or_cidr($cidr);
2233 my $ipversion = get_ip_version($cidr);
2237 ipversion => $ipversion,
2239 $data->{comment} = $comment if $comment;
2246 sub get_ip_version {
2249 my $ipversion = undef;
2251 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2253 }elsif ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2260 sub generic_fw_config_parser {
2261 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2266 my $res = $empty_conf;
2268 while (defined(my $line = <$fh>)) {
2269 next if $line =~ m/^#/;
2270 next if $line =~ m/^\s*$/;
2274 my $linenr = $fh->input_line_number();
2275 my $prefix = "$filename (line $linenr)";
2277 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2278 $section = 'options
';
2282 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2283 $section = 'aliases
';
2287 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2288 $section = 'groups
';
2292 die "security group name too long\n" if length($group) > $max_group_name_length;
2293 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2296 ($section, $group, $comment) = undef;
2297 warn "$prefix: $err";
2301 $res->{$section}->{$group} = [];
2302 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2307 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2312 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2317 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2318 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2321 ($section, $group, $comment) = undef;
2322 warn "$prefix: $err";
2326 $res->{$section}->{$group} = [];
2327 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2333 warn "$prefix: skip line - no section\n";
2337 if ($section eq 'options
') {
2340 if ($rule_env eq 'cluster
') {
2341 ($opt, $value) = parse_clusterfw_option($line);
2342 } elsif ($rule_env eq 'host
') {
2343 ($opt, $value) = parse_hostfw_option($line);
2345 ($opt, $value) = parse_vmfw_option($line);
2347 $res->{options}->{$opt} = $value;
2349 warn "$prefix: $@" if $@;
2350 } elsif ($section eq 'aliases
') {
2352 my $data = parse_alias($line);
2353 $res->{aliases}->{lc($data->{name})} = $data;
2355 warn "$prefix: $@" if $@;
2356 } elsif ($section eq 'rules
') {
2358 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2360 warn "$prefix: $err";
2363 push @{$res->{$section}}, $rule;
2364 } elsif ($section eq 'groups
') {
2366 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2368 warn "$prefix: $err";
2371 push @{$res->{$section}->{$group}}, $rule;
2372 } elsif ($section eq 'ipset
') {
2373 # we can add single line comments to the end of the rule
2374 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2376 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2381 if ($nomatch && !$feature_ipset_nomatch) {
2382 $errors->{nomatch} = "nomatch not supported by kernel";
2386 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2387 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2390 pve_verify_ipv4_or_cidr_or_alias($cidr);
2395 $errors->{cidr} = $err;
2398 my $entry = { cidr => $cidr };
2399 $entry->{nomatch} = 1 if $nomatch;
2400 $entry->{comment} = $comment if $comment;
2401 $entry->{errors} = $errors if $errors;
2403 if ($verbose && $errors) {
2404 warn "$prefix - errors in ipset '$group': $line\n";
2405 foreach my $p (keys %{$errors}) {
2406 warn " $p: $errors->{$p}\n";
2410 push @{$res->{$section}->{$group}}, $entry;
2412 warn "$prefix: skip line - unknown section\n";
2420 sub parse_hostfw_config {
2421 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2423 my $empty_conf = { rules => [], options => {}};
2425 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2428 sub parse_vmfw_config {
2429 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2436 ipset_comments => {},
2439 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2442 sub parse_clusterfw_config {
2443 my ($filename, $fh, $verbose) = @_;
2453 group_comments => {},
2455 ipset_comments => {},
2458 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2462 my ($code, @param) = @_;
2466 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2473 sub read_local_vm_config {
2478 my $vmdata = { openvz => $openvz, qemu => $qemu };
2480 my $vmlist = PVE::Cluster::get_vmlist();
2481 return $vmdata if !$vmlist || !$vmlist->{ids};
2482 my $ids = $vmlist->{ids};
2484 foreach my $vmid (keys %$ids) {
2485 next if !$vmid; # skip VE0
2486 my $d = $ids->{$vmid};
2487 next if !$d->{node} || $d->{node} ne $nodename;
2488 next if !$d->{type};
2489 if ($d->{type} eq 'openvz
') {
2490 if ($have_pve_manager) {
2491 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2492 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2493 $openvz->{$vmid} = $conf;
2496 } elsif ($d->{type} eq 'qemu
') {
2497 if ($have_qemu_server) {
2498 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2499 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2500 $qemu->{$vmid} = $conf;
2509 sub load_vmfw_conf {
2510 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2514 $dir = $pvefw_conf_dir if !defined($dir);
2516 my $filename = "$dir/$vmid.fw";
2517 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2518 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2519 $vmfw_conf->{vmid} = $vmid;
2525 my $format_rules = sub {
2526 my ($rules, $allow_iface) = @_;
2530 foreach my $rule (@$rules) {
2531 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2532 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2533 $raw .= uc($rule->{type});
2534 if ($rule->{macro}) {
2535 $raw .= " $rule->{macro}($rule->{action})";
2537 $raw .= " " . $rule->{action};
2539 if ($allow_iface && $rule->{iface}) {
2540 $raw .= " -i $rule->{iface}";
2543 if ($rule->{type} ne 'group
') {
2544 $raw .= " -source $rule->{source}" if $rule->{source};
2545 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2546 $raw .= " -p $rule->{proto}" if $rule->{proto};
2547 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2548 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2551 $raw .= " # " . encode('utf8
', $rule->{comment})
2552 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2555 die "unknown rule type '$rule->{type
}'";
2562 my $format_options = sub {
2567 $raw .= "[OPTIONS]\n\n";
2568 foreach my $opt (keys %$options) {
2569 $raw .= "$opt: $options->{$opt}\n";
2576 my $format_aliases = sub {
2581 $raw .= "[ALIASES]\n\n";
2582 foreach my $k (keys %$aliases) {
2583 my $e = $aliases->{$k};
2584 $raw .= "$e->{name} $e->{cidr}";
2585 $raw .= " # " . encode('utf8
', $e->{comment})
2586 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2594 my $format_ipsets = sub {
2599 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2600 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2601 my $utf8comment = encode('utf8
', $comment);
2602 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2604 $raw .= "[IPSET $ipset]\n\n";
2606 my $options = $fw_conf->{ipset}->{$ipset};
2609 foreach my $entry (@$options) {
2610 $nethash->{$entry->{cidr}} = $entry;
2613 foreach my $cidr (sort keys %$nethash) {
2614 my $entry = $nethash->{$cidr};
2615 my $line = $entry->{nomatch} ? '!' : '';
2616 $line .= $entry->{cidr};
2617 $line .= " # " . encode('utf8
', $entry->{comment})
2618 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2628 sub save_vmfw_conf {
2629 my ($vmid, $vmfw_conf) = @_;
2633 my $options = $vmfw_conf->{options};
2634 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2636 my $aliases = $vmfw_conf->{aliases};
2637 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2639 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2641 my $rules = $vmfw_conf->{rules} || [];
2642 if ($rules && scalar(@$rules)) {
2643 $raw .= "[RULES]\n\n";
2644 $raw .= &$format_rules($rules, 1);
2648 mkdir $pvefw_conf_dir;
2650 my $filename = "$pvefw_conf_dir/$vmid.fw";
2651 PVE::Tools::file_set_contents($filename, $raw);
2654 sub read_vm_firewall_configs {
2655 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2657 my $vmfw_configs = {};
2659 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2660 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2661 next if !$vmfw_conf->{options}; # skip if file does not exists
2662 $vmfw_configs->{$vmid} = $vmfw_conf;
2664 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2665 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2666 next if !$vmfw_conf->{options}; # skip if file does not exists
2667 $vmfw_configs->{$vmid} = $vmfw_conf;
2670 return $vmfw_configs;
2673 sub get_option_log_level {
2674 my ($options, $k) = @_;
2676 my $v = $options->{$k};
2677 $v = $default_log_level if !defined($v);
2679 return undef if $v eq '' || $v eq 'nolog
';
2681 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2683 return $v if ($v >= 0) && ($v <= 7);
2685 warn "unknown log level ($k = '$v')\n";
2690 sub generate_std_chains {
2691 my ($ruleset, $options, $ipversion) = @_;
2693 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2695 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2699 if ($ipversion == 4) {
2700 # same as shorewall smurflog.
2701 $chain = 'PVEFW-smurflog
';
2702 $std_chains->{$chain} = [];
2704 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2705 push @{$std_chains->{$chain}}, "-j DROP";
2708 # same as shorewall logflags action.
2709 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2710 $chain = 'PVEFW-logflags
';
2711 $std_chains->{$chain} = [];
2713 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2714 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2715 push @{$std_chains->{$chain}}, "-j DROP";
2717 foreach my $chain (keys %$std_chains) {
2718 ruleset_create_chain($ruleset, $chain);
2719 foreach my $rule (@{$std_chains->{$chain}}) {
2721 ruleset_generate_rule($ruleset, $chain, $rule);
2723 ruleset_addrule($ruleset, $chain, $rule);
2729 sub generate_ipset_chains {
2730 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2732 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2733 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2734 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2738 sub generate_ipset {
2739 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2741 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2743 my $hashsize = scalar(@$options);
2744 if ($hashsize <= 64) {
2747 $hashsize = round_powerof2($hashsize);
2750 $ipset_ruleset->{$name} = ["create $name hash:net family inet hashsize $hashsize maxelem $hashsize"];
2754 foreach my $entry (@$options) {
2755 next if $entry->{errors}; # skip entries with errors
2757 my $cidr = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2758 $nethash->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2763 foreach my $cidr (sort keys %$nethash) {
2764 my $entry = $nethash->{$cidr};
2766 my $cmd = "add $name $cidr";
2767 if ($entry->{nomatch}) {
2768 if ($feature_ipset_nomatch) {
2769 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2771 warn "ignore !$cidr - nomatch not supported by kernel\n";
2774 push @{$ipset_ruleset->{$name}}, $cmd;
2779 sub round_powerof2 {
2783 $int |= $int >> $_ foreach (1,2,4,8,16);
2787 sub load_clusterfw_conf {
2788 my ($filename, $verbose) = @_;
2790 $filename = $clusterfw_conf_filename if !defined($filename);
2792 my $cluster_conf = {};
2793 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2794 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
2797 return $cluster_conf;
2800 sub save_clusterfw_conf {
2801 my ($cluster_conf) = @_;
2805 my $options = $cluster_conf->{options};
2806 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2808 my $aliases = $cluster_conf->{aliases};
2809 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2811 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
2813 my $rules = $cluster_conf->{rules};
2814 if ($rules && scalar(@$rules)) {
2815 $raw .= "[RULES]\n\n";
2816 $raw .= &$format_rules($rules, 1);
2820 if ($cluster_conf->{groups}) {
2821 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2822 my $rules = $cluster_conf->{groups}->{$group};
2823 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2824 my $utf8comment = encode('utf8
', $comment);
2825 $raw .= "[group $group] # $utf8comment\n\n";
2827 $raw .= "[group $group]\n\n";
2830 $raw .= &$format_rules($rules, 0);
2835 mkdir $pvefw_conf_dir;
2836 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2839 sub load_hostfw_conf {
2840 my ($cluster_conf, $filename, $verbose) = @_;
2842 $filename = $hostfw_conf_filename if !defined($filename);
2844 my $hostfw_conf = {};
2845 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2846 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
2848 return $hostfw_conf;
2851 sub save_hostfw_conf {
2852 my ($hostfw_conf) = @_;
2856 my $options = $hostfw_conf->{options};
2857 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2859 my $rules = $hostfw_conf->{rules};
2860 if ($rules && scalar(@$rules)) {
2861 $raw .= "[RULES]\n\n";
2862 $raw .= &$format_rules($rules, 1);
2866 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2870 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
2874 if ($vmdata) { # test mode
2875 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2876 my $filename = "$testdir/cluster.fw";
2877 $cluster_conf = load_clusterfw_conf($filename, $verbose);
2879 $filename = "$testdir/host.fw";
2880 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
2882 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
2883 } else { # normal operation
2884 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
2886 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
2888 $vmdata = read_local_vm_config();
2889 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
2892 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
2893 return ($ruleset, $ipset_ruleset);
2896 sub compile_iptables_filter {
2897 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
2899 $cluster_conf->{ipset}->{venet0} = [];
2900 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
2903 if ($cluster_conf->{aliases}->{local_network}) {
2904 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2906 $localnet = local_network() || '127.0.0.0/8';
2907 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2910 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
2912 return ({}, {}) if !$cluster_conf->{options}->{enable};
2916 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2917 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2919 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2921 my $hostfw_options = $hostfw_conf->{options} || {};
2923 # fixme: what log level should we use here?
2924 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2926 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2929 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2930 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2931 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2933 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2934 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2936 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2938 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2939 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2941 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2942 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2944 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2946 generate_std_chains($ruleset, $hostfw_options, $ipversion);
2948 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2950 my $ipset_ruleset = {};
2952 # currently pveproxy don't works with ipv6
, so let
's generate host fw ipv4 only for the moment
2953 if ($hostfw_enable && ($ipversion == 4)) {
2954 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
2955 warn $@ if $@; # just to be sure - should not happen
2958 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2960 # generate firewall rules for QEMU VMs
2961 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2963 my $conf = $vmdata->{qemu}->{$vmid};
2964 my $vmfw_conf = $vmfw_configs->{$vmid};
2965 return if !$vmfw_conf;
2967 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2969 foreach my $netid (keys %$conf) {
2970 next if $netid !~ m/^net(\d+)$/;
2971 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2972 next if !$net->{firewall};
2973 my $iface = "tap${vmid}i$1";
2975 my $macaddr = $net->{macaddr};
2976 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2977 $vmfw_conf, $vmid, 'IN
', $ipversion);
2978 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2979 $vmfw_conf, $vmid, 'OUT
', $ipversion);
2982 warn $@ if $@; # just to be sure - should not happen
2985 # generate firewall rules for OpenVZ containers
2986 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2988 my $conf = $vmdata->{openvz}->{$vmid};
2990 my $vmfw_conf = $vmfw_configs->{$vmid};
2991 return if !$vmfw_conf;
2993 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2995 if ($vmfw_conf->{options}->{enable}) {
2996 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2997 my $ip = $conf->{ip_address}->{value};
3002 foreach my $singleip (split(',', $ip)) {
3003 my $singleip_ver = parse_address_list($singleip); # make sure we have a valid $ip list
3004 push @{$cluster_conf->{ipset}->{venet0}}, { cidr => $singleip };
3005 push @ips, $singleip if $singleip_ver == $ipversion;
3009 my $ip_list = join(',', @ips);
3010 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'IN
', $ipversion);
3011 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'OUT
', $ipversion);
3016 if ($conf->{netif} && $conf->{netif}->{value}) {
3017 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
3018 foreach my $netid (keys %$netif) {
3019 my $d = $netif->{$netid};
3020 my $bridge = $d->{bridge};
3021 next if !$bridge || $bridge !~ m/^vmbr\d+(v(\d+))?f$/; # firewall enabled ?
3022 my $macaddr = $d->{mac};
3023 my $iface = $d->{host_ifname};
3024 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3025 $vmfw_conf, $vmid, 'IN
', $ipversion);
3026 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3027 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3031 warn $@ if $@; # just to be sure - should not happen
3034 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3035 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3038 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
3040 return ($ruleset, $ipset_ruleset);
3043 sub get_ruleset_status {
3044 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3046 my $statushash = {};
3048 foreach my $chain (sort keys %$ruleset) {
3049 my $sig = &$digest_fn($ruleset->{$chain});
3051 $statushash->{$chain}->{sig} = $sig;
3053 my $oldsig = $active_chains->{$chain};
3054 if (!defined($oldsig)) {
3055 $statushash->{$chain}->{action} = 'create
';
3057 if ($oldsig eq $sig) {
3058 $statushash->{$chain}->{action} = 'exists';
3060 $statushash->{$chain}->{action} = 'update
';
3063 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3064 foreach my $cmd (@{$ruleset->{$chain}}) {
3065 print "\t$cmd\n" if $verbose;
3069 foreach my $chain (sort keys %$active_chains) {
3070 if (!defined($ruleset->{$chain})) {
3071 my $sig = $active_chains->{$chain};
3072 $statushash->{$chain}->{action} = 'delete';
3073 $statushash->{$chain}->{sig} = $sig;
3074 print "delete $chain ($sig)\n" if $verbose;
3081 sub print_sig_rule {
3082 my ($chain, $sig) = @_;
3084 # We just use this to store a SHA1 checksum used to detect changes
3085 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3088 sub get_ruleset_cmdlist {
3089 my ($ruleset, $verbose) = @_;
3091 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3093 my ($active_chains, $hooks) = iptables_get_chains();
3094 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3096 # create missing chains first
3097 foreach my $chain (sort keys %$ruleset) {
3098 my $stat = $statushash->{$chain};
3099 die "internal error" if !$stat;
3100 next if $stat->{action} ne 'create
';
3102 $cmdlist .= ":$chain - [0:0]\n";
3105 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3106 my $chain = "PVEFW-$h";
3107 if ($ruleset->{$chain} && !$hooks->{$h}) {
3108 $cmdlist .= "-A $h -j $chain\n";
3112 foreach my $chain (sort keys %$ruleset) {
3113 my $stat = $statushash->{$chain};
3114 die "internal error" if !$stat;
3116 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3117 $cmdlist .= "-F $chain\n";
3118 foreach my $cmd (@{$ruleset->{$chain}}) {
3119 $cmdlist .= "$cmd\n";
3121 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3122 } elsif ($stat->{action
} eq 'delete') {
3123 die "internal error"; # this should not happen
3124 } elsif ($stat->{action
} eq 'exists') {
3127 die "internal error - unknown status '$stat->{action}'";
3131 foreach my $chain (keys %$statushash) {
3132 next if $statushash->{$chain}->{action
} ne 'delete';
3133 $cmdlist .= "-F $chain\n";
3135 foreach my $chain (keys %$statushash) {
3136 next if $statushash->{$chain}->{action
} ne 'delete';
3137 next if $chain eq 'PVEFW-INPUT';
3138 next if $chain eq 'PVEFW-OUTPUT';
3139 next if $chain eq 'PVEFW-FORWARD';
3140 $cmdlist .= "-X $chain\n";
3143 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3145 $cmdlist .= "COMMIT\n";
3147 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3150 sub get_ipset_cmdlist
{
3151 my ($ruleset, $verbose) = @_;
3155 my $delete_cmdlist = "";
3157 my $active_chains = ipset_get_chains
();
3158 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3160 # remove stale _swap chains
3161 foreach my $chain (keys %$active_chains) {
3162 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3163 $cmdlist .= "destroy $chain\n";
3167 foreach my $chain (sort keys %$ruleset) {
3168 my $stat = $statushash->{$chain};
3169 die "internal error" if !$stat;
3171 if ($stat->{action
} eq 'create') {
3172 foreach my $cmd (@{$ruleset->{$chain}}) {
3173 $cmdlist .= "$cmd\n";
3177 if ($stat->{action
} eq 'update') {
3178 my $chain_swap = $chain."_swap";
3180 foreach my $cmd (@{$ruleset->{$chain}}) {
3181 $cmd =~ s/$chain/$chain_swap/;
3182 $cmdlist .= "$cmd\n";
3184 $cmdlist .= "swap $chain_swap $chain\n";
3185 $cmdlist .= "flush $chain_swap\n";
3186 $cmdlist .= "destroy $chain_swap\n";
3191 foreach my $chain (keys %$statushash) {
3192 next if $statushash->{$chain}->{action
} ne 'delete';
3194 $delete_cmdlist .= "flush $chain\n";
3195 $delete_cmdlist .= "destroy $chain\n";
3198 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3200 return ($cmdlist, $delete_cmdlist, $changes);
3204 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
3206 enable_bridge_firewall
();
3208 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3209 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3211 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3214 if ($ipset_changes) {
3215 print "ipset changes:\n";
3216 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3217 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3221 print "iptables changes:\n";
3226 ipset_restore_cmdlist
($ipset_create_cmdlist);
3228 iptables_restore_cmdlist
($cmdlist);
3230 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3232 # test: re-read status and check if everything is up to date
3233 my $active_chains = iptables_get_chains
();
3234 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3237 foreach my $chain (sort keys %$ruleset) {
3238 my $stat = $statushash->{$chain};
3239 if ($stat->{action
} ne 'exists') {
3240 warn "unable to update chain '$chain'\n";
3245 die "unable to apply firewall changes\n" if $errors;
3247 update_nf_conntrack_max
($hostfw_conf);
3249 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3253 sub update_nf_conntrack_max
{
3254 my ($hostfw_conf) = @_;
3256 my $max = 65536; # reasonable default
3258 my $options = $hostfw_conf->{options
} || {};
3260 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3261 $max = $options->{nf_conntrack_max
};
3262 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3265 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3266 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3268 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3270 if ($current != $max) {
3271 my $hashsize = int($max/4);
3272 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3273 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3277 sub update_nf_conntrack_tcp_timeout_established
{
3278 my ($hostfw_conf) = @_;
3280 my $options = $hostfw_conf->{options
} || {};
3282 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3284 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3287 sub remove_pvefw_chains
{
3289 my ($chash, $hooks) = iptables_get_chains
();
3290 my $cmdlist = "*filter\n";
3292 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3294 $cmdlist .= "-D $h -j PVEFW-$h\n";
3298 foreach my $chain (keys %$chash) {
3299 $cmdlist .= "-F $chain\n";
3302 foreach my $chain (keys %$chash) {
3303 $cmdlist .= "-X $chain\n";
3305 $cmdlist .= "COMMIT\n";
3307 iptables_restore_cmdlist
($cmdlist);
3309 my $ipset_chains = ipset_get_chains
();
3313 foreach my $chain (keys %$ipset_chains) {
3314 $cmdlist .= "flush $chain\n";
3315 $cmdlist .= "destroy $chain\n";
3318 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3322 my $cluster_conf = load_clusterfw_conf
();
3323 my $cluster_options = $cluster_conf->{options
};
3324 my $enable = $cluster_options->{enable
};
3328 # load required modules here
3334 my $cluster_conf = load_clusterfw_conf
();
3335 my $cluster_options = $cluster_conf->{options
};
3337 if (!$cluster_options->{enable
}) {
3338 PVE
::Firewall
::remove_pvefw_chains
();
3342 my $hostfw_conf = load_hostfw_conf
();
3344 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3346 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset);