8 use Socket
qw(AF_INET6 inet_ntop inet_pton);
10 use PVE
::Exception
qw(raise raise_param_exc);
11 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
14 use PVE
::Tools
qw($IPV4RE $IPV6RE);
19 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
22 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
23 my $pvefw_conf_dir = "/etc/pve/firewall";
24 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
26 # dynamically include PVE::QemuServer and PVE::OpenVZ
27 # to avoid dependency problems
30 require PVE
::QemuServer
;
31 $have_qemu_server = 1;
37 $have_pve_manager = 1;
40 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
41 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
42 my $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
44 my $max_alias_name_length = 64;
45 my $max_ipset_name_length = 64;
46 my $max_group_name_length = 20;
48 PVE
::JSONSchema
::register_format
('IPorCIDR', \
&pve_verify_ip_or_cidr
);
49 sub pve_verify_ip_or_cidr
{
50 my ($cidr, $noerr) = @_;
52 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
53 return $cidr if Net
::IP-
>new($cidr);
54 return undef if $noerr;
55 die Net
::IP
::Error
() . "\n";
57 return undef if $noerr;
58 die "value does not look like a valid IP address or CIDR network\n";
61 PVE
::JSONSchema
::register_format
('IPorCIDRorAlias', \
&pve_verify_ip_or_cidr_or_alias
);
62 sub pve_verify_ip_or_cidr_or_alias
{
63 my ($cidr, $noerr) = @_;
65 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
67 return pve_verify_ip_or_cidr
($cidr, $noerr);
70 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
71 description
=> "IP set name.",
73 pattern
=> $ipset_name_pattern,
75 maxLength
=> $max_ipset_name_length,
78 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
79 description
=> "Alias name.",
81 pattern
=> $ip_alias_pattern,
83 maxLength
=> $max_alias_name_length,
86 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
87 description
=> "Log level.",
89 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
93 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
94 description
=> "Security Group name.",
96 pattern
=> $security_group_name_pattern,
98 maxLength
=> $max_group_name_length,
101 my $feature_ipset_nomatch = 0;
103 my (undef, undef, $release) = POSIX
::uname
();
104 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
105 my ($major, $minor) = ($1, $2);
106 $feature_ipset_nomatch = 1 if ($major > 3) ||
107 ($major == 3 && $minor >= 7);
114 my $nodename = PVE
::INotify
::nodename
();
116 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
118 my $default_log_level = 'nolog'; # avoid logs by default
120 my $log_level_hash = {
131 # imported/converted from: /usr/share/shorewall/macro.*
132 my $pve_fw_macros = {
135 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
136 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
139 "Auth (identd) traffic",
140 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
143 "Border Gateway Protocol traffic",
144 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
147 "BitTorrent traffic for BitTorrent 3.1 and earlier",
148 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
149 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
152 "BitTorrent traffic for BitTorrent 3.2 and later",
153 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
154 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
157 "Concurrent Versions System pserver traffic",
158 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
161 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
162 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
163 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
164 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
167 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
168 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
169 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
172 "Distributed Checksum Clearinghouse spam filtering mechanism",
173 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
176 "Forwarded DHCP traffic",
177 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
180 "Domain Name System traffic (upd and tcp)",
181 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
182 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
185 "Distributed Compiler service",
186 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
189 "File Transfer Protocol",
190 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
193 "Finger protocol (RFC 742)",
194 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
197 "GNUnet secure peer-to-peer networking traffic",
198 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
199 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
200 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
201 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
204 "Generic Routing Encapsulation tunneling protocol",
205 { action
=> 'PARAM', proto
=> '47' },
208 "Git distributed revision control traffic",
209 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
212 "OpenPGP HTTP keyserver protocol traffic",
213 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
216 "Hypertext Transfer Protocol (WWW)",
217 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
220 "Hypertext Transfer Protocol (WWW) over SSL",
221 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
224 "Internet Cache Protocol V2 (Squid) traffic",
225 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
228 "AOL Instant Messenger traffic",
229 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
232 "Internet Message Access Protocol",
233 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
236 "Internet Message Access Protocol over SSL",
237 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
240 "IPIP capsulation traffic",
241 { action
=> 'PARAM', proto
=> '94' },
245 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
246 { action
=> 'PARAM', proto
=> '50' },
249 "IPsec authentication (AH) traffic",
250 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
251 { action
=> 'PARAM', proto
=> '51' },
254 "IPsec traffic and Nat-Traversal",
255 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
256 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
257 { action
=> 'PARAM', proto
=> '50' },
260 "Internet Relay Chat traffic",
261 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
264 "HP Jetdirect printing",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
268 "Layer 2 Tunneling Protocol traffic",
269 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
272 "Lightweight Directory Access Protocol traffic",
273 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
276 "Secure Lightweight Directory Access Protocol traffic",
277 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
280 "Microsoft Notification Protocol",
281 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
284 "Microsoft SQL Server",
285 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
288 "Mail traffic (SMTP, SMTPS, Submission)",
289 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
290 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
291 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
294 "Munin networked resource monitoring traffic",
295 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
299 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
302 "NNTP traffic (Usenet).",
303 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
306 "Encrypted NNTP traffic (Usenet)",
307 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
310 "Network Time Protocol (ntpd)",
311 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
314 "OSPF multicast traffic",
315 { action
=> 'PARAM', proto
=> '89' },
319 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
322 "Symantec PCAnywere (tm)",
323 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
324 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
328 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
331 "Encrypted POP3 traffic",
332 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
335 "Point-to-Point Tunneling Protocol",
336 { action
=> 'PARAM', proto
=> '47' },
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
341 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
345 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
348 "Line Printer protocol printing",
349 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
352 "Microsoft Remote Desktop Protocol traffic",
353 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
356 "Routing Information Protocol (bidirectional)",
357 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
360 "BIND remote management protocol",
361 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
364 "Razor Antispam System",
365 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
368 "Remote time retrieval (rdate)",
369 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
373 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
376 "SANE network scanning",
377 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
380 "Microsoft SMB traffic",
381 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
382 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
383 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
384 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
387 "Samba Web Administration Tool",
388 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
391 "Simple Mail Transfer Protocol",
392 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
395 "Encrypted Simple Mail Transfer Protocol",
396 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
399 "Simple Network Management Protocol",
400 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
401 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
404 "Spam Assassin SPAMD traffic",
405 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
408 "Secure shell traffic",
409 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
412 "Subversion server (svnserve)",
413 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
416 "SixXS IPv6 Deployment and Tunnel Broker",
417 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
418 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
419 { action
=> 'PARAM', proto
=> '41' },
420 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
423 "Squid web proxy traffic",
424 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
427 "Mail message submission traffic",
428 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
431 "Syslog protocol (RFC 5424) traffic",
432 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
436 "Trivial File Transfer Protocol traffic",
437 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
441 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
445 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
448 "RFC 868 Time protocol",
449 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
452 "Traceroute (for up to 30 hops) traffic",
453 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
454 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
457 "VNC traffic for VNC display's 0 - 99",
458 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
461 "VNC traffic from Vncservers to Vncviewers in listen mode",
462 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
465 "WWW traffic (HTTP and HTTPS)",
466 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
467 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
470 "Web Cache/Proxy traffic (port 8080)",
471 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
475 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
478 "Whois (nicname, RFC 3912) traffic",
479 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
483 my $pve_fw_parsed_macros;
484 my $pve_fw_macro_descr;
485 my $pve_fw_preferred_macro_names = {};
487 my $pve_std_chains = {};
488 $pve_std_chains->{4} = {
489 'PVEFW-SET-ACCEPT-MARK' => [
490 "-j MARK --set-mark 1",
492 'PVEFW-DropBroadcast' => [
493 # same as shorewall 'Broadcast'
494 # simply DROP BROADCAST/MULTICAST/ANYCAST
495 # we can use this to reduce logging
496 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
497 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
498 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
499 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
502 # same as shorewall 'reject'
503 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
504 { action
=> 'DROP', source
=> '224.0.0.0/4' },
505 { action
=> 'DROP', proto
=> 'icmp' },
506 "-p tcp -j REJECT --reject-with tcp-reset",
507 "-p udp -j REJECT --reject-with icmp-port-unreachable",
508 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
509 "-j REJECT --reject-with icmp-host-prohibited",
512 # same as shorewall 'Drop', which is equal to DROP,
513 # but REJECT/DROP some packages to reduce logging,
514 # and ACCEPT critical ICMP types
515 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
516 # we are not interested in BROADCAST/MULTICAST/ANYCAST
517 { action
=> 'PVEFW-DropBroadcast' },
518 # ACCEPT critical ICMP types
519 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
520 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
521 # Drop packets with INVALID state
522 "-m conntrack --ctstate INVALID -j DROP",
523 # Drop Microsoft SMB noise
524 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
525 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
526 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
527 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
528 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
529 # Drop new/NotSyn traffic so that it doesn't get logged
530 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
532 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
535 # same as shorewall 'Reject', which is equal to Reject,
536 # but REJECT/DROP some packages to reduce logging,
537 # and ACCEPT critical ICMP types
538 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
539 # we are not interested in BROADCAST/MULTICAST/ANYCAST
540 { action
=> 'PVEFW-DropBroadcast' },
541 # ACCEPT critical ICMP types
542 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
543 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
544 # Drop packets with INVALID state
545 "-m conntrack --ctstate INVALID -j DROP",
546 # Drop Microsoft SMB noise
547 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
548 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
549 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
550 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
551 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
552 # Drop new/NotSyn traffic so that it doesn't get logged
553 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
555 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
557 'PVEFW-tcpflags' => [
558 # same as shorewall tcpflags action.
559 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
560 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
561 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
562 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
563 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
564 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
567 # same as shorewall smurfs action
568 # Filter packets for smurfs (packets with a broadcast address as the source).
569 "-s 0.0.0.0/32 -j RETURN",
570 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
571 "-s 224.0.0.0/4 -g PVEFW-smurflog",
575 $pve_std_chains->{6} = {
576 'PVEFW-SET-ACCEPT-MARK' => [
577 "-j MARK --set-mark 1",
579 'PVEFW-DropBroadcast' => [
580 # same as shorewall 'Broadcast'
581 # simply DROP BROADCAST/MULTICAST/ANYCAST
582 # we can use this to reduce logging
583 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
584 # ipv6 addrtype does not work with kernel 2.6.32
585 #{ action => 'DROP', dsttype => 'MULTICAST' },
586 #{ action => 'DROP', dsttype => 'ANYCAST' },
587 { action
=> 'DROP', dest
=> 'ff00::/8' },
588 #{ action => 'DROP', dest => '224.0.0.0/4' },
591 # same as shorewall 'reject'
592 #{ action => 'DROP', dsttype => 'BROADCAST' },
593 #{ action => 'DROP', source => '224.0.0.0/4' },
594 { action
=> 'DROP', proto
=> 'icmpv6' },
595 "-p tcp -j REJECT --reject-with tcp-reset",
596 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
597 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
598 #"-j REJECT --reject-with icmp-host-prohibited",
601 # same as shorewall 'Drop', which is equal to DROP,
602 # but REJECT/DROP some packages to reduce logging,
603 # and ACCEPT critical ICMP types
604 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
605 # we are not interested in BROADCAST/MULTICAST/ANYCAST
606 { action
=> 'PVEFW-DropBroadcast' },
607 # ACCEPT critical ICMP types
608 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
609 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
610 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
612 # Drop packets with INVALID state
613 "-m conntrack --ctstate INVALID -j DROP",
614 # Drop Microsoft SMB noise
615 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
616 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
617 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
618 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
619 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
620 # Drop new/NotSyn traffic so that it doesn't get logged
621 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
623 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
626 # same as shorewall 'Reject', which is equal to Reject,
627 # but REJECT/DROP some packages to reduce logging,
628 # and ACCEPT critical ICMP types
629 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
630 # we are not interested in BROADCAST/MULTICAST/ANYCAST
631 { action
=> 'PVEFW-DropBroadcast' },
632 # ACCEPT critical ICMP types
633 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
634 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
635 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
637 # Drop packets with INVALID state
638 "-m conntrack --ctstate INVALID -j DROP",
639 # Drop Microsoft SMB noise
640 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
641 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
642 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
643 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
644 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
645 # Drop new/NotSyn traffic so that it doesn't get logged
646 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
648 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
650 'PVEFW-tcpflags' => [
651 # same as shorewall tcpflags action.
652 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
653 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
654 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
655 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
656 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
657 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
661 # iptables -p icmp -h
662 my $icmp_type_names = {
665 'destination-unreachable' => 1,
666 'network-unreachable' => 1,
667 'host-unreachable' => 1,
668 'protocol-unreachable' => 1,
669 'port-unreachable' => 1,
670 'fragmentation-needed' => 1,
671 'source-route-failed' => 1,
672 'network-unknown' => 1,
674 'network-prohibited' => 1,
675 'host-prohibited' => 1,
676 'TOS-network-unreachable' => 1,
677 'TOS-host-unreachable' => 1,
678 'communication-prohibited' => 1,
679 'host-precedence-violation' => 1,
680 'precedence-cutoff' => 1,
681 'source-quench' => 1,
683 'network-redirect' => 1,
684 'host-redirect' => 1,
685 'TOS-network-redirect' => 1,
686 'TOS-host-redirect' => 1,
688 'router-advertisement' => 1,
689 'router-solicitation' => 1,
690 'time-exceeded' => 1,
691 'ttl-zero-during-transit' => 1,
692 'ttl-zero-during-reassembly' => 1,
693 'parameter-problem' => 1,
694 'ip-header-bad' => 1,
695 'required-option-missing' => 1,
696 'timestamp-request' => 1,
697 'timestamp-reply' => 1,
698 'address-mask-request' => 1,
699 'address-mask-reply' => 1,
702 # ip6tables -p icmpv6 -h
704 my $icmpv6_type_names = {
706 'destination-unreachable' => 1,
708 'communication-prohibited' => 1,
709 'address-unreachable' => 1,
710 'port-unreachable' => 1,
711 'packet-too-big' => 1,
712 'time-exceeded' => 1,
713 'ttl-zero-during-transit' => 1,
714 'ttl-zero-during-reassembly' => 1,
715 'parameter-problem' => 1,
717 'unknown-header-type' => 1,
718 'unknown-option' => 1,
721 'router-solicitation' => 1,
722 'router-advertisement' => 1,
723 'neighbour-solicitation' => 1,
724 'neighbour-advertisement' => 1,
728 sub init_firewall_macros
{
730 $pve_fw_parsed_macros = {};
732 foreach my $k (keys %$pve_fw_macros) {
733 my $lc_name = lc($k);
734 my $macro = $pve_fw_macros->{$k};
735 if (!ref($macro->[0])) {
736 $pve_fw_macro_descr->{$k} = shift @$macro;
738 $pve_fw_preferred_macro_names->{$lc_name} = $k;
739 $pve_fw_parsed_macros->{$k} = $macro;
743 init_firewall_macros
();
746 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
751 sub get_etc_services
{
753 return $etc_services if $etc_services;
755 my $filename = "/etc/services";
757 my $fh = IO
::File-
>new($filename, O_RDONLY
);
759 warn "unable to read '$filename' - $!\n";
765 while (my $line = <$fh>) {
767 next if $line =~m/^#/;
768 next if ($line =~m/^\s*$/);
770 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
771 $services->{byid
}->{$2}->{name
} = $1;
772 $services->{byid
}->{$2}->{port
} = $2;
773 $services->{byid
}->{$2}->{$3} = 1;
774 $services->{byname
}->{$1} = $services->{byid
}->{$2};
780 $etc_services = $services;
783 return $etc_services;
788 sub get_etc_protocols
{
789 return $etc_protocols if $etc_protocols;
791 my $filename = "/etc/protocols";
793 my $fh = IO
::File-
>new($filename, O_RDONLY
);
795 warn "unable to read '$filename' - $!\n";
801 while (my $line = <$fh>) {
803 next if $line =~m/^#/;
804 next if ($line =~m/^\s*$/);
806 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
807 $protocols->{byid
}->{$2}->{name
} = $1;
808 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
814 # add special case for ICMP v6
815 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
816 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
818 $etc_protocols = $protocols;
820 return $etc_protocols;
823 my $ipv4_mask_hash_localnet = {
825 '255.255.128.0' => 17,
826 '255.255.192.0' => 18,
827 '255.255.224.0' => 19,
828 '255.255.240.0' => 20,
829 '255.255.248.0' => 21,
830 '255.255.252.0' => 22,
831 '255.255.254.0' => 23,
832 '255.255.255.0' => 24,
833 '255.255.255.128' => 25,
834 '255.255.255.192' => 26,
835 '255.255.255.224' => 27,
836 '255.255.255.240' => 28,
837 '255.255.255.248' => 29,
838 '255.255.255.252' => 30,
844 my ($new_value) = @_;
846 $__local_network = $new_value if defined($new_value);
848 return $__local_network if defined($__local_network);
851 my $nodename = PVE
::INotify
::nodename
();
853 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
855 my $testip = Net
::IP-
>new($ip);
857 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
858 foreach my $entry (@$routes) {
859 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
860 next if !defined($mask);
861 return if $mask eq '0.0.0.0';
862 my $cidr = "$entry->{dest}/$mask";
863 my $testnet = Net
::IP-
>new($cidr);
864 if ($testnet->overlaps($testip)) {
865 $__local_network = $cidr;
872 return $__local_network;
875 # ipset names are limited to 31 characters,
876 # and we use '-v4' or '-v6' to indicate IP versions,
877 # and we use '_swap' suffix for atomic update,
878 # for example PVEFW-${VMID}-${ipset_name}_swap
880 my $max_iptables_ipset_name_length = 31 - length("_swap") - length("-v4");
882 sub compute_ipset_chain_name
{
883 my ($vmid, $ipset_name) = @_;
885 $vmid = 0 if !defined($vmid);
887 my $id = "$vmid-${ipset_name}";
889 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
890 $id = PVE
::Tools
::fnv31a_hex
($id);
896 sub compute_ipfilter_ipset_name
{
899 return "ipfilter-$iface";
902 sub parse_address_list
{
905 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
906 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
910 if ($str =~ m/^${ip_alias_pattern}$/) {
911 die "alias name too long\n" if length($str) > $max_alias_name_length;
919 foreach my $elem (split(/,/, $str)) {
921 my $ip = Net
::IP-
>new($elem);
923 my $err = Net
::IP
::Error
();
924 die "invalid IP address: $err\n";
926 $iprange = 1 if $elem =~ m/-/;
928 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
930 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
931 if $ipversion && ($new_ipversion != $ipversion);
933 $ipversion = $new_ipversion;
936 die "you can't use a range in a list\n" if $iprange && $count > 1;
941 sub parse_port_name_number_or_range
{
944 my $services = PVE
::Firewall
::get_etc_services
();
948 foreach my $item (split(/,/, $str)) {
950 if ($item =~ m/^(\d+):(\d+)$/) {
951 my ($port1, $port2) = ($1, $2);
952 die "invalid port '$port1'\n" if $port1 > 65535;
953 die "invalid port '$port2'\n" if $port2 > 65535;
954 } elsif ($item =~ m/^(\d+)$/) {
956 die "invalid port '$port'\n" if $port > 65535;
958 if ($icmp_type_names->{$item}) {
960 } elsif ($icmpv6_type_names->{$item}) {
963 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
968 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
973 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
974 sub pve_fw_verify_port_spec
{
977 parse_port_name_number_or_range
($portstr);
982 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
983 sub pve_fw_verify_addr_spec
{
986 parse_address_list
($list);
991 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
992 sub pve_fw_verify_protocol_spec
{
995 my $protocols = get_etc_protocols
();
997 die "unknown protocol '$proto'\n" if $proto &&
998 !(defined($protocols->{byname
}->{$proto}) ||
999 defined($protocols->{byid
}->{$proto}));
1005 # helper function for API
1007 sub copy_opject_with_digest
{
1010 my $sha = Digest
::SHA-
>new('sha1');
1013 foreach my $k (sort keys %$object) {
1014 my $v = $object->{$k};
1015 next if !defined($v);
1017 $sha->add($k, ':', $v, "\n");
1020 my $digest = $sha->hexdigest;
1022 $res->{digest
} = $digest;
1024 return wantarray ?
($res, $digest) : $res;
1027 sub copy_list_with_digest
{
1030 my $sha = Digest
::SHA-
>new('sha1');
1033 foreach my $entry (@$list) {
1035 foreach my $k (sort keys %$entry) {
1036 my $v = $entry->{$k};
1037 next if !defined($v);
1039 # Note: digest ignores refs ($rule->{errors})
1040 $sha->add($k, ':', $v, "\n") if !ref($v); ;
1045 my $digest = $sha->hexdigest;
1047 foreach my $entry (@$res) {
1048 $entry->{digest
} = $digest;
1051 return wantarray ?
($res, $digest) : $res;
1054 my $rule_properties = {
1056 description
=> "Update rule at position <pos>.",
1061 digest
=> get_standard_option
('pve-config-digest'),
1065 enum
=> ['in', 'out', 'group'],
1068 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1071 pattern
=> $security_group_name_pattern,
1080 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
1082 type
=> 'string', format
=> 'pve-fw-addr-spec',
1086 type
=> 'string', format
=> 'pve-fw-addr-spec',
1090 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1098 type
=> 'string', format
=> 'pve-fw-port-spec',
1102 type
=> 'string', format
=> 'pve-fw-port-spec',
1111 sub add_rule_properties
{
1112 my ($properties) = @_;
1114 foreach my $k (keys %$rule_properties) {
1115 my $h = $rule_properties->{$k};
1116 # copy data, so that we can modify later without side effects
1117 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1123 sub delete_rule_properties
{
1124 my ($rule, $delete_str) = @_;
1126 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1127 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1128 if !defined($rule_properties->{$opt});
1129 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1130 if $opt eq 'type' || $opt eq 'action';
1131 delete $rule->{$opt};
1137 my $apply_macro = sub {
1138 my ($macro_name, $param, $verify) = @_;
1140 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1141 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1145 foreach my $templ (@$macro_rules) {
1147 my $param_used = {};
1148 foreach my $k (keys %$templ) {
1149 my $v = $templ->{$k};
1150 if ($v eq 'PARAM') {
1152 $param_used->{$k} = 1;
1153 } elsif ($v eq 'DEST') {
1154 $v = $param->{dest
};
1155 $param_used->{dest
} = 1;
1156 } elsif ($v eq 'SOURCE') {
1157 $v = $param->{source
};
1158 $param_used->{source
} = 1;
1162 my $msg = "missing parameter '$k' in macro '$macro_name'";
1163 raise_param_exc
({ macro => $msg }) if $verify;
1168 foreach my $k (keys %$param) {
1169 next if $k eq 'macro';
1170 next if !defined($param->{$k});
1171 next if $param_used->{$k};
1172 if (defined($rule->{$k})) {
1173 if ($rule->{$k} ne $param->{$k}) {
1174 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1175 raise_param_exc
({ $k => $msg }) if $verify;
1179 $rule->{$k} = $param->{$k};
1182 push @$rules, $rule;
1188 my $rule_env_iface_lookup = {
1197 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1199 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1201 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1202 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1204 my $errors = $rule->{errors
} || {};
1206 my $error_count = 0;
1208 my $add_error = sub {
1209 my ($param, $msg) = @_;
1211 raise_param_exc
({ $param => $msg }) if !$noerr;
1213 $errors->{$param} = $msg if !$errors->{$param};
1216 my $check_ipset_or_alias_property = sub {
1217 my ($name, $expected_ipversion) = @_;
1219 if (my $value = $rule->{$name}) {
1220 if ($value =~ m/^\+/) {
1221 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1222 &$add_error($name, "no such ipset '$1'")
1223 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1226 &$add_error($name, "invalid ipset name '$value'");
1228 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1229 my $alias = lc($value);
1230 &$add_error($name, "no such alias '$value'")
1231 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1233 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1234 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1236 die "detected mixed ipv4/ipv6 adresses in rule\n"
1237 if $expected_ipversion && ($expected_ipversion != $e->{ipversion
});
1242 my $type = $rule->{type
};
1243 my $action = $rule->{action
};
1245 &$add_error('type', "missing property") if !$type;
1246 &$add_error('action', "missing property") if !$action;
1249 if ($type eq 'in' || $type eq 'out') {
1250 &$add_error('action', "unknown action '$action'")
1251 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1252 } elsif ($type eq 'group') {
1253 &$add_error('type', "security groups not allowed")
1255 &$add_error('action', "invalid characters in security group name")
1256 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1258 &$add_error('type', "unknown rule type '$type'");
1262 if ($rule->{iface
}) {
1263 &$add_error('type', "parameter -i not allowed for this rule type")
1265 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1266 &$add_error('iface', $@) if $@;
1267 if ($rule_env eq 'vm') {
1268 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1269 if $rule->{iface
} !~ m/^net(\d+)$/;
1270 } elsif ($rule_env eq 'ct') {
1271 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1272 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1276 if ($rule->{macro}) {
1277 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1278 $rule->{macro} = $preferred_name;
1280 &$add_error('macro', "unknown macro '$rule->{macro}'");
1285 my $set_ip_version = sub {
1288 die "detected mixed ipv4/ipv6 adresses in rule\n"
1289 if $ipversion && ($vers != $ipversion);
1294 if ($rule->{proto
}) {
1295 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1296 &$add_error('proto', $@) if $@;
1297 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1298 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1301 if ($rule->{dport
}) {
1302 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1303 &$add_error('dport', $@) if $@;
1304 &$add_error('proto', "missing property - 'dport' requires this property")
1308 if ($rule->{sport
}) {
1309 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1310 &$add_error('sport', $@) if $@;
1311 &$add_error('proto', "missing property - 'sport' requires this property")
1315 if ($rule->{source
}) {
1317 my $source_ipversion = parse_address_list
($rule->{source
});
1318 &$set_ip_version($source_ipversion);
1320 &$add_error('source', $@) if $@;
1321 &$check_ipset_or_alias_property('source', $ipversion);
1324 if ($rule->{dest
}) {
1326 my $dest_ipversion = parse_address_list
($rule->{dest
});
1327 &$set_ip_version($dest_ipversion);
1329 &$add_error('dest', $@) if $@;
1330 &$check_ipset_or_alias_property('dest', $ipversion);
1333 if ($rule->{macro} && !$error_count) {
1334 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1336 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1337 my $eh = $err->{errors
};
1338 foreach my $p (keys %$eh) {
1339 &$add_error($p, $eh->{$p});
1342 &$add_error('macro', "$err");
1347 $rule->{errors
} = $errors if $error_count;
1348 $rule->{ipversion
} = $ipversion if $ipversion;
1353 sub copy_rule_data
{
1354 my ($rule, $param) = @_;
1356 foreach my $k (keys %$rule_properties) {
1357 if (defined(my $v = $param->{$k})) {
1358 if ($v eq '' || $v eq '-') {
1369 sub rules_modify_permissions
{
1370 my ($rule_env) = @_;
1372 if ($rule_env eq 'host') {
1374 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1376 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1378 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1380 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1382 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1389 sub rules_audit_permissions
{
1390 my ($rule_env) = @_;
1392 if ($rule_env eq 'host') {
1394 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1396 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1398 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1400 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1402 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1410 my $bridge_firewall_enabled = 0;
1412 sub enable_bridge_firewall
{
1414 return if $bridge_firewall_enabled; # only once
1416 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1417 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1419 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1420 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1422 $bridge_firewall_enabled = 1;
1425 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1427 sub iptables_restore_cmdlist
{
1430 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1433 sub ip6tables_restore_cmdlist
{
1436 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1439 sub ipset_restore_cmdlist
{
1442 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1445 sub iptables_get_chains
{
1446 my ($iptablescmd) = @_;
1448 $iptablescmd = "iptables" if !$iptablescmd;
1452 # check what chains we want to track
1453 my $is_pvefw_chain = sub {
1456 return 1 if $name =~ m/^PVEFW-\S+$/;
1458 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1460 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1462 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1464 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1465 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1477 return if $line =~ m/^#/;
1478 return if $line =~ m/^\s*$/;
1480 if ($line =~ m/^\*(\S+)$/) {
1485 return if $table ne 'filter';
1487 if ($line =~ m/^:(\S+)\s/) {
1489 return if !&$is_pvefw_chain($chain);
1490 $res->{$chain} = "unknown";
1491 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1492 my ($chain, $sig) = ($1, $2);
1493 return if !&$is_pvefw_chain($chain);
1494 $res->{$chain} = $sig;
1495 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1498 # simply ignore the rest
1503 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1505 return wantarray ?
($res, $hooks) : $res;
1508 sub iptables_chain_digest
{
1510 my $digest = Digest
::SHA-
>new('sha1');
1511 foreach my $rule (@$rules) { # order is important
1512 $digest->add($rule);
1514 return $digest->b64digest;
1517 sub ipset_chain_digest
{
1520 my $digest = Digest
::SHA-
>new('sha1');
1521 foreach my $rule (sort @$rules) { # note: sorted
1522 $digest->add($rule);
1524 return $digest->b64digest;
1527 sub ipset_get_chains
{
1535 return if $line =~ m/^#/;
1536 return if $line =~ m/^\s*$/;
1537 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1539 $line =~ s/\s+$//; # delete trailing white space
1540 push @{$chains->{$chain}}, $line;
1542 # simply ignore the rest
1547 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1549 # compute digest for each chain
1550 foreach my $chain (keys %$chains) {
1551 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1557 sub ruleset_generate_cmdstr
{
1558 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1560 return if defined($rule->{enable
}) && !$rule->{enable
};
1561 return if $rule->{errors
};
1563 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1565 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1566 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1570 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1571 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1573 my $source = $rule->{source
};
1574 my $dest = $rule->{dest
};
1577 if ($source =~ m/^\+/) {
1578 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1580 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1581 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1582 push @cmd, "-m set --match-set ${ipset_chain} src";
1583 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1584 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1585 push @cmd, "-m set --match-set ${ipset_chain} src";
1587 die "no such ipset '$name'\n";
1590 die "invalid security group name '$source'\n";
1592 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1593 my $alias = lc($source);
1594 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1595 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1596 die "no such alias '$source'\n" if !$e;
1597 push @cmd, "-s $e->{cidr}";
1598 } elsif ($source =~ m/\-/){
1599 push @cmd, "-m iprange --src-range $source";
1601 push @cmd, "-s $source";
1606 if ($dest =~ m/^\+/) {
1607 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1609 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1610 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1611 push @cmd, "-m set --match-set ${ipset_chain} dst";
1612 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1613 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1614 push @cmd, "-m set --match-set ${ipset_chain} dst";
1616 die "no such ipset '$name'\n";
1619 die "invalid security group name '$dest'\n";
1621 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1622 my $alias = lc($dest);
1623 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1624 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1625 die "no such alias '$dest'\n" if !$e;
1626 push @cmd, "-d $e->{cidr}";
1627 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1628 push @cmd, "-m iprange --dst-range $dest";
1630 push @cmd, "-d $dest";
1634 if ($rule->{proto
}) {
1635 push @cmd, "-p $rule->{proto}";
1638 $multiport++ if $nbdport > 1;
1639 $multiport++ if $nbsport > 1;
1641 push @cmd, "--match multiport" if $multiport;
1643 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1644 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1646 if ($rule->{dport
}) {
1647 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1648 # Note: we use dport to store --icmp-type
1649 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1650 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1651 } elsif ($rule->{proto
} && $rule->{proto
} eq 'icmpv6') {
1652 # Note: we use dport to store --icmpv6-type
1653 die "unknown icmpv6-type '$rule->{dport}'\n" if !defined($icmpv6_type_names->{$rule->{dport
}});
1654 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1657 if ($multiport == 2) {
1658 push @cmd, "--ports $rule->{dport}";
1660 push @cmd, "--dports $rule->{dport}";
1663 push @cmd, "--dport $rule->{dport}";
1668 if ($rule->{sport
}) {
1670 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1672 push @cmd, "--sport $rule->{sport}";
1675 } elsif ($rule->{dport
} || $rule->{sport
}) {
1676 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1677 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1680 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1682 if (my $action = $rule->{action
}) {
1683 $action = $actions->{$action} if defined($actions->{$action});
1684 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1685 push @cmd, $goto ?
"-g $action" : "-j $action";
1688 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1691 sub ruleset_generate_rule
{
1692 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1696 if ($rule->{macro}) {
1697 $rules = &$apply_macro($rule->{macro}, $rule);
1702 # update all or nothing
1705 foreach my $tmp (@$rules) {
1706 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1707 push @cmds, $cmdstr;
1711 foreach my $cmdstr (@cmds) {
1712 ruleset_addrule
($ruleset, $chain, $cmdstr);
1716 sub ruleset_generate_rule_insert
{
1717 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1719 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1721 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1722 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1726 sub ruleset_create_chain
{
1727 my ($ruleset, $chain) = @_;
1729 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1730 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1732 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1734 $ruleset->{$chain} = [];
1737 sub ruleset_chain_exist
{
1738 my ($ruleset, $chain) = @_;
1740 return $ruleset->{$chain} ?
1 : undef;
1743 sub ruleset_addrule
{
1744 my ($ruleset, $chain, $rule) = @_;
1746 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1748 push @{$ruleset->{$chain}}, "-A $chain $rule";
1751 sub ruleset_insertrule
{
1752 my ($ruleset, $chain, $rule) = @_;
1754 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1756 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1759 sub get_log_rule_base
{
1760 my ($chain, $vmid, $msg, $loglevel) = @_;
1762 die "internal error - no log level" if !defined($loglevel);
1764 $vmid = 0 if !defined($vmid);
1766 # Note: we use special format for prefix to pass further
1767 # info to log daemon (VMID, LOGVELEL and CHAIN)
1769 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1772 sub ruleset_addlog {
1773 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1775 return if !defined($loglevel);
1777 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1779 $logrule = "$rule $logrule" if defined($rule);
1781 ruleset_addrule($ruleset, $chain, $logrule);
1784 sub ruleset_add_chain_policy {
1785 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1787 if ($policy eq 'ACCEPT') {
1789 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1790 { ACCEPT => $accept_action});
1792 } elsif ($policy eq 'DROP') {
1794 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1796 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1798 ruleset_addrule($ruleset, $chain, "-j DROP
");
1799 } elsif ($policy eq 'REJECT') {
1800 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1802 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1804 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1807 die "internal error
: unknown policy
'$policy'";
1811 sub ruleset_chain_add_conn_filters {
1812 my ($ruleset, $chain, $accept) = @_;
1814 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1815 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1818 sub ruleset_chain_add_input_filters {
1819 my ($ruleset, $chain, $options, $cluster_conf, $ipversion, $loglevel) = @_;
1821 if ($cluster_conf->{ipset}->{blacklist}){
1822 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1823 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1824 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1825 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1827 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1828 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1831 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1832 if ($ipversion == 4) {
1833 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1837 if ($options->{tcpflags}) {
1838 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1842 sub ruleset_create_vm_chain {
1843 my ($ruleset, $chain, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1845 ruleset_create_chain($ruleset, $chain);
1846 my $accept = generate_nfqueue($options);
1848 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1849 if ($direction eq 'OUT') {
1850 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1851 proto => 'udp', sport => 68, dport => 67 });
1853 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1854 proto => 'udp', sport => 67, dport => 68 });
1858 if ($direction eq 'OUT') {
1859 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1860 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1862 if ($ipfilter_ipset) {
1863 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
1865 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1869 sub ruleset_add_group_rule {
1870 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1872 my $group = $rule->{action};
1873 my $group_chain = "GROUP-
$group-$direction";
1874 if(!ruleset_chain_exist($ruleset, $group_chain)){
1875 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1878 if ($direction eq 'OUT' && $rule->{iface_out}) {
1879 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1880 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1881 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1883 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1886 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1889 sub ruleset_generate_vm_rules {
1890 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
1892 my $lc_direction = lc($direction);
1894 my $in_accept = generate_nfqueue($options);
1896 foreach my $rule (@$rules) {
1897 next if $rule->{iface} && $rule->{iface} ne $netid;
1898 next if !$rule->{enable} || $rule->{errors};
1899 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
1901 if ($rule->{type} eq 'group') {
1902 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1903 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
1905 next if $rule->{type} ne $lc_direction;
1907 if ($direction eq 'OUT') {
1908 ruleset_generate_rule($ruleset, $chain, $rule,
1909 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1910 undef, $cluster_conf, $vmfw_conf);
1912 ruleset_generate_rule($ruleset, $chain, $rule,
1913 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1914 undef, $cluster_conf, $vmfw_conf);
1922 sub generate_nfqueue {
1925 if ($options->{ips}) {
1926 my $action = "NFQUEUE
";
1927 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1928 if (defined($3) && defined($1)) {
1929 $action .= " --queue-balance
$1:$3";
1930 } elsif (defined($1)) {
1931 $action .= " --queue-num
$1";
1934 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1941 sub ruleset_generate_vm_ipsrules {
1942 my ($ruleset, $options, $direction, $iface) = @_;
1944 if ($options->{ips} && $direction eq 'IN') {
1945 my $nfqueue = generate_nfqueue($options);
1947 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1948 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1951 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1955 sub generate_venet_rules_direction {
1956 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction, $ipversion) = @_;
1958 my $lc_direction = lc($direction);
1960 my $rules = $vmfw_conf->{rules};
1962 my $options = $vmfw_conf->{options};
1963 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1965 my $chain = "venet0-
$vmid-$direction";
1967 ruleset_create_vm_chain($ruleset, $chain, $options, undef, undef, $direction);
1969 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction, undef, $ipversion);
1974 if ($direction eq 'OUT') {
1975 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1977 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1980 my $accept = generate_nfqueue($options);
1981 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1982 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1984 if ($direction eq 'OUT') {
1985 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1988 iface_in => 'venet0'});
1990 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1993 iface_out => 'venet0'});
1997 sub generate_tap_rules_direction {
1998 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2000 my $lc_direction = lc($direction);
2002 my $rules = $vmfw_conf->{rules};
2004 my $options = $vmfw_conf->{options};
2005 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2007 my $tapchain = "$iface-$direction";
2009 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2010 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name)
2011 if $vmfw_conf->{ipset}->{$ipfilter_name};
2013 # create chain with mac and ip filter
2014 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $ipfilter_ipset, $direction);
2016 if ($options->{enable}) {
2017 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2019 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2024 if ($direction eq 'OUT') {
2025 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2027 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2030 my $accept = generate_nfqueue($options);
2031 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2032 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
2034 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2035 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, 'ACCEPT', $loglevel, $accept_action);
2038 # plug the tap chain to bridge chain
2039 if ($direction eq 'IN') {
2040 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2041 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2043 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2044 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2048 sub enable_host_firewall {
2049 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2051 my $options = $hostfw_conf->{options};
2052 my $cluster_options = $cluster_conf->{options};
2053 my $rules = $hostfw_conf->{rules};
2054 my $cluster_rules = $cluster_conf->{rules};
2056 # host inbound firewall
2057 my $chain = "PVEFW-HOST-IN
";
2058 ruleset_create_chain($ruleset, $chain);
2060 my $loglevel = get_option_log_level($options, "log_level_in
");
2062 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2064 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2065 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $ipversion, $loglevel);
2067 # we use RETURN because we need to check also tap rules
2068 my $accept_action = 'RETURN';
2070 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2072 # add host rules first, so that cluster wide rules can be overwritten
2073 foreach my $rule (@$rules, @$cluster_rules) {
2074 next if !$rule->{enable} || $rule->{errors};
2076 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2079 if ($rule->{type} eq 'group') {
2080 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2081 } elsif ($rule->{type} eq 'in') {
2082 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2083 undef, $cluster_conf, $hostfw_conf);
2087 delete $rule->{iface_in};
2090 # allow standard traffic for management ipset (includes cluster network)
2091 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
");
2092 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2093 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2094 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2095 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2096 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2098 my $localnet = local_network();
2102 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2103 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2104 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2107 # implement input policy
2108 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2109 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
2111 # host outbound firewall
2112 $chain = "PVEFW-HOST-OUT
";
2113 ruleset_create_chain($ruleset, $chain);
2115 $loglevel = get_option_log_level($options, "log_level_out
");
2117 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2119 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2121 # we use RETURN because we may want to check other thigs later
2122 $accept_action = 'RETURN';
2124 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2126 # add host rules first, so that cluster wide rules can be overwritten
2127 foreach my $rule (@$rules, @$cluster_rules) {
2128 next if !$rule->{enable} || $rule->{errors};
2130 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2132 if ($rule->{type} eq 'group') {
2133 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2134 } elsif ($rule->{type} eq 'out') {
2135 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2136 undef, $cluster_conf, $hostfw_conf);
2140 delete $rule->{iface_out};
2143 # allow standard traffic on cluster network
2145 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2146 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2147 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2148 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2150 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2151 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2152 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2155 # implement output policy
2156 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2157 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
2159 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2160 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2163 sub generate_group_rules {
2164 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2166 my $rules = $cluster_conf->{groups}->{$group};
2169 warn "no such security group
'$group'\n";
2170 $rules = []; # create empty chain
2173 my $chain = "GROUP-
${group
}-IN
";
2175 ruleset_create_chain($ruleset, $chain);
2176 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2178 foreach my $rule (@$rules) {
2179 next if $rule->{type} ne 'in';
2180 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2181 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
2184 $chain = "GROUP-
${group
}-OUT
";
2186 ruleset_create_chain($ruleset, $chain);
2187 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2189 foreach my $rule (@$rules) {
2190 next if $rule->{type} ne 'out';
2191 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2192 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2193 # check also other tap rules later
2194 ruleset_generate_rule($ruleset, $chain, $rule,
2195 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
2200 my $valid_netdev_names = {};
2201 for (my $i = 0; $i < $MAX_NETS; $i++) {
2202 $valid_netdev_names->{"net
$i"} = 1;
2206 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2208 my $orig_line = $line;
2212 # we can add single line comments to the end of the rule
2213 if ($line =~ s/#\s*(.*?)\s*$//) {
2214 $rule->{comment} = decode('utf8', $1);
2217 # we can disable a rule when prefixed with '|'
2219 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2221 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2222 die "unable to parse rule
: $line\n";
2224 $rule->{type} = lc($1);
2225 $rule->{action} = $2;
2227 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2228 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2229 $rule->{macro} = $1;
2230 $rule->{action} = $2;
2234 while (length($line)) {
2235 if ($line =~ s/^-i (\S+)\s*//) {
2236 $rule->{iface} = $1;
2240 last if $rule->{type} eq 'group';
2242 if ($line =~ s/^-p (\S+)\s*//) {
2243 $rule->{proto} = $1;
2247 if ($line =~ s/^-dport (\S+)\s*//) {
2248 $rule->{dport} = $1;
2252 if ($line =~ s/^-sport (\S+)\s*//) {
2253 $rule->{sport} = $1;
2256 if ($line =~ s/^-source (\S+)\s*//) {
2257 $rule->{source} = $1;
2260 if ($line =~ s/^-dest (\S+)\s*//) {
2268 die "unable to parse rule parameters
: $line\n" if length($line);
2270 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2271 if ($verbose && $rule->{errors}) {
2272 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2273 foreach my $p (keys %{$rule->{errors}}) {
2274 warn " $p: $rule->{errors
}->{$p}\n";
2281 sub parse_vmfw_option {
2286 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2288 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2291 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2293 $value = $2 ? lc($3) : '';
2294 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2297 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2301 die "can
't parse option '$line'\n"
2304 return ($opt, $value);
2307 sub parse_hostfw_option {
2312 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2314 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2317 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2319 $value = $2 ? lc($3) : '';
2320 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2324 die "can't parse option
'$line'\n"
2327 return ($opt, $value);
2330 sub parse_clusterfw_option {
2335 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2338 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2342 die "can
't parse option '$line'\n"
2345 return ($opt, $value);
2349 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2351 my $alias = lc($cidr);
2352 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2353 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2355 die "no such alias '$cidr'\n" if !$e;;
2357 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2360 sub parse_ip_or_cidr {
2365 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2368 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2372 die "value does not look like a valid IP address or CIDR network\n";
2375 return wantarray ? ($cidr, $ipversion) : $cidr;
2381 # we can add single line comments to the end of the line
2382 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2384 if ($line =~ m/^(\S+)\s(\S+)$/) {
2385 my ($name, $cidr) = ($1, $2);
2388 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2393 ipversion => $ipversion,
2395 $data->{comment} = $comment if $comment;
2402 sub generic_fw_config_parser {
2403 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2408 my $res = $empty_conf;
2410 while (defined(my $line = <$fh>)) {
2411 next if $line =~ m/^#/;
2412 next if $line =~ m/^\s*$/;
2416 my $linenr = $fh->input_line_number();
2417 my $prefix = "$filename (line $linenr)";
2419 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2420 $section = 'options
';
2424 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2425 $section = 'aliases
';
2429 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2430 $section = 'groups
';
2434 die "security group name too long\n" if length($group) > $max_group_name_length;
2435 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2438 ($section, $group, $comment) = undef;
2439 warn "$prefix: $err";
2443 $res->{$section}->{$group} = [];
2444 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2449 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2454 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2459 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2460 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2463 ($section, $group, $comment) = undef;
2464 warn "$prefix: $err";
2468 $res->{$section}->{$group} = [];
2469 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2475 warn "$prefix: skip line - no section\n";
2479 if ($section eq 'options
') {
2482 if ($rule_env eq 'cluster
') {
2483 ($opt, $value) = parse_clusterfw_option($line);
2484 } elsif ($rule_env eq 'host
') {
2485 ($opt, $value) = parse_hostfw_option($line);
2487 ($opt, $value) = parse_vmfw_option($line);
2489 $res->{options}->{$opt} = $value;
2491 warn "$prefix: $@" if $@;
2492 } elsif ($section eq 'aliases
') {
2494 my $data = parse_alias($line);
2495 $res->{aliases}->{lc($data->{name})} = $data;
2497 warn "$prefix: $@" if $@;
2498 } elsif ($section eq 'rules
') {
2500 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2502 warn "$prefix: $err";
2505 push @{$res->{$section}}, $rule;
2506 } elsif ($section eq 'groups
') {
2508 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2510 warn "$prefix: $err";
2513 push @{$res->{$section}->{$group}}, $rule;
2514 } elsif ($section eq 'ipset
') {
2515 # we can add single line comments to the end of the rule
2516 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2518 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2523 if ($nomatch && !$feature_ipset_nomatch) {
2524 $errors->{nomatch} = "nomatch not supported by kernel";
2528 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2529 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2531 $cidr = parse_ip_or_cidr($cidr);
2536 $errors->{cidr} = $err;
2539 my $entry = { cidr => $cidr };
2540 $entry->{nomatch} = 1 if $nomatch;
2541 $entry->{comment} = $comment if $comment;
2542 $entry->{errors} = $errors if $errors;
2544 if ($verbose && $errors) {
2545 warn "$prefix - errors in ipset '$group': $line\n";
2546 foreach my $p (keys %{$errors}) {
2547 warn " $p: $errors->{$p}\n";
2551 push @{$res->{$section}->{$group}}, $entry;
2553 warn "$prefix: skip line - unknown section\n";
2561 sub parse_hostfw_config {
2562 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2564 my $empty_conf = { rules => [], options => {}};
2566 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2569 sub parse_vmfw_config {
2570 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2577 ipset_comments => {},
2580 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2583 sub parse_clusterfw_config {
2584 my ($filename, $fh, $verbose) = @_;
2594 group_comments => {},
2596 ipset_comments => {},
2599 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2603 my ($code, @param) = @_;
2607 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2614 sub read_local_vm_config {
2619 my $vmdata = { openvz => $openvz, qemu => $qemu };
2621 my $vmlist = PVE::Cluster::get_vmlist();
2622 return $vmdata if !$vmlist || !$vmlist->{ids};
2623 my $ids = $vmlist->{ids};
2625 foreach my $vmid (keys %$ids) {
2626 next if !$vmid; # skip VE0
2627 my $d = $ids->{$vmid};
2628 next if !$d->{node} || $d->{node} ne $nodename;
2629 next if !$d->{type};
2630 if ($d->{type} eq 'openvz
') {
2631 if ($have_pve_manager) {
2632 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2633 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2634 $openvz->{$vmid} = $conf;
2637 } elsif ($d->{type} eq 'qemu
') {
2638 if ($have_qemu_server) {
2639 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2640 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2641 $qemu->{$vmid} = $conf;
2650 sub load_vmfw_conf {
2651 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2655 $dir = $pvefw_conf_dir if !defined($dir);
2657 my $filename = "$dir/$vmid.fw";
2658 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2659 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2660 $vmfw_conf->{vmid} = $vmid;
2666 my $format_rules = sub {
2667 my ($rules, $allow_iface) = @_;
2671 foreach my $rule (@$rules) {
2672 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2673 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2674 $raw .= uc($rule->{type});
2675 if ($rule->{macro}) {
2676 $raw .= " $rule->{macro}($rule->{action})";
2678 $raw .= " " . $rule->{action};
2680 if ($allow_iface && $rule->{iface}) {
2681 $raw .= " -i $rule->{iface}";
2684 if ($rule->{type} ne 'group
') {
2685 $raw .= " -source $rule->{source}" if $rule->{source};
2686 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2687 $raw .= " -p $rule->{proto}" if $rule->{proto};
2688 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2689 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2692 $raw .= " # " . encode('utf8
', $rule->{comment})
2693 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2696 die "unknown rule type '$rule->{type
}'";
2703 my $format_options = sub {
2708 $raw .= "[OPTIONS]\n\n";
2709 foreach my $opt (keys %$options) {
2710 $raw .= "$opt: $options->{$opt}\n";
2717 my $format_aliases = sub {
2722 $raw .= "[ALIASES]\n\n";
2723 foreach my $k (keys %$aliases) {
2724 my $e = $aliases->{$k};
2725 $raw .= "$e->{name} $e->{cidr}";
2726 $raw .= " # " . encode('utf8
', $e->{comment})
2727 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2735 my $format_ipsets = sub {
2740 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2741 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2742 my $utf8comment = encode('utf8
', $comment);
2743 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2745 $raw .= "[IPSET $ipset]\n\n";
2747 my $options = $fw_conf->{ipset}->{$ipset};
2750 foreach my $entry (@$options) {
2751 $nethash->{$entry->{cidr}} = $entry;
2754 foreach my $cidr (sort keys %$nethash) {
2755 my $entry = $nethash->{$cidr};
2756 my $line = $entry->{nomatch} ? '!' : '';
2757 $line .= $entry->{cidr};
2758 $line .= " # " . encode('utf8
', $entry->{comment})
2759 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2769 sub save_vmfw_conf {
2770 my ($vmid, $vmfw_conf) = @_;
2774 my $options = $vmfw_conf->{options};
2775 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2777 my $aliases = $vmfw_conf->{aliases};
2778 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2780 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2782 my $rules = $vmfw_conf->{rules} || [];
2783 if ($rules && scalar(@$rules)) {
2784 $raw .= "[RULES]\n\n";
2785 $raw .= &$format_rules($rules, 1);
2789 mkdir $pvefw_conf_dir;
2791 my $filename = "$pvefw_conf_dir/$vmid.fw";
2792 PVE::Tools::file_set_contents($filename, $raw);
2795 sub read_vm_firewall_configs {
2796 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2798 my $vmfw_configs = {};
2800 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2801 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2802 next if !$vmfw_conf->{options}; # skip if file does not exists
2803 $vmfw_configs->{$vmid} = $vmfw_conf;
2805 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2806 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2807 next if !$vmfw_conf->{options}; # skip if file does not exists
2808 $vmfw_configs->{$vmid} = $vmfw_conf;
2811 return $vmfw_configs;
2814 sub get_option_log_level {
2815 my ($options, $k) = @_;
2817 my $v = $options->{$k};
2818 $v = $default_log_level if !defined($v);
2820 return undef if $v eq '' || $v eq 'nolog
';
2822 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2824 return $v if ($v >= 0) && ($v <= 7);
2826 warn "unknown log level ($k = '$v')\n";
2831 sub generate_std_chains {
2832 my ($ruleset, $options, $ipversion) = @_;
2834 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2836 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2840 if ($ipversion == 4) {
2841 # same as shorewall smurflog.
2842 $chain = 'PVEFW-smurflog
';
2843 $std_chains->{$chain} = [];
2845 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2846 push @{$std_chains->{$chain}}, "-j DROP";
2849 # same as shorewall logflags action.
2850 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2851 $chain = 'PVEFW-logflags
';
2852 $std_chains->{$chain} = [];
2854 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2855 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2856 push @{$std_chains->{$chain}}, "-j DROP";
2858 foreach my $chain (keys %$std_chains) {
2859 ruleset_create_chain($ruleset, $chain);
2860 foreach my $rule (@{$std_chains->{$chain}}) {
2862 ruleset_generate_rule($ruleset, $chain, $rule);
2864 ruleset_addrule($ruleset, $chain, $rule);
2870 sub generate_ipset_chains {
2871 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2873 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2874 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2875 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2879 sub generate_ipset {
2880 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2882 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2884 $ipset_ruleset->{$name} = ["create $name list:set size 4"];
2888 foreach my $entry (@$options) {
2889 next if $entry->{errors}; # skip entries with errors
2891 my ($cidr, $ipversion);
2892 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2893 ($cidr, $ipversion) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2895 ($cidr, $ipversion) = parse_ip_or_cidr($entry->{cidr});
2897 #http://backreference.org/2013/03/01/ipv6-address-normalization/
2898 if ($ipversion == 6) {
2899 my $ipv6 = inet_pton(AF_INET6, lc($cidr));
2900 $cidr = inet_ntop(AF_INET6, $ipv6);
2906 $nethash->{$ipversion}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2911 foreach my $ipversion (sort keys %$nethash) {
2912 my $data = $nethash->{$ipversion};
2913 my $subname = "$name-v$ipversion";
2915 my $hashsize = scalar(@$options);
2916 if ($hashsize <= 64) {
2919 $hashsize = round_powerof2($hashsize);
2922 my $family = $ipversion == "6" ? "inet6" : "inet";
2924 $ipset_ruleset->{$subname} = ["create $subname hash:net family $family hashsize $hashsize maxelem $hashsize"];
2926 foreach my $cidr (sort keys %$data) {
2927 my $entry = $data->{$cidr};
2929 my $cmd = "add $subname $cidr";
2930 if ($entry->{nomatch}) {
2931 if ($feature_ipset_nomatch) {
2932 push @{$ipset_ruleset->{$subname}}, "$cmd nomatch";
2934 warn "ignore !$cidr - nomatch not supported by kernel\n";
2937 push @{$ipset_ruleset->{$subname}}, $cmd;
2941 push @{$ipset_ruleset->{$name}}, "add $name $subname";
2945 sub round_powerof2 {
2949 $int |= $int >> $_ foreach (1,2,4,8,16);
2953 sub load_clusterfw_conf {
2954 my ($filename, $verbose) = @_;
2956 $filename = $clusterfw_conf_filename if !defined($filename);
2958 my $cluster_conf = {};
2959 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2960 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
2963 return $cluster_conf;
2966 sub save_clusterfw_conf {
2967 my ($cluster_conf) = @_;
2971 my $options = $cluster_conf->{options};
2972 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2974 my $aliases = $cluster_conf->{aliases};
2975 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2977 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
2979 my $rules = $cluster_conf->{rules};
2980 if ($rules && scalar(@$rules)) {
2981 $raw .= "[RULES]\n\n";
2982 $raw .= &$format_rules($rules, 1);
2986 if ($cluster_conf->{groups}) {
2987 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2988 my $rules = $cluster_conf->{groups}->{$group};
2989 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2990 my $utf8comment = encode('utf8
', $comment);
2991 $raw .= "[group $group] # $utf8comment\n\n";
2993 $raw .= "[group $group]\n\n";
2996 $raw .= &$format_rules($rules, 0);
3001 mkdir $pvefw_conf_dir;
3002 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3005 sub load_hostfw_conf {
3006 my ($cluster_conf, $filename, $verbose) = @_;
3008 $filename = $hostfw_conf_filename if !defined($filename);
3010 my $hostfw_conf = {};
3011 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3012 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3014 return $hostfw_conf;
3017 sub save_hostfw_conf {
3018 my ($hostfw_conf) = @_;
3022 my $options = $hostfw_conf->{options};
3023 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3025 my $rules = $hostfw_conf->{rules};
3026 if ($rules && scalar(@$rules)) {
3027 $raw .= "[RULES]\n\n";
3028 $raw .= &$format_rules($rules, 1);
3032 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3036 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3040 if ($vmdata) { # test mode
3041 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3042 my $filename = "$testdir/cluster.fw";
3043 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3045 $filename = "$testdir/host.fw";
3046 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3048 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3049 } else { # normal operation
3050 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3052 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3054 $vmdata = read_local_vm_config();
3055 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3058 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3059 my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3061 return ($ruleset, $ipset_ruleset, $rulesetv6);
3064 sub compile_iptables_filter {
3065 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3067 $cluster_conf->{ipset}->{venet0} = [];
3068 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
3071 if ($cluster_conf->{aliases}->{local_network}) {
3072 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3074 $localnet = local_network() || '127.0.0.0/8';
3075 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
3078 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3080 return ({}, {}) if !$cluster_conf->{options}->{enable};
3084 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3085 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3087 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3089 my $hostfw_options = $hostfw_conf->{options} || {};
3091 # fixme: what log level should we use here?
3092 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3094 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3097 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
3098 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3099 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3101 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3102 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $ipversion, $loglevel);
3104 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3106 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3107 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3109 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
3110 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $ipversion, $loglevel);
3112 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3114 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3116 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3118 my $ipset_ruleset = {};
3120 # currently pveproxy don't works with ipv6
, so let
's generate host fw ipv4 only for the moment
3121 if ($hostfw_enable && ($ipversion == 4)) {
3122 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3123 warn $@ if $@; # just to be sure - should not happen
3126 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3128 # generate firewall rules for QEMU VMs
3129 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3131 my $conf = $vmdata->{qemu}->{$vmid};
3132 my $vmfw_conf = $vmfw_configs->{$vmid};
3133 return if !$vmfw_conf;
3135 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3137 foreach my $netid (keys %$conf) {
3138 next if $netid !~ m/^net(\d+)$/;
3139 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3140 next if !$net->{firewall};
3141 my $iface = "tap${vmid}i$1";
3143 my $macaddr = $net->{macaddr};
3144 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3145 $vmfw_conf, $vmid, 'IN
', $ipversion);
3146 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3147 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3150 warn $@ if $@; # just to be sure - should not happen
3153 # generate firewall rules for OpenVZ containers
3154 foreach my $vmid (keys %{$vmdata->{openvz}}) {
3156 my $conf = $vmdata->{openvz}->{$vmid};
3158 my $vmfw_conf = $vmfw_configs->{$vmid};
3159 return if !$vmfw_conf;
3161 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3163 if ($vmfw_conf->{options}->{enable}) {
3164 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
3165 my $ip = $conf->{ip_address}->{value};
3170 foreach my $singleip (split(',', $ip)) {
3171 my $singleip_ver = parse_address_list($singleip); # make sure we have a valid $ip list
3172 push @{$cluster_conf->{ipset}->{venet0}}, { cidr => $singleip };
3173 push @ips, $singleip if $singleip_ver == $ipversion;
3177 my $ip_list = join(',', @ips);
3178 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'IN
', $ipversion);
3179 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'OUT
', $ipversion);
3184 if ($conf->{netif} && $conf->{netif}->{value}) {
3185 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
3186 foreach my $netid (keys %$netif) {
3187 my $d = $netif->{$netid};
3188 my $bridge = $d->{bridge};
3189 next if !$bridge || $bridge !~ m/^vmbr\d+(v(\d+))?f$/; # firewall enabled ?
3190 my $macaddr = $d->{mac};
3191 my $iface = $d->{host_ifname};
3192 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3193 $vmfw_conf, $vmid, 'IN
', $ipversion);
3194 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3195 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3199 warn $@ if $@; # just to be sure - should not happen
3202 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3203 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3206 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
3208 return ($ruleset, $ipset_ruleset);
3211 sub get_ruleset_status {
3212 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3214 my $statushash = {};
3216 foreach my $chain (sort keys %$ruleset) {
3217 my $sig = &$digest_fn($ruleset->{$chain});
3219 $statushash->{$chain}->{sig} = $sig;
3221 my $oldsig = $active_chains->{$chain};
3222 if (!defined($oldsig)) {
3223 $statushash->{$chain}->{action} = 'create
';
3225 if ($oldsig eq $sig) {
3226 $statushash->{$chain}->{action} = 'exists';
3228 $statushash->{$chain}->{action} = 'update
';
3231 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3232 foreach my $cmd (@{$ruleset->{$chain}}) {
3233 print "\t$cmd\n" if $verbose;
3237 foreach my $chain (sort keys %$active_chains) {
3238 if (!defined($ruleset->{$chain})) {
3239 my $sig = $active_chains->{$chain};
3240 $statushash->{$chain}->{action} = 'delete';
3241 $statushash->{$chain}->{sig} = $sig;
3242 print "delete $chain ($sig)\n" if $verbose;
3249 sub print_sig_rule {
3250 my ($chain, $sig) = @_;
3252 # We just use this to store a SHA1 checksum used to detect changes
3253 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3256 sub get_ruleset_cmdlist {
3257 my ($ruleset, $verbose, $iptablescmd) = @_;
3259 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3261 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3262 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3264 # create missing chains first
3265 foreach my $chain (sort keys %$ruleset) {
3266 my $stat = $statushash->{$chain};
3267 die "internal error" if !$stat;
3268 next if $stat->{action} ne 'create
';
3270 $cmdlist .= ":$chain - [0:0]\n";
3273 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3274 my $chain = "PVEFW-$h";
3275 if ($ruleset->{$chain} && !$hooks->{$h}) {
3276 $cmdlist .= "-A $h -j $chain\n";
3280 foreach my $chain (sort keys %$ruleset) {
3281 my $stat = $statushash->{$chain};
3282 die "internal error" if !$stat;
3284 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3285 $cmdlist .= "-F $chain\n";
3286 foreach my $cmd (@{$ruleset->{$chain}}) {
3287 $cmdlist .= "$cmd\n";
3289 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3290 } elsif ($stat->{action
} eq 'delete') {
3291 die "internal error"; # this should not happen
3292 } elsif ($stat->{action
} eq 'exists') {
3295 die "internal error - unknown status '$stat->{action}'";
3299 foreach my $chain (keys %$statushash) {
3300 next if $statushash->{$chain}->{action
} ne 'delete';
3301 $cmdlist .= "-F $chain\n";
3303 foreach my $chain (keys %$statushash) {
3304 next if $statushash->{$chain}->{action
} ne 'delete';
3305 next if $chain eq 'PVEFW-INPUT';
3306 next if $chain eq 'PVEFW-OUTPUT';
3307 next if $chain eq 'PVEFW-FORWARD';
3308 $cmdlist .= "-X $chain\n";
3311 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3313 $cmdlist .= "COMMIT\n";
3315 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3318 sub get_ipset_cmdlist
{
3319 my ($ruleset, $verbose) = @_;
3323 my $delete_cmdlist = "";
3325 my $active_chains = ipset_get_chains
();
3326 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3328 # remove stale _swap chains
3329 foreach my $chain (keys %$active_chains) {
3330 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3331 $cmdlist .= "destroy $chain\n";
3335 foreach my $chain (sort keys %$ruleset) {
3336 my $stat = $statushash->{$chain};
3337 die "internal error" if !$stat;
3339 if ($stat->{action
} eq 'create') {
3340 foreach my $cmd (@{$ruleset->{$chain}}) {
3341 $cmdlist .= "$cmd\n";
3346 foreach my $chain (sort keys %$ruleset) {
3347 my $stat = $statushash->{$chain};
3348 die "internal error" if !$stat;
3350 if ($stat->{action
} eq 'update') {
3351 my $chain_swap = $chain."_swap";
3353 foreach my $cmd (@{$ruleset->{$chain}}) {
3354 $cmd =~ s/$chain/$chain_swap/;
3355 $cmdlist .= "$cmd\n";
3357 $cmdlist .= "swap $chain_swap $chain\n";
3358 $cmdlist .= "flush $chain_swap\n";
3359 $cmdlist .= "destroy $chain_swap\n";
3363 foreach my $chain (sort keys %$statushash) {
3364 next if $statushash->{$chain}->{action
} ne 'delete';
3366 $delete_cmdlist .= "flush $chain\n";
3367 $delete_cmdlist .= "destroy $chain\n";
3370 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3372 return ($cmdlist, $delete_cmdlist, $changes);
3376 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3378 enable_bridge_firewall
();
3380 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3381 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3383 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3384 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3387 if ($ipset_changes) {
3388 print "ipset changes:\n";
3389 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3390 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3394 print "iptables changes:\n";
3399 print "ip6tables changes:\n";
3404 ipset_restore_cmdlist
($ipset_create_cmdlist);
3406 iptables_restore_cmdlist
($cmdlist);
3407 ip6tables_restore_cmdlist
($cmdlistv6);
3409 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3411 # test: re-read status and check if everything is up to date
3412 my $active_chains = iptables_get_chains
();
3413 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3416 foreach my $chain (sort keys %$ruleset) {
3417 my $stat = $statushash->{$chain};
3418 if ($stat->{action
} ne 'exists') {
3419 warn "unable to update chain '$chain'\n";
3424 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3425 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3427 foreach my $chain (sort keys %$rulesetv6) {
3428 my $stat = $statushashv6->{$chain};
3429 if ($stat->{action
} ne 'exists') {
3430 warn "unable to update chain '$chain'\n";
3435 die "unable to apply firewall changes\n" if $errors;
3437 update_nf_conntrack_max
($hostfw_conf);
3439 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3443 sub update_nf_conntrack_max
{
3444 my ($hostfw_conf) = @_;
3446 my $max = 65536; # reasonable default
3448 my $options = $hostfw_conf->{options
} || {};
3450 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3451 $max = $options->{nf_conntrack_max
};
3452 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3455 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3456 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3458 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3460 if ($current != $max) {
3461 my $hashsize = int($max/4);
3462 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3463 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3467 sub update_nf_conntrack_tcp_timeout_established
{
3468 my ($hostfw_conf) = @_;
3470 my $options = $hostfw_conf->{options
} || {};
3472 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3474 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3477 sub remove_pvefw_chains
{
3479 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3480 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3481 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3485 sub remove_pvefw_chains_iptables
{
3486 my ($iptablescmd) = @_;
3488 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3489 my $cmdlist = "*filter\n";
3491 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3493 $cmdlist .= "-D $h -j PVEFW-$h\n";
3497 foreach my $chain (keys %$chash) {
3498 $cmdlist .= "-F $chain\n";
3501 foreach my $chain (keys %$chash) {
3502 $cmdlist .= "-X $chain\n";
3504 $cmdlist .= "COMMIT\n";
3506 if($iptablescmd eq "ip6tables") {
3507 ip6tables_restore_cmdlist
($cmdlist);
3509 iptables_restore_cmdlist
($cmdlist);
3513 sub remove_pvefw_chains_ipset
{
3515 my $ipset_chains = ipset_get_chains
();
3517 my $sub_cmdlist = "";
3520 foreach my $chain (keys %$ipset_chains) {
3521 if ($chain =~ m/^PVEFW-\S+\-(v4|v6)$/) {
3522 $sub_cmdlist .= "flush $chain\n";
3523 $sub_cmdlist .= "destroy $chain\n";
3525 $cmdlist .= "flush $chain\n";
3526 $cmdlist .= "destroy $chain\n";
3530 $cmdlist .= $sub_cmdlist;
3532 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3536 my $cluster_conf = load_clusterfw_conf
();
3537 my $cluster_options = $cluster_conf->{options
};
3538 my $enable = $cluster_options->{enable
};
3542 # load required modules here
3548 my $cluster_conf = load_clusterfw_conf
();
3549 my $cluster_options = $cluster_conf->{options
};
3551 if (!$cluster_options->{enable
}) {
3552 PVE
::Firewall
::remove_pvefw_chains
();
3556 my $hostfw_conf = load_hostfw_conf
();
3558 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3560 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);