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";
101 my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
103 my $default_log_level = 'info';
105 my $log_level_hash = {
116 # imported/converted from: /usr/share/shorewall/macro.*
117 my $pve_fw_macros = {
120 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
121 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
124 "Auth (identd) traffic",
125 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
128 "Border Gateway Protocol traffic",
129 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
132 "BitTorrent traffic for BitTorrent 3.1 and earlier",
133 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
134 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
137 "BitTorrent traffic for BitTorrent 3.2 and later",
138 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
139 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
142 "Concurrent Versions System pserver traffic",
143 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
146 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
147 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
148 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
149 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
152 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
153 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
154 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
157 "Distributed Checksum Clearinghouse spam filtering mechanism",
158 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
161 "Forwarded DHCP traffic (bidirectional)",
162 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
163 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
166 "Domain Name System traffic (upd and tcp)",
167 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
168 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
171 "Distributed Compiler service",
172 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
175 "File Transfer Protocol",
176 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
179 "Finger protocol (RFC 742)",
180 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
183 "GNUnet secure peer-to-peer networking traffic",
184 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
185 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
186 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
187 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
190 "Generic Routing Encapsulation tunneling protocol (bidirectional)",
191 { action
=> 'PARAM', proto
=> '47' },
192 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
195 "Git distributed revision control traffic",
196 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
199 "OpenPGP HTTP keyserver protocol traffic",
200 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
203 "Hypertext Transfer Protocol (WWW)",
204 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
207 "Hypertext Transfer Protocol (WWW) over SSL",
208 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
211 "Internet Cache Protocol V2 (Squid) traffic",
212 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
215 "AOL Instant Messenger traffic",
216 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
219 "Internet Message Access Protocol",
220 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
223 "Internet Message Access Protocol over SSL",
224 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
227 "IPIP capsulation traffic (bidirectional)",
228 { action
=> 'PARAM', proto
=> '94' },
229 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '94' },
232 "IPsec traffic (bidirectional)",
233 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
234 { action
=> 'PARAM', proto
=> '50' },
235 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
236 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
239 "IPsec authentication (AH) traffic (bidirectional)",
240 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
241 { action
=> 'PARAM', proto
=> '51' },
242 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
243 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '51' },
246 "IPsec traffic and Nat-Traversal (bidirectional)",
247 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
248 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
249 { action
=> 'PARAM', proto
=> '50' },
250 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500' },
251 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '4500' },
252 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
255 "Internet Relay Chat traffic",
256 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
259 "HP Jetdirect printing",
260 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
263 "Layer 2 Tunneling Protocol traffic",
264 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
265 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1701' },
268 "Lightweight Directory Access Protocol traffic",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
272 "Secure Lightweight Directory Access Protocol traffic",
273 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
276 "Microsoft Notification Protocol",
277 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
280 "Microsoft SQL Server",
281 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
284 "Mail traffic (SMTP, SMTPS, Submission)",
285 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
286 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
287 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
290 "Munin networked resource monitoring traffic",
291 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
295 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
298 "NNTP traffic (Usenet).",
299 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
302 "Encrypted NNTP traffic (Usenet)",
303 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
306 "Network Time Protocol (ntpd)",
307 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
310 "Bi-directional NTP (for NTP peers)",
311 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
312 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '123' },
315 "OSPF multicast traffic",
316 { action
=> 'PARAM', proto
=> '89' },
320 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
323 "Symantec PCAnywere (tm)",
324 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
325 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
332 "Encrypted POP3 traffic",
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
336 "Point-to-Point Tunneling Protocol",
337 { action
=> 'PARAM', proto
=> '47' },
338 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
339 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
343 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
347 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
350 "Line Printer protocol printing",
351 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
354 "Microsoft Remote Desktop Protocol traffic",
355 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
358 "Routing Information Protocol (bidirectional)",
359 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
360 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '520' },
363 "BIND remote management protocol",
364 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
367 "Razor Antispam System",
368 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
371 "Remote time retrieval (rdate)",
372 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
376 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
379 "SANE network scanning",
380 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
383 "Microsoft SMB traffic",
384 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
385 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
386 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
387 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
390 "Microsoft SMB traffic (bidirectional)",
391 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
392 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
393 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
394 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
395 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '135,445' },
396 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '137:139' },
397 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
398 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'tcp', dport
=> '135,139,445' },
401 "Samba Web Administration Tool",
402 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
405 "Simple Mail Transfer Protocol",
406 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
409 "Encrypted Simple Mail Transfer Protocol",
410 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
413 "Simple Network Management Protocol",
414 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
415 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
418 "Spam Assassin SPAMD traffic",
419 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
422 "Secure shell traffic",
423 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
426 "Subversion server (svnserve)",
427 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
430 "SixXS IPv6 Deployment and Tunnel Broker",
431 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
432 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
433 { action
=> 'PARAM', proto
=> '41' },
434 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
437 "Squid web proxy traffic",
438 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
441 "Mail message submission traffic",
442 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
445 "Syslog protocol (RFC 5424) traffic",
446 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
447 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
450 "Trivial File Transfer Protocol traffic",
451 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
455 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
459 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
462 "RFC 868 Time protocol",
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
466 "Traceroute (for up to 30 hops) traffic",
467 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
468 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
471 "VNC traffic for VNC display's 0 - 9",
472 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5909' },
475 "VNC traffic from Vncservers to Vncviewers in listen mode",
476 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
479 "WWW traffic (HTTP and HTTPS)",
480 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
481 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
484 "Web Cache/Proxy traffic (port 8080)",
485 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
489 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
492 "Whois (nicname, RFC 3912) traffic",
493 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
497 my $pve_fw_parsed_macros;
498 my $pve_fw_macro_descr;
499 my $pve_fw_preferred_macro_names = {};
501 my $pve_std_chains = {
502 'PVEFW-SET-ACCEPT-MARK' => [
503 "-j MARK --set-mark 1",
505 'PVEFW-DropBroadcast' => [
506 # same as shorewall 'Broadcast'
507 # simply DROP BROADCAST/MULTICAST/ANYCAST
508 # we can use this to reduce logging
509 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
510 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
511 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
512 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
515 # same as shorewall 'reject'
516 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
517 { action
=> 'DROP', source
=> '224.0.0.0/4' },
518 { action
=> 'DROP', proto
=> 'icmp' },
519 "-p tcp -j REJECT --reject-with tcp-reset",
520 "-p udp -j REJECT --reject-with icmp-port-unreachable",
521 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
522 "-j REJECT --reject-with icmp-host-prohibited",
525 # same as shorewall 'Drop', which is equal to DROP,
526 # but REJECT/DROP some packages to reduce logging,
527 # and ACCEPT critical ICMP types
528 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
529 # we are not interested in BROADCAST/MULTICAST/ANYCAST
530 { action
=> 'PVEFW-DropBroadcast' },
531 # ACCEPT critical ICMP types
532 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
533 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
534 # Drop packets with INVALID state
535 "-m conntrack --ctstate INVALID -j DROP",
536 # Drop Microsoft SMB noise
537 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
538 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
539 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
540 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
541 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
542 # Drop new/NotSyn traffic so that it doesn't get logged
543 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
545 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
548 # same as shorewall 'Reject', which is equal to Reject,
549 # but REJECT/DROP some packages to reduce logging,
550 # and ACCEPT critical ICMP types
551 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
552 # we are not interested in BROADCAST/MULTICAST/ANYCAST
553 { action
=> 'PVEFW-DropBroadcast' },
554 # ACCEPT critical ICMP types
555 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
556 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
557 # Drop packets with INVALID state
558 "-m conntrack --ctstate INVALID -j DROP",
559 # Drop Microsoft SMB noise
560 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
561 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
562 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
563 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
564 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
565 # Drop new/NotSyn traffic so that it doesn't get logged
566 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
568 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
570 'PVEFW-tcpflags' => [
571 # same as shorewall tcpflags action.
572 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
573 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
574 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
575 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
576 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
577 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
580 # same as shorewall smurfs action
581 # Filter packets for smurfs (packets with a broadcast address as the source).
582 "-s 0.0.0.0/32 -j RETURN",
583 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
584 "-s 224.0.0.0/4 -g PVEFW-smurflog",
588 # iptables -p icmp -h
589 my $icmp_type_names = {
592 'destination-unreachable' => 1,
593 'network-unreachable' => 1,
594 'host-unreachable' => 1,
595 'protocol-unreachable' => 1,
596 'port-unreachable' => 1,
597 'fragmentation-needed' => 1,
598 'source-route-failed' => 1,
599 'network-unknown' => 1,
601 'network-prohibited' => 1,
602 'host-prohibited' => 1,
603 'TOS-network-unreachable' => 1,
604 'TOS-host-unreachable' => 1,
605 'communication-prohibited' => 1,
606 'host-precedence-violation' => 1,
607 'precedence-cutoff' => 1,
608 'source-quench' => 1,
610 'network-redirect' => 1,
611 'host-redirect' => 1,
612 'TOS-network-redirect' => 1,
613 'TOS-host-redirect' => 1,
615 'router-advertisement' => 1,
616 'router-solicitation' => 1,
617 'time-exceeded' => 1,
618 'ttl-zero-during-transit' => 1,
619 'ttl-zero-during-reassembly' => 1,
620 'parameter-problem' => 1,
621 'ip-header-bad' => 1,
622 'required-option-missing' => 1,
623 'timestamp-request' => 1,
624 'timestamp-reply' => 1,
625 'address-mask-request' => 1,
626 'address-mask-reply' => 1,
629 sub init_firewall_macros
{
631 $pve_fw_parsed_macros = {};
633 foreach my $k (keys %$pve_fw_macros) {
634 my $lc_name = lc($k);
635 my $macro = $pve_fw_macros->{$k};
636 if (!ref($macro->[0])) {
637 $pve_fw_macro_descr->{$k} = shift @$macro;
639 $pve_fw_preferred_macro_names->{$lc_name} = $k;
640 $pve_fw_parsed_macros->{$k} = $macro;
644 init_firewall_macros
();
647 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
652 sub get_etc_services
{
654 return $etc_services if $etc_services;
656 my $filename = "/etc/services";
658 my $fh = IO
::File-
>new($filename, O_RDONLY
);
660 warn "unable to read '$filename' - $!\n";
666 while (my $line = <$fh>) {
668 next if $line =~m/^#/;
669 next if ($line =~m/^\s*$/);
671 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
672 $services->{byid
}->{$2}->{name
} = $1;
673 $services->{byid
}->{$2}->{port
} = $2;
674 $services->{byid
}->{$2}->{$3} = 1;
675 $services->{byname
}->{$1} = $services->{byid
}->{$2};
681 $etc_services = $services;
684 return $etc_services;
689 sub get_etc_protocols
{
690 return $etc_protocols if $etc_protocols;
692 my $filename = "/etc/protocols";
694 my $fh = IO
::File-
>new($filename, O_RDONLY
);
696 warn "unable to read '$filename' - $!\n";
702 while (my $line = <$fh>) {
704 next if $line =~m/^#/;
705 next if ($line =~m/^\s*$/);
707 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
708 $protocols->{byid
}->{$2}->{name
} = $1;
709 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
715 $etc_protocols = $protocols;
717 return $etc_protocols;
720 sub parse_address_list
{
723 return if $str =~ m/^(\+)(\S+)$/; # ipset ref
724 return if $str =~ m/^${ip_alias_pattern}$/;
728 foreach my $elem (split(/,/, $str)) {
730 if (!Net
::IP-
>new($elem)) {
731 my $err = Net
::IP
::Error
();
732 die "invalid IP address: $err\n";
734 $iprange = 1 if $elem =~ m/-/;
737 die "you can use a range in a list\n" if $iprange && $count > 1;
740 sub parse_port_name_number_or_range
{
743 my $services = PVE
::Firewall
::get_etc_services
();
747 foreach my $item (split(/,/, $str)) {
749 if ($item =~ m/^(\d+):(\d+)$/) {
750 my ($port1, $port2) = ($1, $2);
751 die "invalid port '$port1'\n" if $port1 > 65535;
752 die "invalid port '$port2'\n" if $port2 > 65535;
753 } elsif ($item =~ m/^(\d+)$/) {
755 die "invalid port '$port'\n" if $port > 65535;
757 if ($icmp_type_names->{$item}) {
760 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
765 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
770 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
771 sub pve_fw_verify_port_spec
{
774 parse_port_name_number_or_range
($portstr);
779 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
780 sub pve_fw_verify_v4addr_spec
{
783 parse_address_list
($list);
788 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
789 sub pve_fw_verify_protocol_spec
{
792 my $protocols = get_etc_protocols
();
794 die "unknown protocol '$proto'\n" if $proto &&
795 !(defined($protocols->{byname
}->{$proto}) ||
796 defined($protocols->{byid
}->{$proto}));
802 # helper function for API
804 sub copy_opject_with_digest
{
807 my $sha = Digest
::SHA-
>new('sha1');
810 foreach my $k (sort keys %$object) {
811 my $v = $object->{$k};
812 next if !defined($v);
814 $sha->add($k, ':', $v, "\n");
817 my $digest = $sha->b64digest;
819 $res->{digest
} = $digest;
821 return wantarray ?
($res, $digest) : $res;
824 sub copy_list_with_digest
{
827 my $sha = Digest
::SHA-
>new('sha1');
830 foreach my $entry (@$list) {
832 foreach my $k (sort keys %$entry) {
833 my $v = $entry->{$k};
834 next if !defined($v);
836 $sha->add($k, ':', $v, "\n");
841 my $digest = $sha->b64digest;
843 foreach my $entry (@$res) {
844 $entry->{digest
} = $digest;
847 return wantarray ?
($res, $digest) : $res;
850 my $rule_properties = {
852 description
=> "Update rule at position <pos>.",
857 digest
=> get_standard_option
('pve-config-digest'),
861 enum
=> ['in', 'out', 'group'],
864 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
867 pattern
=> $security_group_name_pattern,
876 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
878 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
882 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
886 type
=> 'string', format
=> 'pve-fw-protocol-spec',
894 type
=> 'string', format
=> 'pve-fw-port-spec',
898 type
=> 'string', format
=> 'pve-fw-port-spec',
907 sub add_rule_properties
{
908 my ($properties) = @_;
910 foreach my $k (keys %$rule_properties) {
911 my $h = $rule_properties->{$k};
912 # copy data, so that we can modify later without side effects
913 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
919 sub delete_rule_properties
{
920 my ($rule, $delete_str) = @_;
922 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
923 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
924 if !defined($rule_properties->{$opt});
925 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
926 if $opt eq 'type' || $opt eq 'action';
927 delete $rule->{$opt};
933 my $apply_macro = sub {
934 my ($macro_name, $param, $verify) = @_;
936 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
937 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
941 foreach my $templ (@$macro_rules) {
944 foreach my $k (keys %$templ) {
945 my $v = $templ->{$k};
948 $param_used->{$k} = 1;
949 } elsif ($v eq 'DEST') {
951 $param_used->{dest
} = 1;
952 } elsif ($v eq 'SOURCE') {
953 $v = $param->{source
};
954 $param_used->{source
} = 1;
958 my $msg = "missing parameter '$k' in macro '$macro_name'";
959 raise_param_exc
({ macro => $msg }) if $verify;
964 foreach my $k (keys %$param) {
965 next if $k eq 'macro';
966 next if !defined($param->{$k});
967 next if $param_used->{$k};
968 if (defined($rule->{$k})) {
969 if ($rule->{$k} ne $param->{$k}) {
970 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
971 raise_param_exc
({ $k => $msg }) if $verify;
975 $rule->{$k} = $param->{$k};
985 my ($rule, $allow_groups) = @_;
987 my $type = $rule->{type
};
989 raise_param_exc
({ type
=> "missing property"}) if !$type;
990 raise_param_exc
({ action
=> "missing property"}) if !$rule->{action
};
992 if ($type eq 'in' || $type eq 'out') {
993 raise_param_exc
({ action
=> "unknown action '$rule->{action}'"})
994 if $rule->{action
} !~ m/^(ACCEPT|DROP|REJECT)$/;
995 } elsif ($type eq 'group') {
996 raise_param_exc
({ type
=> "security groups not allowed"})
998 raise_param_exc
({ action
=> "invalid characters in security group name"})
999 if $rule->{action
} !~ m/^${security_group_name_pattern}$/;
1001 raise_param_exc
({ type
=> "unknown rule type '$type'"});
1004 # fixme: verify $rule->{iface}?
1006 if ($rule->{macro}) {
1007 my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
1008 raise_param_exc
({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
1009 $rule->{macro} = $preferred_name;
1012 if ($rule->{dport
}) {
1013 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1014 raise_param_exc
({ dport
=> $@ }) if $@;
1017 if ($rule->{sport
}) {
1018 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1019 raise_param_exc
({ sport
=> $@ }) if $@;
1022 if ($rule->{source
}) {
1023 eval { parse_address_list
($rule->{source
}); };
1024 raise_param_exc
({ source
=> $@ }) if $@;
1027 if ($rule->{dest
}) {
1028 eval { parse_address_list
($rule->{dest
}); };
1029 raise_param_exc
({ dest
=> $@ }) if $@;
1032 if ($rule->{macro}) {
1033 &$apply_macro($rule->{macro}, $rule, 1);
1039 sub copy_rule_data
{
1040 my ($rule, $param) = @_;
1042 foreach my $k (keys %$rule_properties) {
1043 if (defined(my $v = $param->{$k})) {
1044 if ($v eq '' || $v eq '-') {
1060 my $bridge_firewall_enabled = 0;
1062 sub enable_bridge_firewall
{
1064 return if $bridge_firewall_enabled; # only once
1066 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1067 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1069 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1070 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1072 $bridge_firewall_enabled = 1;
1075 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1077 sub iptables_restore_cmdlist
{
1080 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1083 sub ipset_restore_cmdlist
{
1086 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1089 sub iptables_get_chains
{
1093 # check what chains we want to track
1094 my $is_pvefw_chain = sub {
1097 return 1 if $name =~ m/^PVEFW-\S+$/;
1099 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1101 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1103 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1105 return 1 if $name =~ m/^vmbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1106 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1118 return if $line =~ m/^#/;
1119 return if $line =~ m/^\s*$/;
1121 if ($line =~ m/^\*(\S+)$/) {
1126 return if $table ne 'filter';
1128 if ($line =~ m/^:(\S+)\s/) {
1130 return if !&$is_pvefw_chain($chain);
1131 $res->{$chain} = "unknown";
1132 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1133 my ($chain, $sig) = ($1, $2);
1134 return if !&$is_pvefw_chain($chain);
1135 $res->{$chain} = $sig;
1136 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1139 # simply ignore the rest
1144 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1146 return wantarray ?
($res, $hooks) : $res;
1149 sub iptables_chain_digest
{
1151 my $digest = Digest
::SHA-
>new('sha1');
1152 foreach my $rule (@$rules) { # order is important
1153 $digest->add($rule);
1155 return $digest->b64digest;
1158 sub ipset_chain_digest
{
1161 my $digest = Digest
::SHA-
>new('sha1');
1162 foreach my $rule (sort @$rules) { # note: sorted
1163 $digest->add($rule);
1165 return $digest->b64digest;
1168 sub ipset_get_chains
{
1176 return if $line =~ m/^#/;
1177 return if $line =~ m/^\s*$/;
1178 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1180 $line =~ s/\s+$//; # delete trailing white space
1181 push @{$chains->{$chain}}, $line;
1183 # simply ignore the rest
1188 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1190 # compute digest for each chain
1191 foreach my $chain (keys %$chains) {
1192 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1198 sub ruleset_generate_cmdstr
{
1199 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1201 return if defined($rule->{enable
}) && !$rule->{enable
};
1203 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1205 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1206 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1210 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1211 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1213 my $source = $rule->{source
};
1214 my $dest = $rule->{dest
};
1217 if ($source =~ m/^\+/) {
1218 if ($source =~ m/^\+(${security_group_name_pattern})$/) {
1219 die "no such ipset '$1'\n" if !$cluster_conf->{ipset
}->{$1};
1220 push @cmd, "-m set --match-set PVEFW-$1 src";
1222 die "invalid security group name '$source'\n";
1224 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1225 my $alias = lc($source);
1226 my $e = $cluster_conf->{aliases
}->{$alias};
1227 die "no such alias $source\n" if !$e;
1228 push @cmd, "-s $e->{cidr}";
1229 } elsif ($source =~ m/\-/){
1230 push @cmd, "-m iprange --src-range $source";
1233 push @cmd, "-s $source";
1238 if ($dest =~ m/^\+/) {
1239 if ($dest =~ m/^\+(${security_group_name_pattern})$/) {
1240 die "no such ipset '$1'\n" if !$cluster_conf->{ipset
}->{$1};
1241 push @cmd, "-m set --match-set PVEFW-$1 dst";
1243 die "invalid security group name '$dest'\n";
1245 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1246 my $alias = lc($source);
1247 my $e = $cluster_conf->{aliases
}->{$alias};
1248 die "no such alias $dest" if !$e;
1249 push @cmd, "-d $e->{cidr}";
1250 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1251 push @cmd, "-m iprange --dst-range $dest";
1254 push @cmd, "-d $dest";
1258 if ($rule->{proto
}) {
1259 push @cmd, "-p $rule->{proto}";
1262 $multiport++ if $nbdport > 1;
1263 $multiport++ if $nbsport > 1;
1265 push @cmd, "--match multiport" if $multiport;
1267 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1268 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1270 if ($rule->{dport
}) {
1271 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1272 # Note: we use dport to store --icmp-type
1273 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1274 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1277 if ($multiport == 2) {
1278 push @cmd, "--ports $rule->{dport}";
1280 push @cmd, "--dports $rule->{dport}";
1283 push @cmd, "--dport $rule->{dport}";
1288 if ($rule->{sport
}) {
1290 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1292 push @cmd, "--sport $rule->{sport}";
1295 } elsif ($rule->{dport
} || $rule->{sport
}) {
1296 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport
};
1297 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport
};
1300 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1302 if (my $action = $rule->{action
}) {
1303 $action = $actions->{$action} if defined($actions->{$action});
1304 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1305 push @cmd, $goto ?
"-g $action" : "-j $action";
1308 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1311 sub ruleset_generate_rule
{
1312 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1316 if ($rule->{macro}) {
1317 $rules = &$apply_macro($rule->{macro}, $rule);
1322 # update all or nothing
1325 foreach my $tmp (@$rules) {
1326 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1327 push @cmds, $cmdstr;
1331 foreach my $cmdstr (@cmds) {
1332 ruleset_addrule
($ruleset, $chain, $cmdstr);
1336 sub ruleset_generate_rule_insert
{
1337 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1339 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1341 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1342 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1346 sub ruleset_create_chain
{
1347 my ($ruleset, $chain) = @_;
1349 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1350 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1352 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1354 $ruleset->{$chain} = [];
1357 sub ruleset_chain_exist
{
1358 my ($ruleset, $chain) = @_;
1360 return $ruleset->{$chain} ?
1 : undef;
1363 sub ruleset_addrule
{
1364 my ($ruleset, $chain, $rule) = @_;
1366 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1368 push @{$ruleset->{$chain}}, "-A $chain $rule";
1371 sub ruleset_insertrule
{
1372 my ($ruleset, $chain, $rule) = @_;
1374 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1376 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1379 sub get_log_rule_base
{
1380 my ($chain, $vmid, $msg, $loglevel) = @_;
1382 die "internal error - no log level" if !defined($loglevel);
1384 $vmid = 0 if !defined($vmid);
1386 # Note: we use special format for prefix to pass further
1387 # info to log daemon (VMID, LOGVELEL and CHAIN)
1389 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1392 sub ruleset_addlog {
1393 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1395 return if !defined($loglevel);
1397 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1399 $logrule = "$rule $logrule" if defined($rule);
1401 ruleset_addrule($ruleset, $chain, $logrule)
1404 sub generate_bridge_chains {
1405 my ($ruleset, $hostfw_conf, $bridge, $routing_table, $bridges_config) = @_;
1407 my $options = $hostfw_conf->{options} || {};
1409 die "error
: detected direct route to bridge
'$bridge'\n"
1410 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
1412 if (!ruleset_chain_exist($ruleset, "$bridge-FW
")) {
1413 ruleset_create_chain($ruleset, "$bridge-FW
");
1414 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-FW
");
1415 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-FW
");
1418 if (!ruleset_chain_exist($ruleset, "$bridge-OUT
")) {
1419 ruleset_create_chain($ruleset, "$bridge-OUT
");
1421 if($options->{optimize}){
1422 foreach my $interface (@{$bridges_config->{$bridge}}) {
1423 ruleset_addrule($ruleset, "$bridge-OUT
", "-m physdev
--physdev-is-bridged
--physdev-in
$interface -g PVEFW-SET-ACCEPT-MARK
");
1427 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-in
-j
$bridge-OUT
");
1428 ruleset_insertrule($ruleset, "PVEFW-INPUT
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-OUT
");
1431 if (!ruleset_chain_exist($ruleset, "$bridge-IN
")) {
1432 ruleset_create_chain($ruleset, "$bridge-IN
");
1434 if($options->{optimize}){
1435 foreach my $interface (@{$bridges_config->{$bridge}}) {
1436 ruleset_addrule($ruleset, "$bridge-IN
", "-m physdev
--physdev-is-bridged
--physdev-out
$interface -j ACCEPT
");
1440 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j
$bridge-IN
");
1441 ruleset_addrule($ruleset, "$bridge-FW
", "-m mark
--mark
1 -j ACCEPT
");
1442 # accept traffic to unmanaged bridge ports
1443 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j ACCEPT
");
1447 sub ruleset_add_chain_policy {
1448 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1450 if ($policy eq 'ACCEPT') {
1452 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1453 { ACCEPT => $accept_action});
1455 } elsif ($policy eq 'DROP') {
1457 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1459 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1461 ruleset_addrule($ruleset, $chain, "-j DROP
");
1462 } elsif ($policy eq 'REJECT') {
1463 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1465 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1467 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1470 die "internal error
: unknown policy
'$policy'";
1474 sub ruleset_create_vm_chain {
1475 my ($ruleset, $chain, $options, $host_options, $macaddr, $direction) = @_;
1477 ruleset_create_chain($ruleset, $chain);
1478 my $accept = generate_nfqueue($options);
1480 if (!(defined($host_options->{nosmurfs}) && $host_options->{nosmurfs} == 0)) {
1481 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1484 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1485 if ($direction eq 'OUT') {
1486 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1487 proto => 'udp', sport => 68, dport => 67 });
1489 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1490 proto => 'udp', sport => 67, dport => 68 });
1494 if ($host_options->{tcpflags}) {
1495 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1498 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1499 if ($direction eq 'OUT') {
1500 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-g PVEFW-SET-ACCEPT-MARK
");
1502 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1505 if ($direction eq 'OUT') {
1506 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1507 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1509 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1513 sub ruleset_generate_vm_rules {
1514 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1516 my $lc_direction = lc($direction);
1518 my $in_accept = generate_nfqueue($options);
1520 foreach my $rule (@$rules) {
1521 next if $rule->{iface} && $rule->{iface} ne $netid;
1522 next if !$rule->{enable};
1523 if ($rule->{type} eq 'group') {
1524 my $group_chain = "GROUP-
$rule->{action
}-$direction";
1525 if(!ruleset_chain_exist($ruleset, $group_chain)){
1526 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
1528 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1529 if ($direction eq 'OUT'){
1530 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j RETURN
");
1532 my $accept = generate_nfqueue($options);
1533 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$accept");
1537 next if $rule->{type} ne $lc_direction;
1539 if ($direction eq 'OUT') {
1540 ruleset_generate_rule($ruleset, $chain, $rule,
1541 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1542 undef, $cluster_conf);
1544 ruleset_generate_rule($ruleset, $chain, $rule,
1545 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1546 undef, $cluster_conf);
1554 sub generate_nfqueue {
1557 if ($options->{ips}) {
1558 my $action = "NFQUEUE
";
1559 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1560 if (defined($3) && defined($1)) {
1561 $action .= " --queue-balance
$1:$3";
1562 } elsif (defined($1)) {
1563 $action .= " --queue-num
$1";
1566 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1573 sub ruleset_generate_vm_ipsrules {
1574 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1576 if ($options->{ips} && $direction eq 'IN') {
1577 my $nfqueue = generate_nfqueue($options);
1579 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1580 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1583 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1584 ruleset_create_chain($ruleset, "$bridge-IPS
");
1585 ruleset_insertrule($ruleset, "PVEFW-IPS
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-IPS
");
1588 ruleset_addrule($ruleset, "$bridge-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1592 sub generate_venet_rules_direction {
1593 my ($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1595 parse_address_list($ip); # make sure we have a valid $ip list
1597 my $lc_direction = lc($direction);
1599 my $rules = $vmfw_conf->{rules};
1601 my $options = $vmfw_conf->{options};
1602 my $hostfw_options = $vmfw_conf->{options};
1603 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1605 my $chain = "venet0-
$vmid-$direction";
1607 ruleset_create_vm_chain($ruleset, $chain, $options, $hostfw_options, undef, $direction);
1609 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1614 if ($direction eq 'OUT') {
1615 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1617 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1620 my $accept = generate_nfqueue($options);
1621 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1622 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1624 # plug into FORWARD, INPUT and OUTPUT chain
1625 if ($direction eq 'OUT') {
1626 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD
", {
1629 iface_in => 'venet0'});
1631 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT
", {
1634 iface_in => 'venet0'});
1636 ruleset_generate_rule($ruleset, "PVEFW-FORWARD
", {
1639 iface_out => 'venet0'});
1641 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT
", {
1644 iface_out => 'venet0'});
1648 sub generate_tap_rules_direction {
1649 my ($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1651 my $lc_direction = lc($direction);
1653 my $rules = $vmfw_conf->{rules};
1655 my $options = $vmfw_conf->{options};
1656 my $hostfw_options = $hostfw_conf->{options};
1657 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1659 my $tapchain = "$iface-$direction";
1661 ruleset_create_vm_chain($ruleset, $tapchain, $options, $hostfw_options, $macaddr, $direction);
1663 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1665 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1670 if ($direction eq 'OUT') {
1671 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1673 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1676 my $accept = generate_nfqueue($options);
1677 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1678 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1680 # plug the tap chain to bridge chain
1681 if ($direction eq 'IN') {
1682 ruleset_addrule($ruleset, "$bridge-IN
",
1683 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1685 ruleset_addrule($ruleset, "$bridge-OUT
",
1686 "-m physdev
--physdev-in
$iface -j
$tapchain");
1690 sub enable_host_firewall {
1691 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1693 my $options = $hostfw_conf->{options};
1694 my $cluster_options = $cluster_conf->{options};
1695 my $rules = $hostfw_conf->{rules};
1696 my $cluster_rules = $cluster_conf->{rules};
1698 # host inbound firewall
1699 my $chain = "PVEFW-HOST-IN
";
1700 ruleset_create_chain($ruleset, $chain);
1702 my $loglevel = get_option_log_level($options, "log_level_in
");
1704 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1705 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1708 if ($options->{tcpflags}) {
1709 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1712 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1713 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1714 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1715 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1716 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1717 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1719 # we use RETURN because we need to check also tap rules
1720 my $accept_action = 'RETURN';
1722 # add host rules first, so that cluster wide rules can be overwritten
1723 foreach my $rule (@$rules, @$cluster_rules) {
1724 next if $rule->{type} ne 'in';
1725 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1728 # implement input policy
1729 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1730 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1732 # host outbound firewall
1733 $chain = "PVEFW-HOST-OUT
";
1734 ruleset_create_chain($ruleset, $chain);
1736 $loglevel = get_option_log_level($options, "log_level_out
");
1738 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1739 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1740 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1741 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1742 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1743 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1745 # we use RETURN because we may want to check other thigs later
1746 $accept_action = 'RETURN';
1748 # add host rules first, so that cluster wide rules can be overwritten
1749 foreach my $rule (@$rules, @$cluster_rules) {
1750 next if $rule->{type} ne 'out';
1751 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1754 # implement output policy
1755 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1756 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1758 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1759 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1762 sub generate_group_rules {
1763 my ($ruleset, $cluster_conf, $group) = @_;
1764 die "no such security group
'$group'\n" if !$cluster_conf->{groups}->{$group};
1766 my $rules = $cluster_conf->{groups}->{$group};
1768 my $chain = "GROUP-
${group
}-IN
";
1770 ruleset_create_chain($ruleset, $chain);
1771 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1773 foreach my $rule (@$rules) {
1774 next if $rule->{type} ne 'in';
1775 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1778 $chain = "GROUP-
${group
}-OUT
";
1780 ruleset_create_chain($ruleset, $chain);
1781 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1783 foreach my $rule (@$rules) {
1784 next if $rule->{type} ne 'out';
1785 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1786 # check also other tap rules later
1787 ruleset_generate_rule($ruleset, $chain, $rule,
1788 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1793 my $valid_netdev_names = {};
1794 for (my $i = 0; $i < $MAX_NETS; $i++) {
1795 $valid_netdev_names->{"net
$i"} = 1;
1799 my ($line, $need_iface, $allow_groups) = @_;
1801 my ($type, $action, $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 my @data = split(/\s+/, $line);
1812 my $expected_elements = $need_iface ? 8 : 7;
1814 die "wrong number of rule elements
\n" if scalar(@data) > $expected_elements;
1817 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1819 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1822 die "incomplete rule
\n" if ! ($type && $action);
1828 if ($type eq 'in' || $type eq 'out') {
1829 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1831 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1833 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1834 die "unknown
macro '$1'\n" if !$preferred_name;
1835 $macro = $preferred_name;
1837 die "unknown action
'$action'\n";
1839 } elsif ($type eq 'group') {
1840 die "wrong number of rule elements
\n" if scalar(@data) != 3;
1841 die "groups disabled
\n" if !$allow_groups;
1843 die "invalid characters
in group name
\n" if $action !~ m/^${security_group_name_pattern}$/;
1845 die "unknown rule type
'$type'\n";
1849 $iface = undef if $iface && $iface eq '-';
1852 $proto = undef if $proto && $proto eq '-';
1853 pve_fw_verify_protocol_spec($proto) if $proto;
1855 $source = undef if $source && $source eq '-';
1856 $dest = undef if $dest && $dest eq '-';
1858 $dport = undef if $dport && $dport eq '-';
1859 $sport = undef if $sport && $sport eq '-';
1861 parse_port_name_number_or_range($dport) if defined($dport);
1862 parse_port_name_number_or_range($sport) if defined($sport);
1864 parse_address_list($source) if $source;
1865 parse_address_list($dest) if $dest;
1870 comment => $comment,
1882 sub parse_vmfw_option {
1887 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
1889 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
1892 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1894 $value = $2 ? lc($3) : '';
1895 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1898 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1903 die "can
't parse option '$line'\n"
1906 return ($opt, $value);
1909 sub parse_hostfw_option {
1914 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1916 if ($line =~ m/^(enable|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1919 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1921 $value = $2 ? lc($3) : '';
1922 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
1927 die "can't parse option
'$line'\n"
1930 return ($opt, $value);
1933 sub parse_clusterfw_option {
1938 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1941 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1946 die "can
't parse option '$line'\n"
1949 return ($opt, $value);
1952 sub parse_clusterfw_alias {
1955 # we can add single line comments to the end of the line
1956 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
1958 if ($line =~ m/^(\S+)\s(\S+)$/) {
1959 my ($name, $cidr) = ($1, $2);
1961 pve_verify_ipv4_or_cidr($cidr);
1966 $data->{comment} = $comment if $comment;
1973 sub parse_vm_fw_rules {
1974 my ($filename, $fh) = @_;
1976 my $res = { rules => [], options => {}};
1980 while (defined(my $line = <$fh>)) {
1981 next if $line =~ m/^#/;
1982 next if $line =~ m/^\s*$/;
1984 my $linenr = $fh->input_line_number();
1985 my $prefix = "$filename (line $linenr)";
1987 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1989 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1993 warn "$prefix: skip line - no section";
1997 next if !$res->{$section}; # skip undefined section
1999 if ($section eq 'options
') {
2001 my ($opt, $value) = parse_vmfw_option($line);
2002 $res->{options}->{$opt} = $value;
2004 warn "$prefix: $@" if $@;
2009 eval { $rule = parse_fw_rule($line, 1, 1); };
2011 warn "$prefix: $err";
2015 push @{$res->{$section}}, $rule;
2021 sub parse_host_fw_rules {
2022 my ($filename, $fh) = @_;
2024 my $res = { rules => [], options => {}};
2028 while (defined(my $line = <$fh>)) {
2029 next if $line =~ m/^#/;
2030 next if $line =~ m/^\s*$/;
2032 my $linenr = $fh->input_line_number();
2033 my $prefix = "$filename (line $linenr)";
2035 if ($line =~ m/^\[(\S+)\]\s*$/i) {
2037 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
2041 warn "$prefix: skip line - no section";
2045 next if !$res->{$section}; # skip undefined section
2047 if ($section eq 'options
') {
2049 my ($opt, $value) = parse_hostfw_option($line);
2050 $res->{options}->{$opt} = $value;
2052 warn "$prefix: $@" if $@;
2057 eval { $rule = parse_fw_rule($line, 1, 1); };
2059 warn "$prefix: $err";
2063 push @{$res->{$section}}, $rule;
2069 sub parse_cluster_fw_rules {
2070 my ($filename, $fh) = @_;
2080 group_comments => {},
2082 ipset_comments => {},
2085 while (defined(my $line = <$fh>)) {
2086 next if $line =~ m/^#/;
2087 next if $line =~ m/^\s*$/;
2089 my $linenr = $fh->input_line_number();
2090 my $prefix = "$filename (line $linenr)";
2092 if ($line =~ m/^\[options\]$/i) {
2093 $section = 'options
';
2097 if ($line =~ m/^\[aliases\]$/i) {
2098 $section = 'aliases
';
2102 if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2103 $section = 'groups
';
2106 $res->{$section}->{$group} = [];
2107 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2112 if ($line =~ m/^\[rules\]$/i) {
2117 if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2121 $res->{$section}->{$group} = [];
2122 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2128 warn "$prefix: skip line - no section\n";
2132 if ($section eq 'options
') {
2134 my ($opt, $value) = parse_clusterfw_option($line);
2135 $res->{options}->{$opt} = $value;
2137 warn "$prefix: $@" if $@;
2138 } elsif ($section eq 'aliases
') {
2140 my $data = parse_clusterfw_alias($line);
2141 $res->{aliases}->{lc($data->{name})} = $data;
2143 warn "$prefix: $@" if $@;
2144 } elsif ($section eq 'rules
') {
2146 eval { $rule = parse_fw_rule($line, 1, 1); };
2148 warn "$prefix: $err";
2151 push @{$res->{$section}}, $rule;
2152 } elsif ($section eq 'groups
') {
2154 eval { $rule = parse_fw_rule($line, 0, 0); };
2156 warn "$prefix: $err";
2159 push @{$res->{$section}->{$group}}, $rule;
2160 } elsif ($section eq 'ipset
') {
2161 # we can add single line comments to the end of the rule
2162 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2164 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2168 if($cidr !~ m/^${ip_alias_pattern}$/) {
2171 eval { pve_verify_ipv4_or_cidr($cidr); };
2173 warn "$prefix: $cidr - $err";
2178 my $entry = { cidr => $cidr };
2179 $entry->{nomatch} = 1 if $nomatch;
2180 $entry->{comment} = $comment if $comment;
2182 push @{$res->{$section}->{$group}}, $entry;
2190 my ($code, @param) = @_;
2194 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2201 sub read_local_vm_config {
2206 my $vmdata = { openvz => $openvz, qemu => $qemu };
2208 my $vmlist = PVE::Cluster::get_vmlist();
2209 return $vmdata if !$vmlist || !$vmlist->{ids};
2210 my $ids = $vmlist->{ids};
2212 foreach my $vmid (keys %$ids) {
2213 next if !$vmid; # skip VE0
2214 my $d = $ids->{$vmid};
2215 next if !$d->{node} || $d->{node} ne $nodename;
2216 next if !$d->{type};
2217 if ($d->{type} eq 'openvz
') {
2218 if ($have_pve_manager) {
2219 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2220 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2221 $openvz->{$vmid} = $conf;
2224 } elsif ($d->{type} eq 'qemu
') {
2225 if ($have_qemu_server) {
2226 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2227 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2228 $qemu->{$vmid} = $conf;
2237 sub read_bridges_config {
2239 my $bridgehash = {};
2241 dir_glob_foreach('/sys/class/net
', 'vmbr
(\d
+)', sub {
2244 dir_glob_foreach("/sys/class/net/$bridge/brif", '((eth
|bond
)(\d
+)(\
.(\d
+))?
)', sub {
2245 my ($interface) = @_;
2246 push @{$bridgehash->{$bridge}}, $interface;
2253 sub load_vmfw_conf {
2258 my $filename = "/etc/pve/firewall/$vmid.fw";
2259 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2260 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2266 my $format_rules = sub {
2267 my ($rules, $need_iface) = @_;
2271 foreach my $rule (@$rules) {
2272 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2273 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2274 $raw .= uc($rule->{type});
2275 if ($rule->{macro}) {
2276 $raw .= " $rule->{macro}($rule->{action})";
2278 $raw .= " " . $rule->{action};
2280 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
2282 if ($rule->{type} ne 'group
') {
2283 $raw .= " " . ($rule->{source} || '-');
2284 $raw .= " " . ($rule->{dest} || '-');
2285 $raw .= " " . ($rule->{proto} || '-');
2286 $raw .= " " . ($rule->{dport} || '-');
2287 $raw .= " " . ($rule->{sport} || '-');
2290 $raw .= " # " . encode('utf8
', $rule->{comment})
2291 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2294 die "unknown rule type '$rule->{type
}'";
2301 my $format_options = sub {
2306 $raw .= "[OPTIONS]\n\n";
2307 foreach my $opt (keys %$options) {
2308 $raw .= "$opt: $options->{$opt}\n";
2315 my $format_aliases = sub {
2320 $raw .= "[ALIASES]\n\n";
2321 foreach my $k (keys %$aliases) {
2322 my $e = $aliases->{$k};
2323 $raw .= "$e->{name} $e->{cidr}";
2324 $raw .= " # " . encode('utf8
', $e->{comment})
2325 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2333 my $format_ipset = sub {
2339 foreach my $entry (@$options) {
2340 $nethash->{$entry->{cidr}} = $entry;
2343 foreach my $cidr (sort keys %$nethash) {
2344 my $entry = $nethash->{$cidr};
2345 my $line = $entry->{nomatch} ? '!' : '';
2346 $line .= $entry->{cidr};
2347 $line .= " # " . encode('utf8
', $entry->{comment})
2348 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2355 sub save_vmfw_conf {
2356 my ($vmid, $vmfw_conf) = @_;
2360 my $options = $vmfw_conf->{options};
2361 $raw .= &$format_options($options) if scalar(keys %$options);
2363 my $rules = $vmfw_conf->{rules};
2364 if (scalar(@$rules)) {
2365 $raw .= "[RULES]\n\n";
2366 $raw .= &$format_rules($rules, 1);
2370 my $filename = "/etc/pve/firewall/$vmid.fw";
2371 PVE::Tools::file_set_contents($filename, $raw);
2374 sub read_vm_firewall_configs {
2376 my $vmfw_configs = {};
2378 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2379 my $vmfw_conf = load_vmfw_conf($vmid);
2380 next if !$vmfw_conf->{options}; # skip if file does not exists
2381 $vmfw_configs->{$vmid} = $vmfw_conf;
2384 return $vmfw_configs;
2387 sub get_option_log_level {
2388 my ($options, $k) = @_;
2390 my $v = $options->{$k};
2391 $v = $default_log_level if !defined($v);
2393 return undef if $v eq '' || $v eq 'nolog
';
2395 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2397 return $v if ($v >= 0) && ($v <= 7);
2399 warn "unknown log level ($k = '$v')\n";
2404 sub generate_std_chains {
2405 my ($ruleset, $options) = @_;
2407 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2409 # same as shorewall smurflog.
2410 my $chain = 'PVEFW-smurflog
';
2411 $pve_std_chains->{$chain} = [];
2413 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2414 push @{$pve_std_chains->{$chain}}, "-j DROP";
2416 # same as shorewall logflags action.
2417 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2418 $chain = 'PVEFW-logflags
';
2419 $pve_std_chains->{$chain} = [];
2421 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2422 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2423 push @{$pve_std_chains->{$chain}}, "-j DROP";
2425 foreach my $chain (keys %$pve_std_chains) {
2426 ruleset_create_chain($ruleset, $chain);
2427 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2429 ruleset_generate_rule($ruleset, $chain, $rule);
2431 ruleset_addrule($ruleset, $chain, $rule);
2437 sub generate_ipset_chains {
2438 my ($ipset_ruleset, $fw_conf) = @_;
2440 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2441 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset}, $fw_conf->{aliases});
2445 sub generate_ipset {
2446 my ($ipset_ruleset, $name, $options, $aliases) = @_;
2448 my $hashsize = scalar(@$options);
2449 if ($hashsize <= 64) {
2452 $hashsize = round_powerof2($hashsize);
2455 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2459 foreach my $entry (@$options) {
2460 my $cidr = $entry->{cidr};
2461 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2462 my $alias = lc($cidr);
2463 if ($aliases->{$alias}) {
2464 $entry->{cidr} = $aliases->{$alias}->{cidr};
2465 $nethash->{$entry->{cidr}} = $entry;
2467 warn "no such alias '$cidr'\n" if !$aliases->{$alias};
2470 $nethash->{$entry->{cidr}} = $entry;
2474 foreach my $cidr (sort keys %$nethash) {
2475 my $entry = $nethash->{$cidr};
2477 my $cmd = "add $name $cidr";
2478 if ($entry->{nomatch}) {
2479 if ($feature_ipset_nomatch) {
2480 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2482 warn "ignore !$cidr - nomatch not supported by kernel\n";
2485 push @{$ipset_ruleset->{$name}}, $cmd;
2490 sub round_powerof2 {
2494 $int |= $int >> $_ foreach (1,2,4,8,16);
2498 sub save_pvefw_status {
2501 die "unknown status '$status' - internal error"
2502 if $status !~ m/^(stopped|active)$/;
2504 mkdir dirname($pve_fw_status_filename);
2505 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2508 sub read_pvefw_status {
2510 my $status = 'unknown
';
2512 return 'stopped
' if ! -f $pve_fw_status_filename;
2515 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2522 # fixme: move to pve-common PVE::ProcFSTools
2523 sub read_proc_net_route {
2524 my $filename = "/proc/net/route";
2528 my $fh = IO::File->new ($filename, "r");
2529 return $res if !$fh;
2531 my $int_to_quad = sub {
2532 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2535 while (defined(my $line = <$fh>)) {
2536 next if $line =~/^Iface\s+Destination/; # skip head
2537 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2538 push @{$res->{$iface}}, {
2539 dest => &$int_to_quad(hex($dest)),
2540 gateway => &$int_to_quad(hex($gateway)),
2541 mask => &$int_to_quad(hex($mask)),
2550 sub load_clusterfw_conf {
2552 my $cluster_conf = {};
2553 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
2554 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
2557 return $cluster_conf;
2560 sub save_clusterfw_conf {
2561 my ($cluster_conf) = @_;
2565 my $options = $cluster_conf->{options};
2566 $raw .= &$format_options($options) if scalar(keys %$options);
2568 my $aliases = $cluster_conf->{aliases};
2569 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2571 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
2572 if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
2573 my $utf8comment = encode('utf8
', $comment);
2574 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2576 $raw .= "[IPSET $ipset]\n\n";
2578 my $options = $cluster_conf->{ipset}->{$ipset};
2579 $raw .= &$format_ipset($options);
2583 my $rules = $cluster_conf->{rules};
2584 if (scalar(@$rules)) {
2585 $raw .= "[RULES]\n\n";
2586 $raw .= &$format_rules($rules, 1);
2590 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2591 my $rules = $cluster_conf->{groups}->{$group};
2592 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2593 my $utf8comment = encode('utf8
', $comment);
2594 $raw .= "[group $group] # $utf8comment\n\n";
2596 $raw .= "[group $group]\n\n";
2599 $raw .= &$format_rules($rules, 0);
2603 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2606 sub load_hostfw_conf {
2608 my $hostfw_conf = {};
2609 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2610 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
2612 return $hostfw_conf;
2615 sub save_hostfw_conf {
2616 my ($hostfw_conf) = @_;
2620 my $options = $hostfw_conf->{options};
2621 $raw .= &$format_options($options) if scalar(keys %$options);
2623 my $rules = $hostfw_conf->{rules};
2624 if (scalar(@$rules)) {
2625 $raw .= "[RULES]\n\n";
2626 $raw .= &$format_rules($rules, 1);
2630 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2634 my ($cluster_conf, $hostfw_conf) = @_;
2636 $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
2637 $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
2639 my $vmdata = read_local_vm_config();
2640 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2642 my $routing_table = read_proc_net_route();
2644 my $bridges_config = read_bridges_config();
2646 my $ipset_ruleset = {};
2647 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2651 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2652 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2654 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2656 my $hostfw_options = $hostfw_conf->{options} || {};
2658 generate_std_chains($ruleset, $hostfw_options);
2660 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2662 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2664 # generate firewall rules for QEMU VMs
2665 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2666 my $conf = $vmdata->{qemu}->{$vmid};
2667 my $vmfw_conf = $vmfw_configs->{$vmid};
2668 next if !$vmfw_conf;
2669 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2671 foreach my $netid (keys %$conf) {
2672 next if $netid !~ m/^net(\d+)$/;
2673 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2675 my $iface = "tap${vmid}i$1";
2677 my $bridge = $net->{bridge};
2678 next if !$bridge; # fixme: ?
2680 $bridge .= "v$net->{tag}" if $net->{tag};
2682 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table, $bridges_config);
2684 my $macaddr = $net->{macaddr};
2685 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
2686 $vmfw_conf, $vmid, $bridge, 'IN
');
2687 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
2688 $vmfw_conf, $vmid, $bridge, 'OUT
');
2692 # generate firewall rules for OpenVZ containers
2693 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2694 my $conf = $vmdata->{openvz}->{$vmid};
2696 my $vmfw_conf = $vmfw_configs->{$vmid};
2697 next if !$vmfw_conf;
2698 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2700 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2701 my $ip = $conf->{ip_address}->{value};
2702 generate_venet_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2703 generate_venet_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2706 if ($conf->{netif} && $conf->{netif}->{value}) {
2707 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2708 foreach my $netid (keys %$netif) {
2709 my $d = $netif->{$netid};
2710 my $bridge = $d->{bridge};
2712 warn "no bridge device for CT $vmid iface '$netid'\n";
2716 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table, $bridges_config);
2718 my $macaddr = $d->{mac};
2719 my $iface = $d->{host_ifname};
2720 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
2721 $vmfw_conf, $vmid, $bridge, 'IN
');
2722 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
2723 $vmfw_conf, $vmid, $bridge, 'OUT
');
2728 if($hostfw_options->{optimize}){
2730 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
2731 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
2732 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2735 # fixme: what log level should we use here?
2736 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2738 # fixme: should we really block inter-bridge traffic?
2740 # always allow traffic from containers?
2741 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2743 # disable interbridge routing
2744 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
2745 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
2746 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2747 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2748 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
2749 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2751 return ($ruleset, $ipset_ruleset);
2754 sub get_ruleset_status {
2755 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2757 my $statushash = {};
2759 foreach my $chain (sort keys %$ruleset) {
2760 my $sig = &$digest_fn($ruleset->{$chain});
2762 $statushash->{$chain}->{sig} = $sig;
2764 my $oldsig = $active_chains->{$chain};
2765 if (!defined($oldsig)) {
2766 $statushash->{$chain}->{action} = 'create
';
2768 if ($oldsig eq $sig) {
2769 $statushash->{$chain}->{action} = 'exists';
2771 $statushash->{$chain}->{action} = 'update
';
2774 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2775 foreach my $cmd (@{$ruleset->{$chain}}) {
2776 print "\t$cmd\n" if $verbose;
2780 foreach my $chain (sort keys %$active_chains) {
2781 if (!defined($ruleset->{$chain})) {
2782 my $sig = $active_chains->{$chain};
2783 $statushash->{$chain}->{action} = 'delete';
2784 $statushash->{$chain}->{sig} = $sig;
2785 print "delete $chain ($sig)\n" if $verbose;
2792 sub print_sig_rule {
2793 my ($chain, $sig) = @_;
2795 # We just use this to store a SHA1 checksum used to detect changes
2796 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2799 sub get_ruleset_cmdlist {
2800 my ($ruleset, $verbose) = @_;
2802 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2804 my ($active_chains, $hooks) = iptables_get_chains();
2805 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2807 # create missing chains first
2808 foreach my $chain (sort keys %$ruleset) {
2809 my $stat = $statushash->{$chain};
2810 die "internal error" if !$stat;
2811 next if $stat->{action} ne 'create
';
2813 $cmdlist .= ":$chain - [0:0]\n";
2816 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2817 if (!$hooks->{$h}) {
2818 $cmdlist .= "-A $h -j PVEFW-$h\n";
2822 foreach my $chain (sort keys %$ruleset) {
2823 my $stat = $statushash->{$chain};
2824 die "internal error" if !$stat;
2826 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2827 $cmdlist .= "-F $chain\n";
2828 foreach my $cmd (@{$ruleset->{$chain}}) {
2829 $cmdlist .= "$cmd\n";
2831 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2832 } elsif ($stat->{action
} eq 'delete') {
2833 die "internal error"; # this should not happen
2834 } elsif ($stat->{action
} eq 'exists') {
2837 die "internal error - unknown status '$stat->{action}'";
2841 foreach my $chain (keys %$statushash) {
2842 next if $statushash->{$chain}->{action
} ne 'delete';
2843 $cmdlist .= "-F $chain\n";
2845 foreach my $chain (keys %$statushash) {
2846 next if $statushash->{$chain}->{action
} ne 'delete';
2847 next if $chain eq 'PVEFW-INPUT';
2848 next if $chain eq 'PVEFW-OUTPUT';
2849 next if $chain eq 'PVEFW-FORWARD';
2850 $cmdlist .= "-X $chain\n";
2853 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2855 $cmdlist .= "COMMIT\n";
2857 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2860 sub get_ipset_cmdlist
{
2861 my ($ruleset, $verbose) = @_;
2865 my $delete_cmdlist = "";
2867 my $active_chains = ipset_get_chains
();
2868 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2870 # remove stale _swap chains
2871 foreach my $chain (keys %$active_chains) {
2872 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2873 $cmdlist .= "destroy $chain\n";
2877 foreach my $chain (sort keys %$ruleset) {
2878 my $stat = $statushash->{$chain};
2879 die "internal error" if !$stat;
2881 if ($stat->{action
} eq 'create') {
2882 foreach my $cmd (@{$ruleset->{$chain}}) {
2883 $cmdlist .= "$cmd\n";
2887 if ($stat->{action
} eq 'update') {
2888 my $chain_swap = $chain."_swap";
2890 foreach my $cmd (@{$ruleset->{$chain}}) {
2891 $cmd =~ s/$chain/$chain_swap/;
2892 $cmdlist .= "$cmd\n";
2894 $cmdlist .= "swap $chain_swap $chain\n";
2895 $cmdlist .= "flush $chain_swap\n";
2896 $cmdlist .= "destroy $chain_swap\n";
2901 foreach my $chain (keys %$statushash) {
2902 next if $statushash->{$chain}->{action
} ne 'delete';
2904 $delete_cmdlist .= "flush $chain\n";
2905 $delete_cmdlist .= "destroy $chain\n";
2908 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
2910 return ($cmdlist, $delete_cmdlist, $changes);
2914 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2916 enable_bridge_firewall
();
2918 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2919 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
2921 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
2924 if ($ipset_changes) {
2925 print "ipset changes:\n";
2926 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2927 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2931 print "iptables changes:\n";
2936 ipset_restore_cmdlist
($ipset_create_cmdlist);
2938 iptables_restore_cmdlist
($cmdlist);
2940 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2942 # test: re-read status and check if everything is up to date
2943 my $active_chains = iptables_get_chains
();
2944 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
2947 foreach my $chain (sort keys %$ruleset) {
2948 my $stat = $statushash->{$chain};
2949 if ($stat->{action
} ne 'exists') {
2950 warn "unable to update chain '$chain'\n";
2955 die "unable to apply firewall changes\n" if $errors;
2957 update_nf_conntrack_max
($hostfw_conf);
2959 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
2963 sub update_nf_conntrack_max
{
2964 my ($hostfw_conf) = @_;
2966 my $max = 65536; # reasonable default
2968 my $options = $hostfw_conf->{options
} || {};
2970 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
2971 $max = $options->{nf_conntrack_max
};
2972 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2975 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2976 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2978 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
2980 if ($current != $max) {
2981 my $hashsize = int($max/4);
2982 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
2983 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
2987 sub update_nf_conntrack_tcp_timeout_established
{
2988 my ($hostfw_conf) = @_;
2990 my $options = $hostfw_conf->{options
} || {};
2992 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
2994 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
2997 sub remove_pvefw_chains
{
2999 my ($chash, $hooks) = iptables_get_chains
();
3000 my $cmdlist = "*filter\n";
3002 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3004 $cmdlist .= "-D $h -j PVEFW-$h\n";
3008 foreach my $chain (keys %$chash) {
3009 $cmdlist .= "-F $chain\n";
3012 foreach my $chain (keys %$chash) {
3013 $cmdlist .= "-X $chain\n";
3015 $cmdlist .= "COMMIT\n";
3017 iptables_restore_cmdlist
($cmdlist);
3021 my ($start, $verbose) = @_;
3025 my $cluster_conf = load_clusterfw_conf
();
3026 my $cluster_options = $cluster_conf->{options
};
3028 my $enable = $cluster_options->{enable
};
3030 my $status = read_pvefw_status
();
3032 die "Firewall is disabled - cannot start\n" if !$enable && $start;
3035 PVE
::Firewall
::remove_pvefw_chains
();
3036 print "Firewall disabled\n" if $verbose;
3040 my $hostfw_conf = load_hostfw_conf
();
3042 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3044 if ($start || $status eq 'active') {
3046 save_pvefw_status
('active') if ($status ne 'active');
3048 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
3050 print "Firewall not active (status = $status)\n" if $verbose;