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 my $max_alias_name_length = 64;
78 my $max_ipset_name_length = 64;
81 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
82 description
=> "Security Group name.",
84 pattern
=> $security_group_name_pattern,
89 my $feature_ipset_nomatch = 0;
91 my (undef, undef, $release) = POSIX
::uname
();
92 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
93 my ($major, $minor) = ($1, $2);
94 $feature_ipset_nomatch = 1 if ($major > 3) ||
95 ($major == 3 && $minor >= 7);
102 my $nodename = PVE
::INotify
::nodename
();
104 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
106 my $default_log_level = 'nolog'; # avoid logs by default
108 my $log_level_hash = {
119 # imported/converted from: /usr/share/shorewall/macro.*
120 my $pve_fw_macros = {
123 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
124 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
127 "Auth (identd) traffic",
128 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
131 "Border Gateway Protocol traffic",
132 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
135 "BitTorrent traffic for BitTorrent 3.1 and earlier",
136 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
137 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
140 "BitTorrent traffic for BitTorrent 3.2 and later",
141 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
142 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
145 "Concurrent Versions System pserver traffic",
146 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
149 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
150 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
151 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
152 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
155 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
156 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
157 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
160 "Distributed Checksum Clearinghouse spam filtering mechanism",
161 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
164 "Forwarded DHCP traffic",
165 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
168 "Domain Name System traffic (upd and tcp)",
169 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
170 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
173 "Distributed Compiler service",
174 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
177 "File Transfer Protocol",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
181 "Finger protocol (RFC 742)",
182 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
185 "GNUnet secure peer-to-peer networking traffic",
186 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
187 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
188 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
189 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
192 "Generic Routing Encapsulation tunneling protocol",
193 { action
=> 'PARAM', proto
=> '47' },
196 "Git distributed revision control traffic",
197 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
200 "OpenPGP HTTP keyserver protocol traffic",
201 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
204 "Hypertext Transfer Protocol (WWW)",
205 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
208 "Hypertext Transfer Protocol (WWW) over SSL",
209 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
212 "Internet Cache Protocol V2 (Squid) traffic",
213 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
216 "AOL Instant Messenger traffic",
217 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
220 "Internet Message Access Protocol",
221 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
224 "Internet Message Access Protocol over SSL",
225 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
228 "IPIP capsulation traffic",
229 { action
=> 'PARAM', proto
=> '94' },
233 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
234 { action
=> 'PARAM', proto
=> '50' },
237 "IPsec authentication (AH) traffic",
238 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
239 { action
=> 'PARAM', proto
=> '51' },
242 "IPsec traffic and Nat-Traversal",
243 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
244 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
245 { action
=> 'PARAM', proto
=> '50' },
248 "Internet Relay Chat traffic",
249 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
252 "HP Jetdirect printing",
253 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
256 "Layer 2 Tunneling Protocol traffic",
257 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
260 "Lightweight Directory Access Protocol traffic",
261 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
264 "Secure Lightweight Directory Access Protocol traffic",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
268 "Microsoft Notification Protocol",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
272 "Microsoft SQL Server",
273 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
276 "Mail traffic (SMTP, SMTPS, Submission)",
277 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
278 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
279 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
282 "Munin networked resource monitoring traffic",
283 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
287 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
290 "NNTP traffic (Usenet).",
291 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
294 "Encrypted NNTP traffic (Usenet)",
295 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
298 "Network Time Protocol (ntpd)",
299 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
302 "OSPF multicast traffic",
303 { action
=> 'PARAM', proto
=> '89' },
307 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
310 "Symantec PCAnywere (tm)",
311 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
312 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
316 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
319 "Encrypted POP3 traffic",
320 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
323 "Point-to-Point Tunneling Protocol",
324 { action
=> 'PARAM', proto
=> '47' },
325 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
329 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
336 "Line Printer protocol printing",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
340 "Microsoft Remote Desktop Protocol traffic",
341 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
344 "Routing Information Protocol (bidirectional)",
345 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
348 "BIND remote management protocol",
349 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
352 "Razor Antispam System",
353 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
356 "Remote time retrieval (rdate)",
357 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
361 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
364 "SANE network scanning",
365 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
368 "Microsoft SMB traffic",
369 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
370 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
371 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
372 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
375 "Samba Web Administration Tool",
376 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
379 "Simple Mail Transfer Protocol",
380 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
383 "Encrypted Simple Mail Transfer Protocol",
384 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
387 "Simple Network Management Protocol",
388 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
389 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
392 "Spam Assassin SPAMD traffic",
393 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
396 "Secure shell traffic",
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
400 "Subversion server (svnserve)",
401 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
404 "SixXS IPv6 Deployment and Tunnel Broker",
405 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
406 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
407 { action
=> 'PARAM', proto
=> '41' },
408 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
411 "Squid web proxy traffic",
412 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
415 "Mail message submission traffic",
416 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
419 "Syslog protocol (RFC 5424) traffic",
420 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
421 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
424 "Trivial File Transfer Protocol traffic",
425 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
436 "RFC 868 Time protocol",
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
440 "Traceroute (for up to 30 hops) traffic",
441 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
442 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
445 "VNC traffic for VNC display's 0 - 99",
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
449 "VNC traffic from Vncservers to Vncviewers in listen mode",
450 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
453 "WWW traffic (HTTP and HTTPS)",
454 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
455 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
458 "Web Cache/Proxy traffic (port 8080)",
459 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
466 "Whois (nicname, RFC 3912) traffic",
467 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
471 my $pve_fw_parsed_macros;
472 my $pve_fw_macro_descr;
473 my $pve_fw_preferred_macro_names = {};
475 my $pve_std_chains = {
476 'PVEFW-SET-ACCEPT-MARK' => [
477 "-j MARK --set-mark 1",
479 'PVEFW-DropBroadcast' => [
480 # same as shorewall 'Broadcast'
481 # simply DROP BROADCAST/MULTICAST/ANYCAST
482 # we can use this to reduce logging
483 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
484 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
485 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
486 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
489 # same as shorewall 'reject'
490 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
491 { action
=> 'DROP', source
=> '224.0.0.0/4' },
492 { action
=> 'DROP', proto
=> 'icmp' },
493 "-p tcp -j REJECT --reject-with tcp-reset",
494 "-p udp -j REJECT --reject-with icmp-port-unreachable",
495 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
496 "-j REJECT --reject-with icmp-host-prohibited",
499 # same as shorewall 'Drop', which is equal to DROP,
500 # but REJECT/DROP some packages to reduce logging,
501 # and ACCEPT critical ICMP types
502 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
503 # we are not interested in BROADCAST/MULTICAST/ANYCAST
504 { action
=> 'PVEFW-DropBroadcast' },
505 # ACCEPT critical ICMP types
506 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
507 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
508 # Drop packets with INVALID state
509 "-m conntrack --ctstate INVALID -j DROP",
510 # Drop Microsoft SMB noise
511 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
512 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
513 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
514 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
515 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
516 # Drop new/NotSyn traffic so that it doesn't get logged
517 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
519 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
522 # same as shorewall 'Reject', which is equal to Reject,
523 # but REJECT/DROP some packages to reduce logging,
524 # and ACCEPT critical ICMP types
525 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
526 # we are not interested in BROADCAST/MULTICAST/ANYCAST
527 { action
=> 'PVEFW-DropBroadcast' },
528 # ACCEPT critical ICMP types
529 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
530 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
531 # Drop packets with INVALID state
532 "-m conntrack --ctstate INVALID -j DROP",
533 # Drop Microsoft SMB noise
534 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
535 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
536 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
537 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
538 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
539 # Drop new/NotSyn traffic so that it doesn't get logged
540 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
542 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
544 'PVEFW-tcpflags' => [
545 # same as shorewall tcpflags action.
546 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
547 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
548 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
549 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
550 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
551 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
554 # same as shorewall smurfs action
555 # Filter packets for smurfs (packets with a broadcast address as the source).
556 "-s 0.0.0.0/32 -j RETURN",
557 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
558 "-s 224.0.0.0/4 -g PVEFW-smurflog",
562 # iptables -p icmp -h
563 my $icmp_type_names = {
566 'destination-unreachable' => 1,
567 'network-unreachable' => 1,
568 'host-unreachable' => 1,
569 'protocol-unreachable' => 1,
570 'port-unreachable' => 1,
571 'fragmentation-needed' => 1,
572 'source-route-failed' => 1,
573 'network-unknown' => 1,
575 'network-prohibited' => 1,
576 'host-prohibited' => 1,
577 'TOS-network-unreachable' => 1,
578 'TOS-host-unreachable' => 1,
579 'communication-prohibited' => 1,
580 'host-precedence-violation' => 1,
581 'precedence-cutoff' => 1,
582 'source-quench' => 1,
584 'network-redirect' => 1,
585 'host-redirect' => 1,
586 'TOS-network-redirect' => 1,
587 'TOS-host-redirect' => 1,
589 'router-advertisement' => 1,
590 'router-solicitation' => 1,
591 'time-exceeded' => 1,
592 'ttl-zero-during-transit' => 1,
593 'ttl-zero-during-reassembly' => 1,
594 'parameter-problem' => 1,
595 'ip-header-bad' => 1,
596 'required-option-missing' => 1,
597 'timestamp-request' => 1,
598 'timestamp-reply' => 1,
599 'address-mask-request' => 1,
600 'address-mask-reply' => 1,
603 sub init_firewall_macros
{
605 $pve_fw_parsed_macros = {};
607 foreach my $k (keys %$pve_fw_macros) {
608 my $lc_name = lc($k);
609 my $macro = $pve_fw_macros->{$k};
610 if (!ref($macro->[0])) {
611 $pve_fw_macro_descr->{$k} = shift @$macro;
613 $pve_fw_preferred_macro_names->{$lc_name} = $k;
614 $pve_fw_parsed_macros->{$k} = $macro;
618 init_firewall_macros
();
621 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
626 sub get_etc_services
{
628 return $etc_services if $etc_services;
630 my $filename = "/etc/services";
632 my $fh = IO
::File-
>new($filename, O_RDONLY
);
634 warn "unable to read '$filename' - $!\n";
640 while (my $line = <$fh>) {
642 next if $line =~m/^#/;
643 next if ($line =~m/^\s*$/);
645 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
646 $services->{byid
}->{$2}->{name
} = $1;
647 $services->{byid
}->{$2}->{port
} = $2;
648 $services->{byid
}->{$2}->{$3} = 1;
649 $services->{byname
}->{$1} = $services->{byid
}->{$2};
655 $etc_services = $services;
658 return $etc_services;
663 sub get_etc_protocols
{
664 return $etc_protocols if $etc_protocols;
666 my $filename = "/etc/protocols";
668 my $fh = IO
::File-
>new($filename, O_RDONLY
);
670 warn "unable to read '$filename' - $!\n";
676 while (my $line = <$fh>) {
678 next if $line =~m/^#/;
679 next if ($line =~m/^\s*$/);
681 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
682 $protocols->{byid
}->{$2}->{name
} = $1;
683 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
689 $etc_protocols = $protocols;
691 return $etc_protocols;
694 my $ipv4_mask_hash_localnet = {
696 '255.255.128.0' => 17,
697 '255.255.192.0' => 18,
698 '255.255.224.0' => 19,
699 '255.255.240.0' => 20,
700 '255.255.248.0' => 21,
701 '255.255.252.0' => 22,
702 '255.255.254.0' => 23,
703 '255.255.255.0' => 24,
704 '255.255.255.128' => 25,
705 '255.255.255.192' => 26,
706 '255.255.255.224' => 27,
707 '255.255.255.240' => 28,
708 '255.255.255.248' => 29,
709 '255.255.255.252' => 30,
715 my ($new_value) = @_;
717 $__local_network = $new_value if defined($new_value);
719 return $__local_network if defined($__local_network);
722 my $nodename = PVE
::INotify
::nodename
();
724 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
726 my $testip = Net
::IP-
>new($ip);
728 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
729 foreach my $entry (@$routes) {
730 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
731 next if !defined($mask);
732 return if $mask eq '0.0.0.0';
733 my $cidr = "$entry->{dest}/$mask";
734 my $testnet = Net
::IP-
>new($cidr);
735 if ($testnet->overlaps($testip)) {
736 $__local_network = $cidr;
743 return $__local_network;
746 my $max_iptables_ipset_name_length = 27;
748 sub compute_ipset_chain_name
{
749 my ($vmid, $ipset_name) = @_;
751 $vmid = 0 if !defined($vmid);
753 my $id = "$vmid-${ipset_name}";
756 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
757 $id = PVE
::Tools
::fnv31a_hex
($id);
763 sub parse_address_list
{
766 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
767 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
771 if ($str =~ m/^${ip_alias_pattern}$/) {
772 die "alias name too long\n" if length($str) > $max_alias_name_length;
778 foreach my $elem (split(/,/, $str)) {
780 if (!Net
::IP-
>new($elem)) {
781 my $err = Net
::IP
::Error
();
782 die "invalid IP address: $err\n";
784 $iprange = 1 if $elem =~ m/-/;
787 die "you can use a range in a list\n" if $iprange && $count > 1;
790 sub parse_port_name_number_or_range
{
793 my $services = PVE
::Firewall
::get_etc_services
();
797 foreach my $item (split(/,/, $str)) {
799 if ($item =~ m/^(\d+):(\d+)$/) {
800 my ($port1, $port2) = ($1, $2);
801 die "invalid port '$port1'\n" if $port1 > 65535;
802 die "invalid port '$port2'\n" if $port2 > 65535;
803 } elsif ($item =~ m/^(\d+)$/) {
805 die "invalid port '$port'\n" if $port > 65535;
807 if ($icmp_type_names->{$item}) {
810 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
815 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
820 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
821 sub pve_fw_verify_port_spec
{
824 parse_port_name_number_or_range
($portstr);
829 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
830 sub pve_fw_verify_v4addr_spec
{
833 parse_address_list
($list);
838 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
839 sub pve_fw_verify_protocol_spec
{
842 my $protocols = get_etc_protocols
();
844 die "unknown protocol '$proto'\n" if $proto &&
845 !(defined($protocols->{byname
}->{$proto}) ||
846 defined($protocols->{byid
}->{$proto}));
852 # helper function for API
854 sub copy_opject_with_digest
{
857 my $sha = Digest
::SHA-
>new('sha1');
860 foreach my $k (sort keys %$object) {
861 my $v = $object->{$k};
862 next if !defined($v);
864 $sha->add($k, ':', $v, "\n");
867 my $digest = $sha->hexdigest;
869 $res->{digest
} = $digest;
871 return wantarray ?
($res, $digest) : $res;
874 sub copy_list_with_digest
{
877 my $sha = Digest
::SHA-
>new('sha1');
880 foreach my $entry (@$list) {
882 foreach my $k (sort keys %$entry) {
883 my $v = $entry->{$k};
884 next if !defined($v);
886 # Note: digest ignores refs ($rule->{errors})
887 $sha->add($k, ':', $v, "\n") if !ref($v); ;
892 my $digest = $sha->hexdigest;
894 foreach my $entry (@$res) {
895 $entry->{digest
} = $digest;
898 return wantarray ?
($res, $digest) : $res;
901 my $rule_properties = {
903 description
=> "Update rule at position <pos>.",
908 digest
=> get_standard_option
('pve-config-digest'),
912 enum
=> ['in', 'out', 'group'],
915 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
918 pattern
=> $security_group_name_pattern,
927 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
929 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
933 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
937 type
=> 'string', format
=> 'pve-fw-protocol-spec',
945 type
=> 'string', format
=> 'pve-fw-port-spec',
949 type
=> 'string', format
=> 'pve-fw-port-spec',
958 sub add_rule_properties
{
959 my ($properties) = @_;
961 foreach my $k (keys %$rule_properties) {
962 my $h = $rule_properties->{$k};
963 # copy data, so that we can modify later without side effects
964 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
970 sub delete_rule_properties
{
971 my ($rule, $delete_str) = @_;
973 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
974 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
975 if !defined($rule_properties->{$opt});
976 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
977 if $opt eq 'type' || $opt eq 'action';
978 delete $rule->{$opt};
984 my $apply_macro = sub {
985 my ($macro_name, $param, $verify) = @_;
987 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
988 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
992 foreach my $templ (@$macro_rules) {
995 foreach my $k (keys %$templ) {
996 my $v = $templ->{$k};
999 $param_used->{$k} = 1;
1000 } elsif ($v eq 'DEST') {
1001 $v = $param->{dest
};
1002 $param_used->{dest
} = 1;
1003 } elsif ($v eq 'SOURCE') {
1004 $v = $param->{source
};
1005 $param_used->{source
} = 1;
1009 my $msg = "missing parameter '$k' in macro '$macro_name'";
1010 raise_param_exc
({ macro => $msg }) if $verify;
1015 foreach my $k (keys %$param) {
1016 next if $k eq 'macro';
1017 next if !defined($param->{$k});
1018 next if $param_used->{$k};
1019 if (defined($rule->{$k})) {
1020 if ($rule->{$k} ne $param->{$k}) {
1021 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1022 raise_param_exc
({ $k => $msg }) if $verify;
1026 $rule->{$k} = $param->{$k};
1029 push @$rules, $rule;
1035 my $rule_env_iface_lookup = {
1044 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1046 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1048 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1049 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1051 my $errors = $rule->{errors
} || {};
1053 my $error_count = 0;
1055 my $add_error = sub {
1056 my ($param, $msg) = @_;
1058 raise_param_exc
({ $param => $msg }) if !$noerr;
1060 $errors->{$param} = $msg if !$errors->{$param};
1063 my $check_ipset_or_alias_property = sub {
1066 if (my $value = $rule->{$name}) {
1067 if ($value =~ m/^\+/) {
1068 if ($value =~ m/^\+(${security_group_name_pattern})$/) {
1069 &$add_error($name, "no such ipset '$1'")
1070 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1073 &$add_error($name, "invalid security group name '$value'");
1075 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1076 my $alias = lc($value);
1077 &$add_error($name, "no such alias '$value'")
1078 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}))
1083 my $type = $rule->{type
};
1084 my $action = $rule->{action
};
1086 &$add_error('type', "missing property") if !$type;
1087 &$add_error('action', "missing property") if !$action;
1090 if ($type eq 'in' || $type eq 'out') {
1091 &$add_error('action', "unknown action '$action'")
1092 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1093 } elsif ($type eq 'group') {
1094 &$add_error('type', "security groups not allowed")
1096 &$add_error('action', "invalid characters in security group name")
1097 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1099 &$add_error('type', "unknown rule type '$type'");
1103 if ($rule->{iface
}) {
1104 &$add_error('type', "parameter -i not allowed for this rule type")
1106 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1107 &$add_error('iface', $@) if $@;
1108 if ($rule_env eq 'vm') {
1109 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1110 if $rule->{iface
} !~ m/^net(\d+)$/;
1111 } elsif ($rule_env eq 'ct') {
1112 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1113 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1117 if ($rule->{macro}) {
1118 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1119 $rule->{macro} = $preferred_name;
1121 &$add_error('macro', "unknown macro '$rule->{macro}'");
1125 if ($rule->{proto
}) {
1126 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1127 &$add_error('proto', $@) if $@;
1130 if ($rule->{dport
}) {
1131 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1132 &$add_error('dport', $@) if $@;
1133 &$add_error('proto', "missing property - 'dport' requires this property")
1137 if ($rule->{sport
}) {
1138 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1139 &$add_error('sport', $@) if $@;
1140 &$add_error('proto', "missing property - 'sport' requires this property")
1144 if ($rule->{source
}) {
1145 eval { parse_address_list
($rule->{source
}); };
1146 &$add_error('source', $@) if $@;
1147 &$check_ipset_or_alias_property('source');
1150 if ($rule->{dest
}) {
1151 eval { parse_address_list
($rule->{dest
}); };
1152 &$add_error('dest', $@) if $@;
1153 &$check_ipset_or_alias_property('dest');
1156 if ($rule->{macro} && !$error_count) {
1157 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1159 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1160 my $eh = $err->{errors
};
1161 foreach my $p (keys %$eh) {
1162 &$add_error($p, $eh->{$p});
1165 &$add_error('macro', "$err");
1170 $rule->{errors
} = $errors if $error_count;
1175 sub copy_rule_data
{
1176 my ($rule, $param) = @_;
1178 foreach my $k (keys %$rule_properties) {
1179 if (defined(my $v = $param->{$k})) {
1180 if ($v eq '' || $v eq '-') {
1192 my $bridge_firewall_enabled = 0;
1194 sub enable_bridge_firewall
{
1196 return if $bridge_firewall_enabled; # only once
1198 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1199 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1201 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1202 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1204 $bridge_firewall_enabled = 1;
1207 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1209 sub iptables_restore_cmdlist
{
1212 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1215 sub ipset_restore_cmdlist
{
1218 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1221 sub iptables_get_chains
{
1225 # check what chains we want to track
1226 my $is_pvefw_chain = sub {
1229 return 1 if $name =~ m/^PVEFW-\S+$/;
1231 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1233 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1235 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1237 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1238 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1250 return if $line =~ m/^#/;
1251 return if $line =~ m/^\s*$/;
1253 if ($line =~ m/^\*(\S+)$/) {
1258 return if $table ne 'filter';
1260 if ($line =~ m/^:(\S+)\s/) {
1262 return if !&$is_pvefw_chain($chain);
1263 $res->{$chain} = "unknown";
1264 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1265 my ($chain, $sig) = ($1, $2);
1266 return if !&$is_pvefw_chain($chain);
1267 $res->{$chain} = $sig;
1268 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1271 # simply ignore the rest
1276 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1278 return wantarray ?
($res, $hooks) : $res;
1281 sub iptables_chain_digest
{
1283 my $digest = Digest
::SHA-
>new('sha1');
1284 foreach my $rule (@$rules) { # order is important
1285 $digest->add($rule);
1287 return $digest->b64digest;
1290 sub ipset_chain_digest
{
1293 my $digest = Digest
::SHA-
>new('sha1');
1294 foreach my $rule (sort @$rules) { # note: sorted
1295 $digest->add($rule);
1297 return $digest->b64digest;
1300 sub ipset_get_chains
{
1308 return if $line =~ m/^#/;
1309 return if $line =~ m/^\s*$/;
1310 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1312 $line =~ s/\s+$//; # delete trailing white space
1313 push @{$chains->{$chain}}, $line;
1315 # simply ignore the rest
1320 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1322 # compute digest for each chain
1323 foreach my $chain (keys %$chains) {
1324 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1330 sub ruleset_generate_cmdstr
{
1331 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1333 return if defined($rule->{enable
}) && !$rule->{enable
};
1334 return if $rule->{errors
};
1336 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1338 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1339 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1343 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1344 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1346 my $source = $rule->{source
};
1347 my $dest = $rule->{dest
};
1350 if ($source =~ m/^\+/) {
1351 if ($source =~ m/^\+(${security_group_name_pattern})$/) {
1353 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1354 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1355 push @cmd, "-m set --match-set ${ipset_chain} src";
1356 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1357 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1358 push @cmd, "-m set --match-set ${ipset_chain} src";
1360 die "no such ipset '$name'\n";
1363 die "invalid security group name '$source'\n";
1365 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1366 my $alias = lc($source);
1367 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1368 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1369 die "no such alias '$source'\n" if !$e;
1370 push @cmd, "-s $e->{cidr}";
1371 } elsif ($source =~ m/\-/){
1372 push @cmd, "-m iprange --src-range $source";
1374 push @cmd, "-s $source";
1379 if ($dest =~ m/^\+/) {
1380 if ($dest =~ m/^\+(${security_group_name_pattern})$/) {
1382 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1383 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1384 push @cmd, "-m set --match-set ${ipset_chain} dst";
1385 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1386 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1387 push @cmd, "-m set --match-set ${ipset_chain} dst";
1389 die "no such ipset '$name'\n";
1392 die "invalid security group name '$dest'\n";
1394 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1395 my $alias = lc($dest);
1396 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1397 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1398 die "no such alias '$dest'\n" if !$e;
1399 push @cmd, "-d $e->{cidr}";
1400 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1401 push @cmd, "-m iprange --dst-range $dest";
1403 push @cmd, "-d $dest";
1407 if ($rule->{proto
}) {
1408 push @cmd, "-p $rule->{proto}";
1411 $multiport++ if $nbdport > 1;
1412 $multiport++ if $nbsport > 1;
1414 push @cmd, "--match multiport" if $multiport;
1416 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1417 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1419 if ($rule->{dport
}) {
1420 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1421 # Note: we use dport to store --icmp-type
1422 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1423 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1426 if ($multiport == 2) {
1427 push @cmd, "--ports $rule->{dport}";
1429 push @cmd, "--dports $rule->{dport}";
1432 push @cmd, "--dport $rule->{dport}";
1437 if ($rule->{sport
}) {
1439 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1441 push @cmd, "--sport $rule->{sport}";
1444 } elsif ($rule->{dport
} || $rule->{sport
}) {
1445 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1446 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1449 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1451 if (my $action = $rule->{action
}) {
1452 $action = $actions->{$action} if defined($actions->{$action});
1453 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1454 push @cmd, $goto ?
"-g $action" : "-j $action";
1457 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1460 sub ruleset_generate_rule
{
1461 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1465 if ($rule->{macro}) {
1466 $rules = &$apply_macro($rule->{macro}, $rule);
1471 # update all or nothing
1474 foreach my $tmp (@$rules) {
1475 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1476 push @cmds, $cmdstr;
1480 foreach my $cmdstr (@cmds) {
1481 ruleset_addrule
($ruleset, $chain, $cmdstr);
1485 sub ruleset_generate_rule_insert
{
1486 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1488 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1490 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1491 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1495 sub ruleset_create_chain
{
1496 my ($ruleset, $chain) = @_;
1498 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1499 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1501 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1503 $ruleset->{$chain} = [];
1506 sub ruleset_chain_exist
{
1507 my ($ruleset, $chain) = @_;
1509 return $ruleset->{$chain} ?
1 : undef;
1512 sub ruleset_addrule
{
1513 my ($ruleset, $chain, $rule) = @_;
1515 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1517 push @{$ruleset->{$chain}}, "-A $chain $rule";
1520 sub ruleset_insertrule
{
1521 my ($ruleset, $chain, $rule) = @_;
1523 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1525 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1528 sub get_log_rule_base
{
1529 my ($chain, $vmid, $msg, $loglevel) = @_;
1531 die "internal error - no log level" if !defined($loglevel);
1533 $vmid = 0 if !defined($vmid);
1535 # Note: we use special format for prefix to pass further
1536 # info to log daemon (VMID, LOGVELEL and CHAIN)
1538 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1541 sub ruleset_addlog {
1542 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1544 return if !defined($loglevel);
1546 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1548 $logrule = "$rule $logrule" if defined($rule);
1550 ruleset_addrule($ruleset, $chain, $logrule);
1553 sub ruleset_add_chain_policy {
1554 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1556 if ($policy eq 'ACCEPT') {
1558 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1559 { ACCEPT => $accept_action});
1561 } elsif ($policy eq 'DROP') {
1563 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1565 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1567 ruleset_addrule($ruleset, $chain, "-j DROP
");
1568 } elsif ($policy eq 'REJECT') {
1569 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1571 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1573 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1576 die "internal error
: unknown policy
'$policy'";
1580 sub ruleset_chain_add_conn_filters {
1581 my ($ruleset, $chain, $accept) = @_;
1583 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1584 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1587 sub ruleset_chain_add_input_filters {
1588 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1590 if ($cluster_conf->{ipset}->{blacklist}){
1591 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1592 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1593 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1594 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1596 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1597 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1600 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1601 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1604 if ($options->{tcpflags}) {
1605 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1609 sub ruleset_create_vm_chain {
1610 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1612 ruleset_create_chain($ruleset, $chain);
1613 my $accept = generate_nfqueue($options);
1615 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1616 if ($direction eq 'OUT') {
1617 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1618 proto => 'udp', sport => 68, dport => 67 });
1620 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1621 proto => 'udp', sport => 67, dport => 68 });
1625 if ($direction eq 'OUT') {
1626 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1627 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1629 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1633 sub ruleset_add_group_rule {
1634 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1636 my $group = $rule->{action};
1637 my $group_chain = "GROUP-
$group-$direction";
1638 if(!ruleset_chain_exist($ruleset, $group_chain)){
1639 generate_group_rules($ruleset, $cluster_conf, $group);
1642 if ($direction eq 'OUT' && $rule->{iface_out}) {
1643 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1644 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1645 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1647 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1650 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1653 sub ruleset_generate_vm_rules {
1654 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options) = @_;
1656 my $lc_direction = lc($direction);
1658 my $in_accept = generate_nfqueue($options);
1660 foreach my $rule (@$rules) {
1661 next if $rule->{iface} && $rule->{iface} ne $netid;
1662 next if !$rule->{enable} || $rule->{errors};
1663 if ($rule->{type} eq 'group') {
1664 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1665 $direction eq 'OUT' ? 'RETURN' : $in_accept);
1667 next if $rule->{type} ne $lc_direction;
1669 if ($direction eq 'OUT') {
1670 ruleset_generate_rule($ruleset, $chain, $rule,
1671 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1672 undef, $cluster_conf, $vmfw_conf);
1674 ruleset_generate_rule($ruleset, $chain, $rule,
1675 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1676 undef, $cluster_conf, $vmfw_conf);
1684 sub generate_nfqueue {
1687 if ($options->{ips}) {
1688 my $action = "NFQUEUE
";
1689 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1690 if (defined($3) && defined($1)) {
1691 $action .= " --queue-balance
$1:$3";
1692 } elsif (defined($1)) {
1693 $action .= " --queue-num
$1";
1696 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1703 sub ruleset_generate_vm_ipsrules {
1704 my ($ruleset, $options, $direction, $iface) = @_;
1706 if ($options->{ips} && $direction eq 'IN') {
1707 my $nfqueue = generate_nfqueue($options);
1709 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1710 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1713 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1717 sub generate_venet_rules_direction {
1718 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1720 my $lc_direction = lc($direction);
1722 my $rules = $vmfw_conf->{rules};
1724 my $options = $vmfw_conf->{options};
1725 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1727 my $chain = "venet0-
$vmid-$direction";
1729 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1731 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction);
1736 if ($direction eq 'OUT') {
1737 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1739 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1742 my $accept = generate_nfqueue($options);
1743 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1744 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1746 if ($direction eq 'OUT') {
1747 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1750 iface_in => 'venet0'});
1752 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1755 iface_out => 'venet0'});
1759 sub generate_tap_rules_direction {
1760 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
1762 my $lc_direction = lc($direction);
1764 my $rules = $vmfw_conf->{rules};
1766 my $options = $vmfw_conf->{options};
1767 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1769 my $tapchain = "$iface-$direction";
1771 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1773 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options);
1775 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1780 if ($direction eq 'OUT') {
1781 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1783 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1786 my $accept = generate_nfqueue($options);
1787 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1788 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1790 # plug the tap chain to bridge chain
1791 if ($direction eq 'IN') {
1792 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
1793 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1795 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
1796 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
1800 sub enable_host_firewall {
1801 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1803 my $options = $hostfw_conf->{options};
1804 my $cluster_options = $cluster_conf->{options};
1805 my $rules = $hostfw_conf->{rules};
1806 my $cluster_rules = $cluster_conf->{rules};
1808 # host inbound firewall
1809 my $chain = "PVEFW-HOST-IN
";
1810 ruleset_create_chain($ruleset, $chain);
1812 my $loglevel = get_option_log_level($options, "log_level_in
");
1814 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1816 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1817 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1819 # we use RETURN because we need to check also tap rules
1820 my $accept_action = 'RETURN';
1822 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1824 # add host rules first, so that cluster wide rules can be overwritten
1825 foreach my $rule (@$rules, @$cluster_rules) {
1826 next if !$rule->{enable} || $rule->{errors};
1828 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1831 if ($rule->{type} eq 'group') {
1832 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1833 } elsif ($rule->{type} eq 'in') {
1834 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1835 undef, $cluster_conf, $hostfw_conf);
1839 delete $rule->{iface_in};
1842 # allow standard traffic for management ipset (includes cluster network)
1843 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
");
1844 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
1845 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1846 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1847 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1848 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
1850 my $localnet = local_network();
1854 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1855 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
1856 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
1859 # implement input policy
1860 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1861 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1863 # host outbound firewall
1864 $chain = "PVEFW-HOST-OUT
";
1865 ruleset_create_chain($ruleset, $chain);
1867 $loglevel = get_option_log_level($options, "log_level_out
");
1869 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1871 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1873 # we use RETURN because we may want to check other thigs later
1874 $accept_action = 'RETURN';
1876 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1878 # add host rules first, so that cluster wide rules can be overwritten
1879 foreach my $rule (@$rules, @$cluster_rules) {
1880 next if !$rule->{enable} || $rule->{errors};
1882 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1884 if ($rule->{type} eq 'group') {
1885 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1886 } elsif ($rule->{type} eq 'out') {
1887 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1888 undef, $cluster_conf, $hostfw_conf);
1892 delete $rule->{iface_out};
1895 # allow standard traffic on cluster network
1897 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1898 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
1899 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1900 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1902 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1903 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
1904 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
1907 # implement output policy
1908 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1909 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1911 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1912 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1915 sub generate_group_rules {
1916 my ($ruleset, $cluster_conf, $group) = @_;
1918 my $rules = $cluster_conf->{groups}->{$group};
1921 warn "no such security group
'$group'\n";
1922 $rules = []; # create empty chain
1925 my $chain = "GROUP-
${group
}-IN
";
1927 ruleset_create_chain($ruleset, $chain);
1928 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1930 foreach my $rule (@$rules) {
1931 next if $rule->{type} ne 'in';
1932 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1935 $chain = "GROUP-
${group
}-OUT
";
1937 ruleset_create_chain($ruleset, $chain);
1938 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1940 foreach my $rule (@$rules) {
1941 next if $rule->{type} ne 'out';
1942 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1943 # check also other tap rules later
1944 ruleset_generate_rule($ruleset, $chain, $rule,
1945 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1950 my $valid_netdev_names = {};
1951 for (my $i = 0; $i < $MAX_NETS; $i++) {
1952 $valid_netdev_names->{"net
$i"} = 1;
1956 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
1960 my $orig_line = $line;
1964 # we can add single line comments to the end of the rule
1965 if ($line =~ s/#\s*(.*?)\s*$//) {
1966 $rule->{comment} = decode('utf8', $1);
1969 # we can disable a rule when prefixed with '|'
1971 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
1973 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1974 die "unable to parse rule
: $line\n";
1976 $rule->{type} = lc($1);
1977 $rule->{action} = $2;
1979 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1980 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1981 $rule->{macro} = $1;
1982 $rule->{action} = $2;
1986 while (length($line)) {
1987 if ($line =~ s/^-i (\S+)\s*//) {
1988 $rule->{iface} = $1;
1992 last if $rule->{type} eq 'group';
1994 if ($line =~ s/^-p (\S+)\s*//) {
1995 $rule->{proto} = $1;
1999 if ($line =~ s/^-dport (\S+)\s*//) {
2000 $rule->{dport} = $1;
2004 if ($line =~ s/^-sport (\S+)\s*//) {
2005 $rule->{sport} = $1;
2008 if ($line =~ s/^-source (\S+)\s*//) {
2009 $rule->{source} = $1;
2012 if ($line =~ s/^-dest (\S+)\s*//) {
2020 die "unable to parse rule parameters
: $line\n" if length($line);
2022 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2023 if ($verbose && $rule->{errors}) {
2024 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2025 foreach my $p (keys %{$rule->{errors}}) {
2026 warn " $p: $rule->{errors
}->{$p}\n";
2033 sub parse_vmfw_option {
2038 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2040 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2043 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2045 $value = $2 ? lc($3) : '';
2046 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2049 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2054 die "can
't parse option '$line'\n"
2057 return ($opt, $value);
2060 sub parse_hostfw_option {
2065 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2067 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2070 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2072 $value = $2 ? lc($3) : '';
2073 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2078 die "can't parse option
'$line'\n"
2081 return ($opt, $value);
2084 sub parse_clusterfw_option {
2089 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2092 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2097 die "can
't parse option '$line'\n"
2100 return ($opt, $value);
2106 # we can add single line comments to the end of the line
2107 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2109 if ($line =~ m/^(\S+)\s(\S+)$/) {
2110 my ($name, $cidr) = ($1, $2);
2112 pve_verify_ipv4_or_cidr($cidr);
2117 $data->{comment} = $comment if $comment;
2124 sub generic_fw_rules_parser {
2125 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2130 my $res = $empty_conf;
2132 while (defined(my $line = <$fh>)) {
2133 next if $line =~ m/^#/;
2134 next if $line =~ m/^\s*$/;
2136 my $linenr = $fh->input_line_number();
2137 my $prefix = "$filename (line $linenr)";
2139 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2140 $section = 'options
';
2144 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2145 $section = 'aliases
';
2149 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2150 $section = 'groups
';
2153 $res->{$section}->{$group} = [];
2154 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2159 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2164 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2168 $res->{$section}->{$group} = [];
2169 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2175 warn "$prefix: skip line - no section\n";
2179 if ($section eq 'options
') {
2182 if ($rule_env eq 'cluster
') {
2183 ($opt, $value) = parse_clusterfw_option($line);
2184 } elsif ($rule_env eq 'host
') {
2185 ($opt, $value) = parse_hostfw_option($line);
2187 ($opt, $value) = parse_vmfw_option($line);
2189 $res->{options}->{$opt} = $value;
2191 warn "$prefix: $@" if $@;
2192 } elsif ($section eq 'aliases
') {
2194 my $data = parse_alias($line);
2195 $res->{aliases}->{lc($data->{name})} = $data;
2197 warn "$prefix: $@" if $@;
2198 } elsif ($section eq 'rules
') {
2200 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2202 warn "$prefix: $err";
2205 push @{$res->{$section}}, $rule;
2206 } elsif ($section eq 'groups
') {
2208 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2210 warn "$prefix: $err";
2213 push @{$res->{$section}->{$group}}, $rule;
2214 } elsif ($section eq 'ipset
') {
2215 # we can add single line comments to the end of the rule
2216 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2218 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2222 if($cidr !~ m/^${ip_alias_pattern}$/) {
2225 eval { pve_verify_ipv4_or_cidr($cidr); };
2227 warn "$prefix: $cidr - $err";
2232 my $entry = { cidr => $cidr };
2233 $entry->{nomatch} = 1 if $nomatch;
2234 $entry->{comment} = $comment if $comment;
2236 push @{$res->{$section}->{$group}}, $entry;
2238 warn "$prefix: skip line - unknown section\n";
2246 sub parse_host_fw_rules {
2247 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2249 my $empty_conf = { rules => [], options => {}};
2251 return generic_fw_rules_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2254 sub parse_vm_fw_rules {
2255 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2262 ipset_comments => {},
2265 return generic_fw_rules_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2268 sub parse_cluster_fw_rules {
2269 my ($filename, $fh, $verbose) = @_;
2279 group_comments => {},
2281 ipset_comments => {},
2284 return generic_fw_rules_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2288 my ($code, @param) = @_;
2292 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2299 sub read_local_vm_config {
2304 my $vmdata = { openvz => $openvz, qemu => $qemu };
2306 my $vmlist = PVE::Cluster::get_vmlist();
2307 return $vmdata if !$vmlist || !$vmlist->{ids};
2308 my $ids = $vmlist->{ids};
2310 foreach my $vmid (keys %$ids) {
2311 next if !$vmid; # skip VE0
2312 my $d = $ids->{$vmid};
2313 next if !$d->{node} || $d->{node} ne $nodename;
2314 next if !$d->{type};
2315 if ($d->{type} eq 'openvz
') {
2316 if ($have_pve_manager) {
2317 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2318 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2319 $openvz->{$vmid} = $conf;
2322 } elsif ($d->{type} eq 'qemu
') {
2323 if ($have_qemu_server) {
2324 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2325 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2326 $qemu->{$vmid} = $conf;
2335 sub load_vmfw_conf {
2336 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2340 $dir = "/etc/pve/firewall" if !defined($dir);
2342 my $filename = "$dir/$vmid.fw";
2343 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2344 $vmfw_conf = parse_vm_fw_rules($filename, $fh, $cluster_conf, $rule_env, $verbose);
2345 $vmfw_conf->{vmid} = $vmid;
2351 my $format_rules = sub {
2352 my ($rules, $allow_iface) = @_;
2356 foreach my $rule (@$rules) {
2357 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2358 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2359 $raw .= uc($rule->{type});
2360 if ($rule->{macro}) {
2361 $raw .= " $rule->{macro}($rule->{action})";
2363 $raw .= " " . $rule->{action};
2365 if ($allow_iface && $rule->{iface}) {
2366 $raw .= " -i $rule->{iface}";
2369 if ($rule->{type} ne 'group
') {
2370 $raw .= " -source $rule->{source}" if $rule->{source};
2371 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2372 $raw .= " -p $rule->{proto}" if $rule->{proto};
2373 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2374 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2377 $raw .= " # " . encode('utf8
', $rule->{comment})
2378 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2381 die "unknown rule type '$rule->{type
}'";
2388 my $format_options = sub {
2393 $raw .= "[OPTIONS]\n\n";
2394 foreach my $opt (keys %$options) {
2395 $raw .= "$opt: $options->{$opt}\n";
2402 my $format_aliases = sub {
2407 $raw .= "[ALIASES]\n\n";
2408 foreach my $k (keys %$aliases) {
2409 my $e = $aliases->{$k};
2410 $raw .= "$e->{name} $e->{cidr}";
2411 $raw .= " # " . encode('utf8
', $e->{comment})
2412 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2420 my $format_ipsets = sub {
2425 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2426 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2427 my $utf8comment = encode('utf8
', $comment);
2428 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2430 $raw .= "[IPSET $ipset]\n\n";
2432 my $options = $fw_conf->{ipset}->{$ipset};
2435 foreach my $entry (@$options) {
2436 $nethash->{$entry->{cidr}} = $entry;
2439 foreach my $cidr (sort keys %$nethash) {
2440 my $entry = $nethash->{$cidr};
2441 my $line = $entry->{nomatch} ? '!' : '';
2442 $line .= $entry->{cidr};
2443 $line .= " # " . encode('utf8
', $entry->{comment})
2444 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2454 sub save_vmfw_conf {
2455 my ($vmid, $vmfw_conf) = @_;
2459 my $options = $vmfw_conf->{options};
2460 $raw .= &$format_options($options) if scalar(keys %$options);
2462 my $aliases = $vmfw_conf->{aliases};
2463 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2465 $raw .= &$format_ipsets($vmfw_conf);
2467 my $rules = $vmfw_conf->{rules} || [];
2468 if (scalar(@$rules)) {
2469 $raw .= "[RULES]\n\n";
2470 $raw .= &$format_rules($rules, 1);
2474 my $filename = "/etc/pve/firewall/$vmid.fw";
2475 PVE::Tools::file_set_contents($filename, $raw);
2478 sub read_vm_firewall_configs {
2479 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2481 my $vmfw_configs = {};
2483 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2484 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2485 next if !$vmfw_conf->{options}; # skip if file does not exists
2486 $vmfw_configs->{$vmid} = $vmfw_conf;
2488 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2489 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2490 next if !$vmfw_conf->{options}; # skip if file does not exists
2491 $vmfw_configs->{$vmid} = $vmfw_conf;
2494 return $vmfw_configs;
2497 sub get_option_log_level {
2498 my ($options, $k) = @_;
2500 my $v = $options->{$k};
2501 $v = $default_log_level if !defined($v);
2503 return undef if $v eq '' || $v eq 'nolog
';
2505 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2507 return $v if ($v >= 0) && ($v <= 7);
2509 warn "unknown log level ($k = '$v')\n";
2514 sub generate_std_chains {
2515 my ($ruleset, $options) = @_;
2517 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2519 # same as shorewall smurflog.
2520 my $chain = 'PVEFW-smurflog
';
2521 $pve_std_chains->{$chain} = [];
2523 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2524 push @{$pve_std_chains->{$chain}}, "-j DROP";
2526 # same as shorewall logflags action.
2527 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2528 $chain = 'PVEFW-logflags
';
2529 $pve_std_chains->{$chain} = [];
2531 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2532 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2533 push @{$pve_std_chains->{$chain}}, "-j DROP";
2535 foreach my $chain (keys %$pve_std_chains) {
2536 ruleset_create_chain($ruleset, $chain);
2537 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2539 ruleset_generate_rule($ruleset, $chain, $rule);
2541 ruleset_addrule($ruleset, $chain, $rule);
2547 sub generate_ipset_chains {
2548 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2550 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2551 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2552 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2556 sub generate_ipset {
2557 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2559 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2561 my $hashsize = scalar(@$options);
2562 if ($hashsize <= 64) {
2565 $hashsize = round_powerof2($hashsize);
2568 $ipset_ruleset->{$name} = ["create $name hash:net family inet hashsize $hashsize maxelem $hashsize"];
2572 foreach my $entry (@$options) {
2573 my $cidr = $entry->{cidr};
2574 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2575 my $alias = lc($cidr);
2576 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2577 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2579 $entry->{cidr} = $e->{cidr};
2580 $nethash->{$entry->{cidr}} = $entry;
2582 warn "no such alias '$cidr'\n";
2585 $nethash->{$entry->{cidr}} = $entry;
2589 foreach my $cidr (sort keys %$nethash) {
2590 my $entry = $nethash->{$cidr};
2592 my $cmd = "add $name $cidr";
2593 if ($entry->{nomatch}) {
2594 if ($feature_ipset_nomatch) {
2595 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2597 warn "ignore !$cidr - nomatch not supported by kernel\n";
2600 push @{$ipset_ruleset->{$name}}, $cmd;
2605 sub round_powerof2 {
2609 $int |= $int >> $_ foreach (1,2,4,8,16);
2613 sub load_clusterfw_conf {
2614 my ($filename, $verbose) = @_;
2616 $filename = $clusterfw_conf_filename if !defined($filename);
2618 my $cluster_conf = {};
2619 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2620 $cluster_conf = parse_cluster_fw_rules($filename, $fh, $verbose);
2623 return $cluster_conf;
2626 sub save_clusterfw_conf {
2627 my ($cluster_conf) = @_;
2631 my $options = $cluster_conf->{options};
2632 $raw .= &$format_options($options) if scalar(keys %$options);
2634 my $aliases = $cluster_conf->{aliases};
2635 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2637 $raw .= &$format_ipsets($cluster_conf);
2639 my $rules = $cluster_conf->{rules};
2640 if (scalar(@$rules)) {
2641 $raw .= "[RULES]\n\n";
2642 $raw .= &$format_rules($rules, 1);
2646 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2647 my $rules = $cluster_conf->{groups}->{$group};
2648 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2649 my $utf8comment = encode('utf8
', $comment);
2650 $raw .= "[group $group] # $utf8comment\n\n";
2652 $raw .= "[group $group]\n\n";
2655 $raw .= &$format_rules($rules, 0);
2659 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2662 sub load_hostfw_conf {
2663 my ($cluster_conf, $filename, $verbose) = @_;
2665 $filename = $hostfw_conf_filename if !defined($filename);
2667 my $hostfw_conf = {};
2668 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2669 $hostfw_conf = parse_host_fw_rules($filename, $fh, $cluster_conf, $verbose);
2671 return $hostfw_conf;
2674 sub save_hostfw_conf {
2675 my ($hostfw_conf) = @_;
2679 my $options = $hostfw_conf->{options};
2680 $raw .= &$format_options($options) if scalar(keys %$options);
2682 my $rules = $hostfw_conf->{rules};
2683 if (scalar(@$rules)) {
2684 $raw .= "[RULES]\n\n";
2685 $raw .= &$format_rules($rules, 1);
2689 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2693 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
2697 if ($vmdata) { # test mode
2698 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2699 my $filename = "$testdir/cluster.fw";
2700 $cluster_conf = load_clusterfw_conf($filename, $verbose);
2702 $filename = "$testdir/host.fw";
2703 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
2705 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
2706 } else { # normal operation
2707 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
2709 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
2711 $vmdata = read_local_vm_config();
2712 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
2715 $cluster_conf->{ipset}->{venet0} = [];
2716 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
2719 if ($cluster_conf->{aliases}->{local_network}) {
2720 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2722 $localnet = local_network() || '127.0.0.0/8';
2723 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2726 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
2730 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2731 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2733 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2735 my $hostfw_options = $hostfw_conf->{options} || {};
2737 # fixme: what log level should we use here?
2738 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2740 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2743 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2744 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2745 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2747 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2748 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2750 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2752 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2753 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2755 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2756 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2758 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2760 generate_std_chains($ruleset, $hostfw_options);
2762 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2764 my $ipset_ruleset = {};
2766 if ($hostfw_enable) {
2767 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2768 warn $@ if $@; # just to be sure - should not happen
2771 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2773 # generate firewall rules for QEMU VMs
2774 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2776 my $conf = $vmdata->{qemu}->{$vmid};
2777 my $vmfw_conf = $vmfw_configs->{$vmid};
2778 return if !$vmfw_conf;
2779 return if !$vmfw_conf->{options}->{enable};
2781 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2783 foreach my $netid (keys %$conf) {
2784 next if $netid !~ m/^net(\d+)$/;
2785 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2786 next if !$net->{firewall};
2787 my $iface = "tap${vmid}i$1";
2789 my $macaddr = $net->{macaddr};
2790 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2791 $vmfw_conf, $vmid, 'IN
');
2792 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2793 $vmfw_conf, $vmid, 'OUT
');
2796 warn $@ if $@; # just to be sure - should not happen
2799 # generate firewall rules for OpenVZ containers
2800 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2802 my $conf = $vmdata->{openvz}->{$vmid};
2804 my $vmfw_conf = $vmfw_configs->{$vmid};
2805 return if !$vmfw_conf;
2806 return if !$vmfw_conf->{options}->{enable};
2808 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2810 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2811 my $ip = $conf->{ip_address}->{value};
2813 parse_address_list($ip); # make sure we have a valid $ip list
2815 my @ips = split(',', $ip);
2817 foreach my $singleip (@ips) {
2818 my $venet0ipset = {};
2819 $venet0ipset->{cidr} = $singleip;
2820 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2823 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2824 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2827 if ($conf->{netif} && $conf->{netif}->{value}) {
2828 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2829 foreach my $netid (keys %$netif) {
2830 my $d = $netif->{$netid};
2832 my $macaddr = $d->{mac};
2833 my $iface = $d->{host_ifname};
2834 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2835 $vmfw_conf, $vmid, 'IN
');
2836 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2837 $vmfw_conf, $vmid, 'OUT
');
2841 warn $@ if $@; # just to be sure - should not happen
2844 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2845 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2848 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
2850 return ($ruleset, $ipset_ruleset);
2853 sub get_ruleset_status {
2854 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2856 my $statushash = {};
2858 foreach my $chain (sort keys %$ruleset) {
2859 my $sig = &$digest_fn($ruleset->{$chain});
2861 $statushash->{$chain}->{sig} = $sig;
2863 my $oldsig = $active_chains->{$chain};
2864 if (!defined($oldsig)) {
2865 $statushash->{$chain}->{action} = 'create
';
2867 if ($oldsig eq $sig) {
2868 $statushash->{$chain}->{action} = 'exists';
2870 $statushash->{$chain}->{action} = 'update
';
2873 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2874 foreach my $cmd (@{$ruleset->{$chain}}) {
2875 print "\t$cmd\n" if $verbose;
2879 foreach my $chain (sort keys %$active_chains) {
2880 if (!defined($ruleset->{$chain})) {
2881 my $sig = $active_chains->{$chain};
2882 $statushash->{$chain}->{action} = 'delete';
2883 $statushash->{$chain}->{sig} = $sig;
2884 print "delete $chain ($sig)\n" if $verbose;
2891 sub print_sig_rule {
2892 my ($chain, $sig) = @_;
2894 # We just use this to store a SHA1 checksum used to detect changes
2895 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2898 sub get_ruleset_cmdlist {
2899 my ($ruleset, $verbose) = @_;
2901 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2903 my ($active_chains, $hooks) = iptables_get_chains();
2904 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2906 # create missing chains first
2907 foreach my $chain (sort keys %$ruleset) {
2908 my $stat = $statushash->{$chain};
2909 die "internal error" if !$stat;
2910 next if $stat->{action} ne 'create
';
2912 $cmdlist .= ":$chain - [0:0]\n";
2915 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2916 if (!$hooks->{$h}) {
2917 $cmdlist .= "-A $h -j PVEFW-$h\n";
2921 foreach my $chain (sort keys %$ruleset) {
2922 my $stat = $statushash->{$chain};
2923 die "internal error" if !$stat;
2925 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2926 $cmdlist .= "-F $chain\n";
2927 foreach my $cmd (@{$ruleset->{$chain}}) {
2928 $cmdlist .= "$cmd\n";
2930 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2931 } elsif ($stat->{action
} eq 'delete') {
2932 die "internal error"; # this should not happen
2933 } elsif ($stat->{action
} eq 'exists') {
2936 die "internal error - unknown status '$stat->{action}'";
2940 foreach my $chain (keys %$statushash) {
2941 next if $statushash->{$chain}->{action
} ne 'delete';
2942 $cmdlist .= "-F $chain\n";
2944 foreach my $chain (keys %$statushash) {
2945 next if $statushash->{$chain}->{action
} ne 'delete';
2946 next if $chain eq 'PVEFW-INPUT';
2947 next if $chain eq 'PVEFW-OUTPUT';
2948 next if $chain eq 'PVEFW-FORWARD';
2949 $cmdlist .= "-X $chain\n";
2952 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2954 $cmdlist .= "COMMIT\n";
2956 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2959 sub get_ipset_cmdlist
{
2960 my ($ruleset, $verbose) = @_;
2964 my $delete_cmdlist = "";
2966 my $active_chains = ipset_get_chains
();
2967 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2969 # remove stale _swap chains
2970 foreach my $chain (keys %$active_chains) {
2971 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2972 $cmdlist .= "destroy $chain\n";
2976 foreach my $chain (sort keys %$ruleset) {
2977 my $stat = $statushash->{$chain};
2978 die "internal error" if !$stat;
2980 if ($stat->{action
} eq 'create') {
2981 foreach my $cmd (@{$ruleset->{$chain}}) {
2982 $cmdlist .= "$cmd\n";
2986 if ($stat->{action
} eq 'update') {
2987 my $chain_swap = $chain."_swap";
2989 foreach my $cmd (@{$ruleset->{$chain}}) {
2990 $cmd =~ s/$chain/$chain_swap/;
2991 $cmdlist .= "$cmd\n";
2993 $cmdlist .= "swap $chain_swap $chain\n";
2994 $cmdlist .= "flush $chain_swap\n";
2995 $cmdlist .= "destroy $chain_swap\n";
3000 foreach my $chain (keys %$statushash) {
3001 next if $statushash->{$chain}->{action
} ne 'delete';
3003 $delete_cmdlist .= "flush $chain\n";
3004 $delete_cmdlist .= "destroy $chain\n";
3007 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3009 return ($cmdlist, $delete_cmdlist, $changes);
3013 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
3015 enable_bridge_firewall
();
3017 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3018 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3020 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3023 if ($ipset_changes) {
3024 print "ipset changes:\n";
3025 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3026 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3030 print "iptables changes:\n";
3035 ipset_restore_cmdlist
($ipset_create_cmdlist);
3037 iptables_restore_cmdlist
($cmdlist);
3039 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3041 # test: re-read status and check if everything is up to date
3042 my $active_chains = iptables_get_chains
();
3043 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3046 foreach my $chain (sort keys %$ruleset) {
3047 my $stat = $statushash->{$chain};
3048 if ($stat->{action
} ne 'exists') {
3049 warn "unable to update chain '$chain'\n";
3054 die "unable to apply firewall changes\n" if $errors;
3056 update_nf_conntrack_max
($hostfw_conf);
3058 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3062 sub update_nf_conntrack_max
{
3063 my ($hostfw_conf) = @_;
3065 my $max = 65536; # reasonable default
3067 my $options = $hostfw_conf->{options
} || {};
3069 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3070 $max = $options->{nf_conntrack_max
};
3071 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3074 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3075 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3077 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3079 if ($current != $max) {
3080 my $hashsize = int($max/4);
3081 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3082 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3086 sub update_nf_conntrack_tcp_timeout_established
{
3087 my ($hostfw_conf) = @_;
3089 my $options = $hostfw_conf->{options
} || {};
3091 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3093 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3096 sub remove_pvefw_chains
{
3098 my ($chash, $hooks) = iptables_get_chains
();
3099 my $cmdlist = "*filter\n";
3101 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3103 $cmdlist .= "-D $h -j PVEFW-$h\n";
3107 foreach my $chain (keys %$chash) {
3108 $cmdlist .= "-F $chain\n";
3111 foreach my $chain (keys %$chash) {
3112 $cmdlist .= "-X $chain\n";
3114 $cmdlist .= "COMMIT\n";
3116 iptables_restore_cmdlist
($cmdlist);
3120 my $cluster_conf = load_clusterfw_conf
();
3121 my $cluster_options = $cluster_conf->{options
};
3122 my $enable = $cluster_options->{enable
};
3126 # load required modules here
3132 my $cluster_conf = load_clusterfw_conf
();
3133 my $cluster_options = $cluster_conf->{options
};
3135 my $enable = $cluster_options->{enable
};
3137 die "Firewall is disabled - cannot start\n" if !$enable;
3140 PVE
::Firewall
::remove_pvefw_chains
();
3144 my $hostfw_conf = load_hostfw_conf
();
3146 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3148 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset);