9 use PVE
::Exception
qw(raise raise_param_exc);
10 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
13 use PVE
::Tools
qw($IPV4RE);
18 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
21 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
22 my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw";
24 # dynamically include PVE::QemuServer and PVE::OpenVZ
25 # to avoid dependency problems
28 require PVE
::QemuServer
;
29 $have_qemu_server = 1;
35 $have_pve_manager = 1;
38 PVE
::JSONSchema
::register_format
('IPv4orCIDR', \
&pve_verify_ipv4_or_cidr
);
39 sub pve_verify_ipv4_or_cidr
{
40 my ($cidr, $noerr) = @_;
42 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
43 return $cidr if Net
::IP-
>new($cidr);
44 return undef if $noerr;
45 die Net
::IP
::Error
() . "\n";
47 return undef if $noerr;
48 die "value does not look like a valid IP address or CIDR network\n";
51 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
52 description
=> "IP set name.",
54 pattern
=> '[A-Za-z][A-Za-z0-9\-\_]+',
59 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
60 description
=> "Alias name.",
62 pattern
=> '[A-Za-z][A-Za-z0-9\-\_]+',
67 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
68 description
=> "Log level.",
70 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
74 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
75 my $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
77 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
78 description
=> "Security Group name.",
80 pattern
=> $security_group_name_pattern,
85 my $feature_ipset_nomatch = 0;
87 my (undef, undef, $release) = POSIX
::uname
();
88 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
89 my ($major, $minor) = ($1, $2);
90 $feature_ipset_nomatch = 1 if ($major > 3) ||
91 ($major == 3 && $minor >= 7);
98 my $nodename = PVE
::INotify
::nodename
();
100 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
102 my $default_log_level = 'nolog'; # avoid logs by default
104 my $log_level_hash = {
115 # imported/converted from: /usr/share/shorewall/macro.*
116 my $pve_fw_macros = {
119 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
120 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
123 "Auth (identd) traffic",
124 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
127 "Border Gateway Protocol traffic",
128 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
131 "BitTorrent traffic for BitTorrent 3.1 and earlier",
132 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
133 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
136 "BitTorrent traffic for BitTorrent 3.2 and later",
137 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
138 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
141 "Concurrent Versions System pserver traffic",
142 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
145 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
146 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
147 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
148 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
151 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
152 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
153 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
156 "Distributed Checksum Clearinghouse spam filtering mechanism",
157 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
160 "Forwarded DHCP traffic",
161 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
164 "Domain Name System traffic (upd and tcp)",
165 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
166 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
169 "Distributed Compiler service",
170 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
173 "File Transfer Protocol",
174 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
177 "Finger protocol (RFC 742)",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
181 "GNUnet secure peer-to-peer networking traffic",
182 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
183 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
184 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
185 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
188 "Generic Routing Encapsulation tunneling protocol",
189 { action
=> 'PARAM', proto
=> '47' },
192 "Git distributed revision control traffic",
193 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
196 "OpenPGP HTTP keyserver protocol traffic",
197 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
200 "Hypertext Transfer Protocol (WWW)",
201 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
204 "Hypertext Transfer Protocol (WWW) over SSL",
205 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
208 "Internet Cache Protocol V2 (Squid) traffic",
209 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
212 "AOL Instant Messenger traffic",
213 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
216 "Internet Message Access Protocol",
217 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
220 "Internet Message Access Protocol over SSL",
221 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
224 "IPIP capsulation traffic",
225 { action
=> 'PARAM', proto
=> '94' },
229 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
230 { action
=> 'PARAM', proto
=> '50' },
233 "IPsec authentication (AH) traffic",
234 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
235 { action
=> 'PARAM', proto
=> '51' },
238 "IPsec traffic and Nat-Traversal",
239 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
240 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
241 { action
=> 'PARAM', proto
=> '50' },
244 "Internet Relay Chat traffic",
245 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
248 "HP Jetdirect printing",
249 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
252 "Layer 2 Tunneling Protocol traffic",
253 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
256 "Lightweight Directory Access Protocol traffic",
257 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
260 "Secure Lightweight Directory Access Protocol traffic",
261 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
264 "Microsoft Notification Protocol",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
268 "Microsoft SQL Server",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
272 "Mail traffic (SMTP, SMTPS, Submission)",
273 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
274 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
275 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
278 "Munin networked resource monitoring traffic",
279 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
283 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
286 "NNTP traffic (Usenet).",
287 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
290 "Encrypted NNTP traffic (Usenet)",
291 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
294 "Network Time Protocol (ntpd)",
295 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
298 "OSPF multicast traffic",
299 { action
=> 'PARAM', proto
=> '89' },
303 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
306 "Symantec PCAnywere (tm)",
307 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
308 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
312 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
315 "Encrypted POP3 traffic",
316 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
319 "Point-to-Point Tunneling Protocol",
320 { action
=> 'PARAM', proto
=> '47' },
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
325 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
332 "Line Printer protocol printing",
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
336 "Microsoft Remote Desktop Protocol traffic",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
340 "Routing Information Protocol (bidirectional)",
341 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
344 "BIND remote management protocol",
345 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
348 "Razor Antispam System",
349 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
352 "Remote time retrieval (rdate)",
353 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
357 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
360 "SANE network scanning",
361 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
364 "Microsoft SMB traffic",
365 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
366 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
367 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
368 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
371 "Samba Web Administration Tool",
372 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
375 "Simple Mail Transfer Protocol",
376 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
379 "Encrypted Simple Mail Transfer Protocol",
380 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
383 "Simple Network Management Protocol",
384 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
385 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
388 "Spam Assassin SPAMD traffic",
389 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
392 "Secure shell traffic",
393 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
396 "Subversion server (svnserve)",
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
400 "SixXS IPv6 Deployment and Tunnel Broker",
401 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
402 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
403 { action
=> 'PARAM', proto
=> '41' },
404 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
407 "Squid web proxy traffic",
408 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
411 "Mail message submission traffic",
412 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
415 "Syslog protocol (RFC 5424) traffic",
416 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
417 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
420 "Trivial File Transfer Protocol traffic",
421 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
425 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
432 "RFC 868 Time protocol",
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
436 "Traceroute (for up to 30 hops) traffic",
437 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
438 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
441 "VNC traffic for VNC display's 0 - 99",
442 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
445 "VNC traffic from Vncservers to Vncviewers in listen mode",
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
449 "WWW traffic (HTTP and HTTPS)",
450 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
451 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
454 "Web Cache/Proxy traffic (port 8080)",
455 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
459 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
462 "Whois (nicname, RFC 3912) traffic",
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
467 my $pve_fw_parsed_macros;
468 my $pve_fw_macro_descr;
469 my $pve_fw_preferred_macro_names = {};
471 my $pve_std_chains = {
472 'PVEFW-SET-ACCEPT-MARK' => [
473 "-j MARK --set-mark 1",
475 'PVEFW-DropBroadcast' => [
476 # same as shorewall 'Broadcast'
477 # simply DROP BROADCAST/MULTICAST/ANYCAST
478 # we can use this to reduce logging
479 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
480 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
481 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
482 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
485 # same as shorewall 'reject'
486 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
487 { action
=> 'DROP', source
=> '224.0.0.0/4' },
488 { action
=> 'DROP', proto
=> 'icmp' },
489 "-p tcp -j REJECT --reject-with tcp-reset",
490 "-p udp -j REJECT --reject-with icmp-port-unreachable",
491 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
492 "-j REJECT --reject-with icmp-host-prohibited",
495 # same as shorewall 'Drop', which is equal to DROP,
496 # but REJECT/DROP some packages to reduce logging,
497 # and ACCEPT critical ICMP types
498 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
499 # we are not interested in BROADCAST/MULTICAST/ANYCAST
500 { action
=> 'PVEFW-DropBroadcast' },
501 # ACCEPT critical ICMP types
502 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
503 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
504 # Drop packets with INVALID state
505 "-m conntrack --ctstate INVALID -j DROP",
506 # Drop Microsoft SMB noise
507 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
508 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
509 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
510 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
511 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
512 # Drop new/NotSyn traffic so that it doesn't get logged
513 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
515 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
518 # same as shorewall 'Reject', which is equal to Reject,
519 # but REJECT/DROP some packages to reduce logging,
520 # and ACCEPT critical ICMP types
521 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
522 # we are not interested in BROADCAST/MULTICAST/ANYCAST
523 { action
=> 'PVEFW-DropBroadcast' },
524 # ACCEPT critical ICMP types
525 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
526 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
527 # Drop packets with INVALID state
528 "-m conntrack --ctstate INVALID -j DROP",
529 # Drop Microsoft SMB noise
530 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
531 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
532 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
533 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
534 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
535 # Drop new/NotSyn traffic so that it doesn't get logged
536 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
538 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
540 'PVEFW-tcpflags' => [
541 # same as shorewall tcpflags action.
542 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
543 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
544 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
545 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
546 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
547 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
550 # same as shorewall smurfs action
551 # Filter packets for smurfs (packets with a broadcast address as the source).
552 "-s 0.0.0.0/32 -j RETURN",
553 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
554 "-s 224.0.0.0/4 -g PVEFW-smurflog",
558 # iptables -p icmp -h
559 my $icmp_type_names = {
562 'destination-unreachable' => 1,
563 'network-unreachable' => 1,
564 'host-unreachable' => 1,
565 'protocol-unreachable' => 1,
566 'port-unreachable' => 1,
567 'fragmentation-needed' => 1,
568 'source-route-failed' => 1,
569 'network-unknown' => 1,
571 'network-prohibited' => 1,
572 'host-prohibited' => 1,
573 'TOS-network-unreachable' => 1,
574 'TOS-host-unreachable' => 1,
575 'communication-prohibited' => 1,
576 'host-precedence-violation' => 1,
577 'precedence-cutoff' => 1,
578 'source-quench' => 1,
580 'network-redirect' => 1,
581 'host-redirect' => 1,
582 'TOS-network-redirect' => 1,
583 'TOS-host-redirect' => 1,
585 'router-advertisement' => 1,
586 'router-solicitation' => 1,
587 'time-exceeded' => 1,
588 'ttl-zero-during-transit' => 1,
589 'ttl-zero-during-reassembly' => 1,
590 'parameter-problem' => 1,
591 'ip-header-bad' => 1,
592 'required-option-missing' => 1,
593 'timestamp-request' => 1,
594 'timestamp-reply' => 1,
595 'address-mask-request' => 1,
596 'address-mask-reply' => 1,
599 sub init_firewall_macros
{
601 $pve_fw_parsed_macros = {};
603 foreach my $k (keys %$pve_fw_macros) {
604 my $lc_name = lc($k);
605 my $macro = $pve_fw_macros->{$k};
606 if (!ref($macro->[0])) {
607 $pve_fw_macro_descr->{$k} = shift @$macro;
609 $pve_fw_preferred_macro_names->{$lc_name} = $k;
610 $pve_fw_parsed_macros->{$k} = $macro;
614 init_firewall_macros
();
617 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
622 sub get_etc_services
{
624 return $etc_services if $etc_services;
626 my $filename = "/etc/services";
628 my $fh = IO
::File-
>new($filename, O_RDONLY
);
630 warn "unable to read '$filename' - $!\n";
636 while (my $line = <$fh>) {
638 next if $line =~m/^#/;
639 next if ($line =~m/^\s*$/);
641 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
642 $services->{byid
}->{$2}->{name
} = $1;
643 $services->{byid
}->{$2}->{port
} = $2;
644 $services->{byid
}->{$2}->{$3} = 1;
645 $services->{byname
}->{$1} = $services->{byid
}->{$2};
651 $etc_services = $services;
654 return $etc_services;
659 sub get_etc_protocols
{
660 return $etc_protocols if $etc_protocols;
662 my $filename = "/etc/protocols";
664 my $fh = IO
::File-
>new($filename, O_RDONLY
);
666 warn "unable to read '$filename' - $!\n";
672 while (my $line = <$fh>) {
674 next if $line =~m/^#/;
675 next if ($line =~m/^\s*$/);
677 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
678 $protocols->{byid
}->{$2}->{name
} = $1;
679 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
685 $etc_protocols = $protocols;
687 return $etc_protocols;
690 my $ipv4_mask_hash_clusternet = {
692 '255.255.128.0' => 17,
693 '255.255.192.0' => 18,
694 '255.255.224.0' => 19,
695 '255.255.240.0' => 20,
696 '255.255.248.0' => 21,
697 '255.255.252.0' => 22,
698 '255.255.254.0' => 23,
699 '255.255.255.0' => 24,
700 '255.255.255.128' => 25,
701 '255.255.255.192' => 26,
702 '255.255.255.224' => 27,
703 '255.255.255.240' => 28,
704 '255.255.255.248' => 29,
705 '255.255.255.252' => 30,
710 sub get_cluster_network
{
712 return $cluster_network if defined($cluster_network);
715 my $nodename = PVE
::INotify
::nodename
();
717 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
719 my $testip = Net
::IP-
>new($ip);
721 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
722 foreach my $entry (@$routes) {
723 my $mask = $ipv4_mask_hash_clusternet->{$entry->{mask
}};
724 next if !defined($mask);
725 return if $mask eq '0.0.0.0';
726 my $cidr = "$entry->{dest}/$mask";
727 my $testnet = Net
::IP-
>new($cidr);
728 if ($testnet->overlaps($testip)) {
729 $cluster_network = $cidr;
736 return $cluster_network;
739 sub parse_address_list
{
742 return if $str =~ m/^(\+)(\S+)$/; # ipset ref
743 return if $str =~ m/^${ip_alias_pattern}$/;
747 foreach my $elem (split(/,/, $str)) {
749 if (!Net
::IP-
>new($elem)) {
750 my $err = Net
::IP
::Error
();
751 die "invalid IP address: $err\n";
753 $iprange = 1 if $elem =~ m/-/;
756 die "you can use a range in a list\n" if $iprange && $count > 1;
759 sub parse_port_name_number_or_range
{
762 my $services = PVE
::Firewall
::get_etc_services
();
766 foreach my $item (split(/,/, $str)) {
768 if ($item =~ m/^(\d+):(\d+)$/) {
769 my ($port1, $port2) = ($1, $2);
770 die "invalid port '$port1'\n" if $port1 > 65535;
771 die "invalid port '$port2'\n" if $port2 > 65535;
772 } elsif ($item =~ m/^(\d+)$/) {
774 die "invalid port '$port'\n" if $port > 65535;
776 if ($icmp_type_names->{$item}) {
779 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
784 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
789 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
790 sub pve_fw_verify_port_spec
{
793 parse_port_name_number_or_range
($portstr);
798 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
799 sub pve_fw_verify_v4addr_spec
{
802 parse_address_list
($list);
807 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
808 sub pve_fw_verify_protocol_spec
{
811 my $protocols = get_etc_protocols
();
813 die "unknown protocol '$proto'\n" if $proto &&
814 !(defined($protocols->{byname
}->{$proto}) ||
815 defined($protocols->{byid
}->{$proto}));
821 # helper function for API
823 sub copy_opject_with_digest
{
826 my $sha = Digest
::SHA-
>new('sha1');
829 foreach my $k (sort keys %$object) {
830 my $v = $object->{$k};
831 next if !defined($v);
833 $sha->add($k, ':', $v, "\n");
836 my $digest = $sha->hexdigest;
838 $res->{digest
} = $digest;
840 return wantarray ?
($res, $digest) : $res;
843 sub copy_list_with_digest
{
846 my $sha = Digest
::SHA-
>new('sha1');
849 foreach my $entry (@$list) {
851 foreach my $k (sort keys %$entry) {
852 my $v = $entry->{$k};
853 next if !defined($v);
855 $sha->add($k, ':', $v, "\n");
860 my $digest = $sha->hexdigest;
862 foreach my $entry (@$res) {
863 $entry->{digest
} = $digest;
866 return wantarray ?
($res, $digest) : $res;
869 my $rule_properties = {
871 description
=> "Update rule at position <pos>.",
876 digest
=> get_standard_option
('pve-config-digest'),
880 enum
=> ['in', 'out', 'group'],
883 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
886 pattern
=> $security_group_name_pattern,
895 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
897 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
901 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
905 type
=> 'string', format
=> 'pve-fw-protocol-spec',
913 type
=> 'string', format
=> 'pve-fw-port-spec',
917 type
=> 'string', format
=> 'pve-fw-port-spec',
926 sub add_rule_properties
{
927 my ($properties) = @_;
929 foreach my $k (keys %$rule_properties) {
930 my $h = $rule_properties->{$k};
931 # copy data, so that we can modify later without side effects
932 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
938 sub delete_rule_properties
{
939 my ($rule, $delete_str) = @_;
941 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
942 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
943 if !defined($rule_properties->{$opt});
944 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
945 if $opt eq 'type' || $opt eq 'action';
946 delete $rule->{$opt};
952 my $apply_macro = sub {
953 my ($macro_name, $param, $verify) = @_;
955 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
956 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
960 foreach my $templ (@$macro_rules) {
963 foreach my $k (keys %$templ) {
964 my $v = $templ->{$k};
967 $param_used->{$k} = 1;
968 } elsif ($v eq 'DEST') {
970 $param_used->{dest
} = 1;
971 } elsif ($v eq 'SOURCE') {
972 $v = $param->{source
};
973 $param_used->{source
} = 1;
977 my $msg = "missing parameter '$k' in macro '$macro_name'";
978 raise_param_exc
({ macro => $msg }) if $verify;
983 foreach my $k (keys %$param) {
984 next if $k eq 'macro';
985 next if !defined($param->{$k});
986 next if $param_used->{$k};
987 if (defined($rule->{$k})) {
988 if ($rule->{$k} ne $param->{$k}) {
989 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
990 raise_param_exc
({ $k => $msg }) if $verify;
994 $rule->{$k} = $param->{$k};
1004 my ($rule, $allow_groups) = @_;
1006 my $type = $rule->{type
};
1008 raise_param_exc
({ type
=> "missing property"}) if !$type;
1009 raise_param_exc
({ action
=> "missing property"}) if !$rule->{action
};
1011 if ($type eq 'in' || $type eq 'out') {
1012 raise_param_exc
({ action
=> "unknown action '$rule->{action}'"})
1013 if $rule->{action
} !~ m/^(ACCEPT|DROP|REJECT)$/;
1014 } elsif ($type eq 'group') {
1015 raise_param_exc
({ type
=> "security groups not allowed"})
1017 raise_param_exc
({ action
=> "invalid characters in security group name"})
1018 if $rule->{action
} !~ m/^${security_group_name_pattern}$/;
1020 raise_param_exc
({ type
=> "unknown rule type '$type'"});
1023 if ($rule->{iface
}) {
1024 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1025 raise_param_exc
({ iface
=> $@ }) if $@;
1028 if ($rule->{macro}) {
1029 my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
1030 raise_param_exc
({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
1031 $rule->{macro} = $preferred_name;
1034 if ($rule->{dport
}) {
1035 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1036 raise_param_exc
({ dport
=> $@ }) if $@;
1039 if ($rule->{sport
}) {
1040 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1041 raise_param_exc
({ sport
=> $@ }) if $@;
1044 if ($rule->{source
}) {
1045 eval { parse_address_list
($rule->{source
}); };
1046 raise_param_exc
({ source
=> $@ }) if $@;
1049 if ($rule->{dest
}) {
1050 eval { parse_address_list
($rule->{dest
}); };
1051 raise_param_exc
({ dest
=> $@ }) if $@;
1054 if ($rule->{macro}) {
1055 &$apply_macro($rule->{macro}, $rule, 1);
1061 sub copy_rule_data
{
1062 my ($rule, $param) = @_;
1064 foreach my $k (keys %$rule_properties) {
1065 if (defined(my $v = $param->{$k})) {
1066 if ($v eq '' || $v eq '-') {
1082 my $bridge_firewall_enabled = 0;
1084 sub enable_bridge_firewall
{
1086 return if $bridge_firewall_enabled; # only once
1088 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1089 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1091 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1092 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1094 $bridge_firewall_enabled = 1;
1097 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1099 sub iptables_restore_cmdlist
{
1102 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1105 sub ipset_restore_cmdlist
{
1108 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1111 sub iptables_get_chains
{
1115 # check what chains we want to track
1116 my $is_pvefw_chain = sub {
1119 return 1 if $name =~ m/^PVEFW-\S+$/;
1121 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1123 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1125 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1127 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1128 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1140 return if $line =~ m/^#/;
1141 return if $line =~ m/^\s*$/;
1143 if ($line =~ m/^\*(\S+)$/) {
1148 return if $table ne 'filter';
1150 if ($line =~ m/^:(\S+)\s/) {
1152 return if !&$is_pvefw_chain($chain);
1153 $res->{$chain} = "unknown";
1154 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1155 my ($chain, $sig) = ($1, $2);
1156 return if !&$is_pvefw_chain($chain);
1157 $res->{$chain} = $sig;
1158 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1161 # simply ignore the rest
1166 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1168 return wantarray ?
($res, $hooks) : $res;
1171 sub iptables_chain_digest
{
1173 my $digest = Digest
::SHA-
>new('sha1');
1174 foreach my $rule (@$rules) { # order is important
1175 $digest->add($rule);
1177 return $digest->b64digest;
1180 sub ipset_chain_digest
{
1183 my $digest = Digest
::SHA-
>new('sha1');
1184 foreach my $rule (sort @$rules) { # note: sorted
1185 $digest->add($rule);
1187 return $digest->b64digest;
1190 sub ipset_get_chains
{
1198 return if $line =~ m/^#/;
1199 return if $line =~ m/^\s*$/;
1200 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1202 $line =~ s/\s+$//; # delete trailing white space
1203 push @{$chains->{$chain}}, $line;
1205 # simply ignore the rest
1210 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1212 # compute digest for each chain
1213 foreach my $chain (keys %$chains) {
1214 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1220 sub ruleset_generate_cmdstr
{
1221 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1223 return if defined($rule->{enable
}) && !$rule->{enable
};
1225 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1227 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1228 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1232 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1233 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1235 my $source = $rule->{source
};
1236 my $dest = $rule->{dest
};
1239 if ($source =~ m/^\+/) {
1240 if ($source =~ m/^\+(${security_group_name_pattern})$/) {
1241 die "no such ipset '$1'\n" if !$cluster_conf->{ipset
}->{$1};
1242 push @cmd, "-m set --match-set PVEFW-$1 src";
1244 die "invalid security group name '$source'\n";
1246 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1247 my $alias = lc($source);
1248 my $e = $cluster_conf->{aliases
}->{$alias};
1249 die "no such alias $source\n" if !$e;
1250 push @cmd, "-s $e->{cidr}";
1251 } elsif ($source =~ m/\-/){
1252 push @cmd, "-m iprange --src-range $source";
1255 push @cmd, "-s $source";
1260 if ($dest =~ m/^\+/) {
1261 if ($dest =~ m/^\+(${security_group_name_pattern})$/) {
1262 die "no such ipset '$1'\n" if !$cluster_conf->{ipset
}->{$1};
1263 push @cmd, "-m set --match-set PVEFW-$1 dst";
1265 die "invalid security group name '$dest'\n";
1267 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1268 my $alias = lc($dest);
1269 my $e = $cluster_conf->{aliases
}->{$alias};
1270 die "no such alias $dest" if !$e;
1271 push @cmd, "-d $e->{cidr}";
1272 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1273 push @cmd, "-m iprange --dst-range $dest";
1276 push @cmd, "-d $dest";
1280 if ($rule->{proto
}) {
1281 push @cmd, "-p $rule->{proto}";
1284 $multiport++ if $nbdport > 1;
1285 $multiport++ if $nbsport > 1;
1287 push @cmd, "--match multiport" if $multiport;
1289 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1290 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1292 if ($rule->{dport
}) {
1293 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1294 # Note: we use dport to store --icmp-type
1295 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1296 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1299 if ($multiport == 2) {
1300 push @cmd, "--ports $rule->{dport}";
1302 push @cmd, "--dports $rule->{dport}";
1305 push @cmd, "--dport $rule->{dport}";
1310 if ($rule->{sport
}) {
1312 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1314 push @cmd, "--sport $rule->{sport}";
1317 } elsif ($rule->{dport
} || $rule->{sport
}) {
1318 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport
};
1319 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport
};
1322 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1324 if (my $action = $rule->{action
}) {
1325 $action = $actions->{$action} if defined($actions->{$action});
1326 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1327 push @cmd, $goto ?
"-g $action" : "-j $action";
1330 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1333 sub ruleset_generate_rule
{
1334 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1338 if ($rule->{macro}) {
1339 $rules = &$apply_macro($rule->{macro}, $rule);
1344 # update all or nothing
1347 foreach my $tmp (@$rules) {
1348 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1349 push @cmds, $cmdstr;
1353 foreach my $cmdstr (@cmds) {
1354 ruleset_addrule
($ruleset, $chain, $cmdstr);
1358 sub ruleset_generate_rule_insert
{
1359 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1361 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1363 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1364 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1368 sub ruleset_create_chain
{
1369 my ($ruleset, $chain) = @_;
1371 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1372 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1374 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1376 $ruleset->{$chain} = [];
1379 sub ruleset_chain_exist
{
1380 my ($ruleset, $chain) = @_;
1382 return $ruleset->{$chain} ?
1 : undef;
1385 sub ruleset_addrule
{
1386 my ($ruleset, $chain, $rule) = @_;
1388 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1390 push @{$ruleset->{$chain}}, "-A $chain $rule";
1393 sub ruleset_insertrule
{
1394 my ($ruleset, $chain, $rule) = @_;
1396 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1398 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1401 sub get_log_rule_base
{
1402 my ($chain, $vmid, $msg, $loglevel) = @_;
1404 die "internal error - no log level" if !defined($loglevel);
1406 $vmid = 0 if !defined($vmid);
1408 # Note: we use special format for prefix to pass further
1409 # info to log daemon (VMID, LOGVELEL and CHAIN)
1411 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1414 sub ruleset_addlog {
1415 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1417 return if !defined($loglevel);
1419 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1421 $logrule = "$rule $logrule" if defined($rule);
1423 ruleset_addrule($ruleset, $chain, $logrule);
1426 sub ruleset_add_chain_policy {
1427 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1429 if ($policy eq 'ACCEPT') {
1431 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1432 { ACCEPT => $accept_action});
1434 } elsif ($policy eq 'DROP') {
1436 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1438 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1440 ruleset_addrule($ruleset, $chain, "-j DROP
");
1441 } elsif ($policy eq 'REJECT') {
1442 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1444 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1446 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1449 die "internal error
: unknown policy
'$policy'";
1453 sub ruleset_chain_add_conn_filters {
1454 my ($ruleset, $chain, $accept) = @_;
1456 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1457 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1460 sub ruleset_chain_add_input_filters {
1461 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1463 if ($cluster_conf->{ipset}->{blacklist}){
1464 ruleset_addlog($ruleset, $chain, 0, "DROP
: ", $loglevel, "-m set
--match-set PVEFW-blacklist src
");
1465 ruleset_addrule($ruleset, $chain, "-m set
--match-set PVEFW-blacklist src
-j DROP
");
1468 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1469 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1472 if ($options->{tcpflags}) {
1473 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1477 sub ruleset_create_vm_chain {
1478 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1480 ruleset_create_chain($ruleset, $chain);
1481 my $accept = generate_nfqueue($options);
1483 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1484 if ($direction eq 'OUT') {
1485 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1486 proto => 'udp', sport => 68, dport => 67 });
1488 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1489 proto => 'udp', sport => 67, dport => 68 });
1493 if ($direction eq 'OUT') {
1494 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1495 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1497 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1501 sub ruleset_add_group_rule {
1502 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1504 my $group = $rule->{action};
1505 my $group_chain = "GROUP-
$group-$direction";
1506 if(!ruleset_chain_exist($ruleset, $group_chain)){
1507 generate_group_rules($ruleset, $cluster_conf, $group);
1510 if ($direction eq 'OUT' && $rule->{iface_out}) {
1511 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1512 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1513 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1515 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1518 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1521 sub ruleset_generate_vm_rules {
1522 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1524 my $lc_direction = lc($direction);
1526 my $in_accept = generate_nfqueue($options);
1528 foreach my $rule (@$rules) {
1529 next if $rule->{iface} && $rule->{iface} ne $netid;
1530 next if !$rule->{enable};
1531 if ($rule->{type} eq 'group') {
1532 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1533 $direction eq 'OUT' ? 'RETURN' : $in_accept);
1535 next if $rule->{type} ne $lc_direction;
1537 if ($direction eq 'OUT') {
1538 ruleset_generate_rule($ruleset, $chain, $rule,
1539 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1540 undef, $cluster_conf);
1542 ruleset_generate_rule($ruleset, $chain, $rule,
1543 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1544 undef, $cluster_conf);
1552 sub generate_nfqueue {
1555 if ($options->{ips}) {
1556 my $action = "NFQUEUE
";
1557 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1558 if (defined($3) && defined($1)) {
1559 $action .= " --queue-balance
$1:$3";
1560 } elsif (defined($1)) {
1561 $action .= " --queue-num
$1";
1564 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1571 sub ruleset_generate_vm_ipsrules {
1572 my ($ruleset, $options, $direction, $iface) = @_;
1574 if ($options->{ips} && $direction eq 'IN') {
1575 my $nfqueue = generate_nfqueue($options);
1577 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1578 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1581 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1585 sub generate_venet_rules_direction {
1586 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1588 my $lc_direction = lc($direction);
1590 my $rules = $vmfw_conf->{rules};
1592 my $options = $vmfw_conf->{options};
1593 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1595 my $chain = "venet0-
$vmid-$direction";
1597 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1599 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1604 if ($direction eq 'OUT') {
1605 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1607 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1610 my $accept = generate_nfqueue($options);
1611 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1612 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1614 if ($direction eq 'OUT') {
1615 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1618 iface_in => 'venet0'});
1620 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1623 iface_out => 'venet0'});
1627 sub generate_tap_rules_direction {
1628 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
1630 my $lc_direction = lc($direction);
1632 my $rules = $vmfw_conf->{rules};
1634 my $options = $vmfw_conf->{options};
1635 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1637 my $tapchain = "$iface-$direction";
1639 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1641 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1643 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1648 if ($direction eq 'OUT') {
1649 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1651 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1654 my $accept = generate_nfqueue($options);
1655 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1656 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1658 # plug the tap chain to bridge chain
1659 if ($direction eq 'IN') {
1660 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
1661 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1663 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
1664 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
1668 sub enable_host_firewall {
1669 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1671 my $options = $hostfw_conf->{options};
1672 my $cluster_options = $cluster_conf->{options};
1673 my $rules = $hostfw_conf->{rules};
1674 my $cluster_rules = $cluster_conf->{rules};
1676 # host inbound firewall
1677 my $chain = "PVEFW-HOST-IN
";
1678 ruleset_create_chain($ruleset, $chain);
1680 my $loglevel = get_option_log_level($options, "log_level_in
");
1682 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1684 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1685 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1687 my $clusternet = get_cluster_network();
1690 ruleset_addrule($ruleset, $chain, "-s
$clusternet -p tcp
--dport
8006 -j ACCEPT
"); # PVE API
1691 ruleset_addrule($ruleset, $chain, "-s
$clusternet -p tcp
--dport
5900:5999 -j ACCEPT
"); # PVE VNC Console
1692 ruleset_addrule($ruleset, $chain, "-s
$clusternet -p tcp
--dport
3128 -j ACCEPT
"); # SPICE Proxy
1693 ruleset_addrule($ruleset, $chain, "-s
$clusternet -p tcp
--dport
22 -j ACCEPT
"); # SSH
1696 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1697 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1698 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1700 # we use RETURN because we need to check also tap rules
1701 my $accept_action = 'RETURN';
1703 # add host rules first, so that cluster wide rules can be overwritten
1704 foreach my $rule (@$rules, @$cluster_rules) {
1705 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1706 if ($rule->{type} eq 'group') {
1707 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1708 } elsif ($rule->{type} eq 'in') {
1709 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1710 undef, $cluster_conf);
1712 delete $rule->{iface_in};
1715 # implement input policy
1716 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1717 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1719 # host outbound firewall
1720 $chain = "PVEFW-HOST-OUT
";
1721 ruleset_create_chain($ruleset, $chain);
1723 $loglevel = get_option_log_level($options, "log_level_out
");
1725 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1727 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1729 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1730 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1731 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1733 # we use RETURN because we may want to check other thigs later
1734 $accept_action = 'RETURN';
1736 # add host rules first, so that cluster wide rules can be overwritten
1737 foreach my $rule (@$rules, @$cluster_rules) {
1738 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1739 if ($rule->{type} eq 'group') {
1740 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1741 } elsif ($rule->{type} eq 'out') {
1742 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1743 undef, $cluster_conf);
1745 delete $rule->{iface_out};
1748 # implement output policy
1749 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1750 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1752 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1753 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1756 sub generate_group_rules {
1757 my ($ruleset, $cluster_conf, $group) = @_;
1759 my $rules = $cluster_conf->{groups}->{$group};
1762 warn "no such security group
'$group'\n";
1763 $rules = []; # create empty chain
1766 my $chain = "GROUP-
${group
}-IN
";
1768 ruleset_create_chain($ruleset, $chain);
1769 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1771 foreach my $rule (@$rules) {
1772 next if $rule->{type} ne 'in';
1773 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1776 $chain = "GROUP-
${group
}-OUT
";
1778 ruleset_create_chain($ruleset, $chain);
1779 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1781 foreach my $rule (@$rules) {
1782 next if $rule->{type} ne 'out';
1783 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1784 # check also other tap rules later
1785 ruleset_generate_rule($ruleset, $chain, $rule,
1786 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1791 my $valid_netdev_names = {};
1792 for (my $i = 0; $i < $MAX_NETS; $i++) {
1793 $valid_netdev_names->{"net
$i"} = 1;
1797 my ($line, $allow_iface, $allow_groups) = @_;
1799 my ($type, $action, $macro, $iface, $source, $dest, $proto, $dport, $sport);
1803 # we can add single line comments to the end of the rule
1804 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1806 # we can disable a rule when prefixed with '|'
1809 $enable = 0 if $line =~ s/^\|//;
1811 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1812 die "unable to parse rule
: $line\n";
1817 if ($type eq 'in' || $type eq 'out') {
1818 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1820 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1822 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1823 die "unknown
macro '$1'\n" if !$preferred_name;
1824 $macro = $preferred_name;
1826 die "unknown action
'$action'\n";
1828 } elsif ($type eq 'group') {
1829 die "groups disabled
\n" if !$allow_groups;
1830 die "invalid characters
in group name
\n" if $action !~ m/^${security_group_name_pattern}$/;
1832 die "unknown rule type
'$type'\n";
1835 while (length($line)) {
1836 if ($line =~ s/^-i (\S+)\s*//) {
1837 die "parameter
-i
not allowed
\n" if !$allow_iface;
1839 PVE::JSONSchema::pve_verify_iface($iface);
1843 last if $type eq 'group';
1845 if ($line =~ s/^-p (\S+)\s*//) {
1847 pve_fw_verify_protocol_spec($proto);
1850 if ($line =~ s/^-dport (\S+)\s*//) {
1852 parse_port_name_number_or_range($dport);
1855 if ($line =~ s/^-sport (\S+)\s*//) {
1857 parse_port_name_number_or_range($sport);
1860 if ($line =~ s/^-source (\S+)\s*//) {
1862 parse_address_list($source);
1865 if ($line =~ s/^-dest (\S+)\s*//) {
1867 parse_address_list($dest);
1874 die "unable to parse rule parameters
: $line\n" if length($line);
1879 comment => $comment,
1891 sub parse_vmfw_option {
1896 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
1898 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
1901 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1903 $value = $2 ? lc($3) : '';
1904 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1907 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1912 die "can
't parse option '$line'\n"
1915 return ($opt, $value);
1918 sub parse_hostfw_option {
1923 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1925 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
1928 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1930 $value = $2 ? lc($3) : '';
1931 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
1936 die "can't parse option
'$line'\n"
1939 return ($opt, $value);
1942 sub parse_clusterfw_option {
1947 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1950 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1955 die "can
't parse option '$line'\n"
1958 return ($opt, $value);
1961 sub parse_clusterfw_alias {
1964 # we can add single line comments to the end of the line
1965 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
1967 if ($line =~ m/^(\S+)\s(\S+)$/) {
1968 my ($name, $cidr) = ($1, $2);
1970 pve_verify_ipv4_or_cidr($cidr);
1975 $data->{comment} = $comment if $comment;
1982 sub parse_vm_fw_rules {
1983 my ($filename, $fh) = @_;
1985 my $res = { rules => [], options => {}};
1989 while (defined(my $line = <$fh>)) {
1990 next if $line =~ m/^#/;
1991 next if $line =~ m/^\s*$/;
1993 my $linenr = $fh->input_line_number();
1994 my $prefix = "$filename (line $linenr)";
1996 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1998 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
2002 warn "$prefix: skip line - no section";
2006 next if !$res->{$section}; # skip undefined section
2008 if ($section eq 'options
') {
2010 my ($opt, $value) = parse_vmfw_option($line);
2011 $res->{options}->{$opt} = $value;
2013 warn "$prefix: $@" if $@;
2018 eval { $rule = parse_fw_rule($line, 1, 1); };
2020 warn "$prefix: $err";
2024 push @{$res->{$section}}, $rule;
2030 sub parse_host_fw_rules {
2031 my ($filename, $fh) = @_;
2033 my $res = { rules => [], options => {}};
2037 while (defined(my $line = <$fh>)) {
2038 next if $line =~ m/^#/;
2039 next if $line =~ m/^\s*$/;
2041 my $linenr = $fh->input_line_number();
2042 my $prefix = "$filename (line $linenr)";
2044 if ($line =~ m/^\[(\S+)\]\s*$/i) {
2046 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
2050 warn "$prefix: skip line - no section";
2054 next if !$res->{$section}; # skip undefined section
2056 if ($section eq 'options
') {
2058 my ($opt, $value) = parse_hostfw_option($line);
2059 $res->{options}->{$opt} = $value;
2061 warn "$prefix: $@" if $@;
2066 eval { $rule = parse_fw_rule($line, 1, 1); };
2068 warn "$prefix: $err";
2072 push @{$res->{$section}}, $rule;
2078 sub parse_cluster_fw_rules {
2079 my ($filename, $fh) = @_;
2089 group_comments => {},
2091 ipset_comments => {},
2094 while (defined(my $line = <$fh>)) {
2095 next if $line =~ m/^#/;
2096 next if $line =~ m/^\s*$/;
2098 my $linenr = $fh->input_line_number();
2099 my $prefix = "$filename (line $linenr)";
2101 if ($line =~ m/^\[options\]$/i) {
2102 $section = 'options
';
2106 if ($line =~ m/^\[aliases\]$/i) {
2107 $section = 'aliases
';
2111 if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2112 $section = 'groups
';
2115 $res->{$section}->{$group} = [];
2116 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2121 if ($line =~ m/^\[rules\]$/i) {
2126 if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2130 $res->{$section}->{$group} = [];
2131 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2137 warn "$prefix: skip line - no section\n";
2141 if ($section eq 'options
') {
2143 my ($opt, $value) = parse_clusterfw_option($line);
2144 $res->{options}->{$opt} = $value;
2146 warn "$prefix: $@" if $@;
2147 } elsif ($section eq 'aliases
') {
2149 my $data = parse_clusterfw_alias($line);
2150 $res->{aliases}->{lc($data->{name})} = $data;
2152 warn "$prefix: $@" if $@;
2153 } elsif ($section eq 'rules
') {
2155 eval { $rule = parse_fw_rule($line, 1, 1); };
2157 warn "$prefix: $err";
2160 push @{$res->{$section}}, $rule;
2161 } elsif ($section eq 'groups
') {
2163 eval { $rule = parse_fw_rule($line, 0, 0); };
2165 warn "$prefix: $err";
2168 push @{$res->{$section}->{$group}}, $rule;
2169 } elsif ($section eq 'ipset
') {
2170 # we can add single line comments to the end of the rule
2171 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2173 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2177 if($cidr !~ m/^${ip_alias_pattern}$/) {
2180 eval { pve_verify_ipv4_or_cidr($cidr); };
2182 warn "$prefix: $cidr - $err";
2187 my $entry = { cidr => $cidr };
2188 $entry->{nomatch} = 1 if $nomatch;
2189 $entry->{comment} = $comment if $comment;
2191 push @{$res->{$section}->{$group}}, $entry;
2199 my ($code, @param) = @_;
2203 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2210 sub read_local_vm_config {
2215 my $vmdata = { openvz => $openvz, qemu => $qemu };
2217 my $vmlist = PVE::Cluster::get_vmlist();
2218 return $vmdata if !$vmlist || !$vmlist->{ids};
2219 my $ids = $vmlist->{ids};
2221 foreach my $vmid (keys %$ids) {
2222 next if !$vmid; # skip VE0
2223 my $d = $ids->{$vmid};
2224 next if !$d->{node} || $d->{node} ne $nodename;
2225 next if !$d->{type};
2226 if ($d->{type} eq 'openvz
') {
2227 if ($have_pve_manager) {
2228 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2229 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2230 $openvz->{$vmid} = $conf;
2233 } elsif ($d->{type} eq 'qemu
') {
2234 if ($have_qemu_server) {
2235 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2236 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2237 $qemu->{$vmid} = $conf;
2246 sub load_vmfw_conf {
2247 my ($vmid, $dir) = @_;
2251 $dir = "/etc/pve/firewall" if !defined($dir);
2253 my $filename = "$dir/$vmid.fw";
2254 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2255 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2261 my $format_rules = sub {
2262 my ($rules, $allow_iface) = @_;
2266 foreach my $rule (@$rules) {
2267 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2268 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2269 $raw .= uc($rule->{type});
2270 if ($rule->{macro}) {
2271 $raw .= " $rule->{macro}($rule->{action})";
2273 $raw .= " " . $rule->{action};
2275 if ($allow_iface && $rule->{iface}) {
2276 $raw .= " -i $rule->{iface}";
2279 if ($rule->{type} ne 'group
') {
2280 $raw .= " -source $rule->{source}" if $rule->{source};
2281 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2282 $raw .= " -p $rule->{proto}" if $rule->{proto};
2283 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2284 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2287 $raw .= " # " . encode('utf8
', $rule->{comment})
2288 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2291 die "unknown rule type '$rule->{type
}'";
2298 my $format_options = sub {
2303 $raw .= "[OPTIONS]\n\n";
2304 foreach my $opt (keys %$options) {
2305 $raw .= "$opt: $options->{$opt}\n";
2312 my $format_aliases = sub {
2317 $raw .= "[ALIASES]\n\n";
2318 foreach my $k (keys %$aliases) {
2319 my $e = $aliases->{$k};
2320 $raw .= "$e->{name} $e->{cidr}";
2321 $raw .= " # " . encode('utf8
', $e->{comment})
2322 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2330 my $format_ipset = sub {
2336 foreach my $entry (@$options) {
2337 $nethash->{$entry->{cidr}} = $entry;
2340 foreach my $cidr (sort keys %$nethash) {
2341 my $entry = $nethash->{$cidr};
2342 my $line = $entry->{nomatch} ? '!' : '';
2343 $line .= $entry->{cidr};
2344 $line .= " # " . encode('utf8
', $entry->{comment})
2345 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2352 sub save_vmfw_conf {
2353 my ($vmid, $vmfw_conf) = @_;
2357 my $options = $vmfw_conf->{options};
2358 $raw .= &$format_options($options) if scalar(keys %$options);
2360 my $rules = $vmfw_conf->{rules} || [];
2361 if (scalar(@$rules)) {
2362 $raw .= "[RULES]\n\n";
2363 $raw .= &$format_rules($rules, 1);
2367 my $filename = "/etc/pve/firewall/$vmid.fw";
2368 PVE::Tools::file_set_contents($filename, $raw);
2371 sub read_vm_firewall_configs {
2372 my ($vmdata, $dir) = @_;
2374 my $vmfw_configs = {};
2376 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2377 my $vmfw_conf = load_vmfw_conf($vmid, $dir);
2378 next if !$vmfw_conf->{options}; # skip if file does not exists
2379 $vmfw_configs->{$vmid} = $vmfw_conf;
2382 return $vmfw_configs;
2385 sub get_option_log_level {
2386 my ($options, $k) = @_;
2388 my $v = $options->{$k};
2389 $v = $default_log_level if !defined($v);
2391 return undef if $v eq '' || $v eq 'nolog
';
2393 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2395 return $v if ($v >= 0) && ($v <= 7);
2397 warn "unknown log level ($k = '$v')\n";
2402 sub generate_std_chains {
2403 my ($ruleset, $options) = @_;
2405 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2407 # same as shorewall smurflog.
2408 my $chain = 'PVEFW-smurflog
';
2409 $pve_std_chains->{$chain} = [];
2411 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2412 push @{$pve_std_chains->{$chain}}, "-j DROP";
2414 # same as shorewall logflags action.
2415 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2416 $chain = 'PVEFW-logflags
';
2417 $pve_std_chains->{$chain} = [];
2419 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2420 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2421 push @{$pve_std_chains->{$chain}}, "-j DROP";
2423 foreach my $chain (keys %$pve_std_chains) {
2424 ruleset_create_chain($ruleset, $chain);
2425 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2427 ruleset_generate_rule($ruleset, $chain, $rule);
2429 ruleset_addrule($ruleset, $chain, $rule);
2435 sub generate_ipset_chains {
2436 my ($ipset_ruleset, $fw_conf) = @_;
2438 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2439 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset}, $fw_conf->{aliases});
2443 sub generate_ipset {
2444 my ($ipset_ruleset, $name, $options, $aliases) = @_;
2446 my $hashsize = scalar(@$options);
2447 if ($hashsize <= 64) {
2450 $hashsize = round_powerof2($hashsize);
2453 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2457 foreach my $entry (@$options) {
2458 my $cidr = $entry->{cidr};
2459 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2460 my $alias = lc($cidr);
2461 if ($aliases->{$alias}) {
2462 $entry->{cidr} = $aliases->{$alias}->{cidr};
2463 $nethash->{$entry->{cidr}} = $entry;
2465 warn "no such alias '$cidr'\n" if !$aliases->{$alias};
2468 $nethash->{$entry->{cidr}} = $entry;
2472 foreach my $cidr (sort keys %$nethash) {
2473 my $entry = $nethash->{$cidr};
2475 my $cmd = "add $name $cidr";
2476 if ($entry->{nomatch}) {
2477 if ($feature_ipset_nomatch) {
2478 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2480 warn "ignore !$cidr - nomatch not supported by kernel\n";
2483 push @{$ipset_ruleset->{$name}}, $cmd;
2488 sub round_powerof2 {
2492 $int |= $int >> $_ foreach (1,2,4,8,16);
2496 sub load_clusterfw_conf {
2497 my ($filename) = @_;
2499 $filename = $clusterfw_conf_filename if !defined($filename);
2501 my $cluster_conf = {};
2502 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2503 $cluster_conf = parse_cluster_fw_rules($filename, $fh);
2506 return $cluster_conf;
2509 sub save_clusterfw_conf {
2510 my ($cluster_conf) = @_;
2514 my $options = $cluster_conf->{options};
2515 $raw .= &$format_options($options) if scalar(keys %$options);
2517 my $aliases = $cluster_conf->{aliases};
2518 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2520 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
2521 if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
2522 my $utf8comment = encode('utf8
', $comment);
2523 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2525 $raw .= "[IPSET $ipset]\n\n";
2527 my $options = $cluster_conf->{ipset}->{$ipset};
2528 $raw .= &$format_ipset($options);
2532 my $rules = $cluster_conf->{rules};
2533 if (scalar(@$rules)) {
2534 $raw .= "[RULES]\n\n";
2535 $raw .= &$format_rules($rules, 1);
2539 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2540 my $rules = $cluster_conf->{groups}->{$group};
2541 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2542 my $utf8comment = encode('utf8
', $comment);
2543 $raw .= "[group $group] # $utf8comment\n\n";
2545 $raw .= "[group $group]\n\n";
2548 $raw .= &$format_rules($rules, 0);
2552 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2555 sub load_hostfw_conf {
2556 my ($filename) = @_;
2558 $filename = $hostfw_conf_filename if !defined($filename);
2560 my $hostfw_conf = {};
2561 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2562 $hostfw_conf = parse_host_fw_rules($filename, $fh);
2564 return $hostfw_conf;
2567 sub save_hostfw_conf {
2568 my ($hostfw_conf) = @_;
2572 my $options = $hostfw_conf->{options};
2573 $raw .= &$format_options($options) if scalar(keys %$options);
2575 my $rules = $hostfw_conf->{rules};
2576 if (scalar(@$rules)) {
2577 $raw .= "[RULES]\n\n";
2578 $raw .= &$format_rules($rules, 1);
2582 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2586 my ($cluster_conf, $hostfw_conf, $vmdata) = @_;
2590 if ($vmdata) { # test mode
2591 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2592 my $filename = "$testdir/cluster.fw";
2593 die "missing test file '$filename'\n" if ! -f $filename;
2594 $cluster_conf = load_clusterfw_conf($filename);
2596 $filename = "$testdir/host.fw";
2597 die "missing test file '$filename'\n" if ! -f $filename;
2598 $hostfw_conf = load_hostfw_conf($filename);
2600 $vmfw_configs = read_vm_firewall_configs($vmdata, $testdir);
2601 } else { # normal operation
2602 $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
2604 $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
2606 $vmdata = read_local_vm_config();
2607 $vmfw_configs = read_vm_firewall_configs($vmdata);
2611 $cluster_conf->{ipset}->{venet0} = [];
2615 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2616 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2618 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2620 my $hostfw_options = $hostfw_conf->{options} || {};
2622 # fixme: what log level should we use here?
2623 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2625 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2627 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2628 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT");
2629 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT");
2631 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2632 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2634 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2636 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2637 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2639 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2640 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2642 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN");
2644 generate_std_chains($ruleset, $hostfw_options);
2646 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2648 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2650 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN");
2652 # generate firewall rules for QEMU VMs
2653 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2654 my $conf = $vmdata->{qemu}->{$vmid};
2655 my $vmfw_conf = $vmfw_configs->{$vmid};
2656 next if !$vmfw_conf;
2657 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2659 foreach my $netid (keys %$conf) {
2660 next if $netid !~ m/^net(\d+)$/;
2661 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2662 next if !$net->{firewall};
2663 my $iface = "tap${vmid}i$1";
2665 my $macaddr = $net->{macaddr};
2666 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2667 $vmfw_conf, $vmid, 'IN
');
2668 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2669 $vmfw_conf, $vmid, 'OUT
');
2673 # generate firewall rules for OpenVZ containers
2674 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2675 my $conf = $vmdata->{openvz}->{$vmid};
2677 my $vmfw_conf = $vmfw_configs->{$vmid};
2678 next if !$vmfw_conf;
2679 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2681 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2682 my $ip = $conf->{ip_address}->{value};
2684 parse_address_list($ip); # make sure we have a valid $ip list
2686 my @ips = split(',', $ip);
2688 foreach my $singleip (@ips) {
2689 my $venet0ipset = {};
2690 $venet0ipset->{cidr} = $singleip;
2691 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2694 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2695 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2698 if ($conf->{netif} && $conf->{netif}->{value}) {
2699 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2700 foreach my $netid (keys %$netif) {
2701 my $d = $netif->{$netid};
2703 my $macaddr = $d->{mac};
2704 my $iface = $d->{host_ifname};
2705 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2706 $vmfw_conf, $vmid, 'IN
');
2707 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2708 $vmfw_conf, $vmid, 'OUT
');
2713 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2714 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2717 my $ipset_ruleset = {};
2718 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2720 return ($ruleset, $ipset_ruleset);
2723 sub get_ruleset_status {
2724 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2726 my $statushash = {};
2728 foreach my $chain (sort keys %$ruleset) {
2729 my $sig = &$digest_fn($ruleset->{$chain});
2731 $statushash->{$chain}->{sig} = $sig;
2733 my $oldsig = $active_chains->{$chain};
2734 if (!defined($oldsig)) {
2735 $statushash->{$chain}->{action} = 'create
';
2737 if ($oldsig eq $sig) {
2738 $statushash->{$chain}->{action} = 'exists';
2740 $statushash->{$chain}->{action} = 'update
';
2743 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2744 foreach my $cmd (@{$ruleset->{$chain}}) {
2745 print "\t$cmd\n" if $verbose;
2749 foreach my $chain (sort keys %$active_chains) {
2750 if (!defined($ruleset->{$chain})) {
2751 my $sig = $active_chains->{$chain};
2752 $statushash->{$chain}->{action} = 'delete';
2753 $statushash->{$chain}->{sig} = $sig;
2754 print "delete $chain ($sig)\n" if $verbose;
2761 sub print_sig_rule {
2762 my ($chain, $sig) = @_;
2764 # We just use this to store a SHA1 checksum used to detect changes
2765 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2768 sub get_ruleset_cmdlist {
2769 my ($ruleset, $verbose) = @_;
2771 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2773 my ($active_chains, $hooks) = iptables_get_chains();
2774 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2776 # create missing chains first
2777 foreach my $chain (sort keys %$ruleset) {
2778 my $stat = $statushash->{$chain};
2779 die "internal error" if !$stat;
2780 next if $stat->{action} ne 'create
';
2782 $cmdlist .= ":$chain - [0:0]\n";
2785 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2786 if (!$hooks->{$h}) {
2787 $cmdlist .= "-A $h -j PVEFW-$h\n";
2791 foreach my $chain (sort keys %$ruleset) {
2792 my $stat = $statushash->{$chain};
2793 die "internal error" if !$stat;
2795 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2796 $cmdlist .= "-F $chain\n";
2797 foreach my $cmd (@{$ruleset->{$chain}}) {
2798 $cmdlist .= "$cmd\n";
2800 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2801 } elsif ($stat->{action
} eq 'delete') {
2802 die "internal error"; # this should not happen
2803 } elsif ($stat->{action
} eq 'exists') {
2806 die "internal error - unknown status '$stat->{action}'";
2810 foreach my $chain (keys %$statushash) {
2811 next if $statushash->{$chain}->{action
} ne 'delete';
2812 $cmdlist .= "-F $chain\n";
2814 foreach my $chain (keys %$statushash) {
2815 next if $statushash->{$chain}->{action
} ne 'delete';
2816 next if $chain eq 'PVEFW-INPUT';
2817 next if $chain eq 'PVEFW-OUTPUT';
2818 next if $chain eq 'PVEFW-FORWARD';
2819 $cmdlist .= "-X $chain\n";
2822 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2824 $cmdlist .= "COMMIT\n";
2826 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2829 sub get_ipset_cmdlist
{
2830 my ($ruleset, $verbose) = @_;
2834 my $delete_cmdlist = "";
2836 my $active_chains = ipset_get_chains
();
2837 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2839 # remove stale _swap chains
2840 foreach my $chain (keys %$active_chains) {
2841 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2842 $cmdlist .= "destroy $chain\n";
2846 foreach my $chain (sort keys %$ruleset) {
2847 my $stat = $statushash->{$chain};
2848 die "internal error" if !$stat;
2850 if ($stat->{action
} eq 'create') {
2851 foreach my $cmd (@{$ruleset->{$chain}}) {
2852 $cmdlist .= "$cmd\n";
2856 if ($stat->{action
} eq 'update') {
2857 my $chain_swap = $chain."_swap";
2859 foreach my $cmd (@{$ruleset->{$chain}}) {
2860 $cmd =~ s/$chain/$chain_swap/;
2861 $cmdlist .= "$cmd\n";
2863 $cmdlist .= "swap $chain_swap $chain\n";
2864 $cmdlist .= "flush $chain_swap\n";
2865 $cmdlist .= "destroy $chain_swap\n";
2870 foreach my $chain (keys %$statushash) {
2871 next if $statushash->{$chain}->{action
} ne 'delete';
2873 $delete_cmdlist .= "flush $chain\n";
2874 $delete_cmdlist .= "destroy $chain\n";
2877 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
2879 return ($cmdlist, $delete_cmdlist, $changes);
2883 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2885 enable_bridge_firewall
();
2887 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2888 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
2890 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
2893 if ($ipset_changes) {
2894 print "ipset changes:\n";
2895 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2896 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2900 print "iptables changes:\n";
2905 ipset_restore_cmdlist
($ipset_create_cmdlist);
2907 iptables_restore_cmdlist
($cmdlist);
2909 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2911 # test: re-read status and check if everything is up to date
2912 my $active_chains = iptables_get_chains
();
2913 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
2916 foreach my $chain (sort keys %$ruleset) {
2917 my $stat = $statushash->{$chain};
2918 if ($stat->{action
} ne 'exists') {
2919 warn "unable to update chain '$chain'\n";
2924 die "unable to apply firewall changes\n" if $errors;
2926 update_nf_conntrack_max
($hostfw_conf);
2928 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
2932 sub update_nf_conntrack_max
{
2933 my ($hostfw_conf) = @_;
2935 my $max = 65536; # reasonable default
2937 my $options = $hostfw_conf->{options
} || {};
2939 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
2940 $max = $options->{nf_conntrack_max
};
2941 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2944 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2945 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2947 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
2949 if ($current != $max) {
2950 my $hashsize = int($max/4);
2951 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
2952 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
2956 sub update_nf_conntrack_tcp_timeout_established
{
2957 my ($hostfw_conf) = @_;
2959 my $options = $hostfw_conf->{options
} || {};
2961 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
2963 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
2966 sub remove_pvefw_chains
{
2968 my ($chash, $hooks) = iptables_get_chains
();
2969 my $cmdlist = "*filter\n";
2971 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2973 $cmdlist .= "-D $h -j PVEFW-$h\n";
2977 foreach my $chain (keys %$chash) {
2978 $cmdlist .= "-F $chain\n";
2981 foreach my $chain (keys %$chash) {
2982 $cmdlist .= "-X $chain\n";
2984 $cmdlist .= "COMMIT\n";
2986 iptables_restore_cmdlist
($cmdlist);
2990 my $cluster_conf = load_clusterfw_conf
();
2991 my $cluster_options = $cluster_conf->{options
};
2992 my $enable = $cluster_options->{enable
};
2996 # load required modules here
3004 my $cluster_conf = load_clusterfw_conf
();
3005 my $cluster_options = $cluster_conf->{options
};
3007 my $enable = $cluster_options->{enable
};
3009 die "Firewall is disabled - cannot start\n" if !$enable;
3012 PVE
::Firewall
::remove_pvefw_chains
();
3013 print "Firewall disabled\n" if $verbose;
3017 my $hostfw_conf = load_hostfw_conf
();
3019 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3021 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);