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",
660 #does smurf attack works with ipv6, as broadcast not exist ???
662 # same as shorewall smurfs action
663 # Filter packets for smurfs (packets with a broadcast address as the source).
664 #"-s 0.0.0.0/32 -j RETURN",
665 #"-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
666 #"-s 224.0.0.0/4 -g PVEFW-smurflog",
670 # iptables -p icmp -h
671 my $icmp_type_names = {
674 'destination-unreachable' => 1,
675 'network-unreachable' => 1,
676 'host-unreachable' => 1,
677 'protocol-unreachable' => 1,
678 'port-unreachable' => 1,
679 'fragmentation-needed' => 1,
680 'source-route-failed' => 1,
681 'network-unknown' => 1,
683 'network-prohibited' => 1,
684 'host-prohibited' => 1,
685 'TOS-network-unreachable' => 1,
686 'TOS-host-unreachable' => 1,
687 'communication-prohibited' => 1,
688 'host-precedence-violation' => 1,
689 'precedence-cutoff' => 1,
690 'source-quench' => 1,
692 'network-redirect' => 1,
693 'host-redirect' => 1,
694 'TOS-network-redirect' => 1,
695 'TOS-host-redirect' => 1,
697 'router-advertisement' => 1,
698 'router-solicitation' => 1,
699 'time-exceeded' => 1,
700 'ttl-zero-during-transit' => 1,
701 'ttl-zero-during-reassembly' => 1,
702 'parameter-problem' => 1,
703 'ip-header-bad' => 1,
704 'required-option-missing' => 1,
705 'timestamp-request' => 1,
706 'timestamp-reply' => 1,
707 'address-mask-request' => 1,
708 'address-mask-reply' => 1,
711 # ip6tables -p icmpv6 -h
713 my $icmpv6_type_names = {
715 'destination-unreachable' => 1,
717 'communication-prohibited' => 1,
718 'address-unreachable' => 1,
719 'port-unreachable' => 1,
720 'packet-too-big' => 1,
721 'time-exceeded' => 1,
722 'ttl-zero-during-transit' => 1,
723 'ttl-zero-during-reassembly' => 1,
724 'parameter-problem' => 1,
726 'unknown-header-type' => 1,
727 'unknown-option' => 1,
730 'router-solicitation' => 1,
731 'router-advertisement' => 1,
732 'neighbour-solicitation' => 1,
733 'neighbour-advertisement' => 1,
737 sub init_firewall_macros
{
739 $pve_fw_parsed_macros = {};
741 foreach my $k (keys %$pve_fw_macros) {
742 my $lc_name = lc($k);
743 my $macro = $pve_fw_macros->{$k};
744 if (!ref($macro->[0])) {
745 $pve_fw_macro_descr->{$k} = shift @$macro;
747 $pve_fw_preferred_macro_names->{$lc_name} = $k;
748 $pve_fw_parsed_macros->{$k} = $macro;
752 init_firewall_macros
();
755 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
760 sub get_etc_services
{
762 return $etc_services if $etc_services;
764 my $filename = "/etc/services";
766 my $fh = IO
::File-
>new($filename, O_RDONLY
);
768 warn "unable to read '$filename' - $!\n";
774 while (my $line = <$fh>) {
776 next if $line =~m/^#/;
777 next if ($line =~m/^\s*$/);
779 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
780 $services->{byid
}->{$2}->{name
} = $1;
781 $services->{byid
}->{$2}->{port
} = $2;
782 $services->{byid
}->{$2}->{$3} = 1;
783 $services->{byname
}->{$1} = $services->{byid
}->{$2};
789 $etc_services = $services;
792 return $etc_services;
797 sub get_etc_protocols
{
798 return $etc_protocols if $etc_protocols;
800 my $filename = "/etc/protocols";
802 my $fh = IO
::File-
>new($filename, O_RDONLY
);
804 warn "unable to read '$filename' - $!\n";
810 while (my $line = <$fh>) {
812 next if $line =~m/^#/;
813 next if ($line =~m/^\s*$/);
815 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
816 $protocols->{byid
}->{$2}->{name
} = $1;
817 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
823 # add special case for ICMP v6
824 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
825 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
827 $etc_protocols = $protocols;
829 return $etc_protocols;
832 my $ipv4_mask_hash_localnet = {
834 '255.255.128.0' => 17,
835 '255.255.192.0' => 18,
836 '255.255.224.0' => 19,
837 '255.255.240.0' => 20,
838 '255.255.248.0' => 21,
839 '255.255.252.0' => 22,
840 '255.255.254.0' => 23,
841 '255.255.255.0' => 24,
842 '255.255.255.128' => 25,
843 '255.255.255.192' => 26,
844 '255.255.255.224' => 27,
845 '255.255.255.240' => 28,
846 '255.255.255.248' => 29,
847 '255.255.255.252' => 30,
853 my ($new_value) = @_;
855 $__local_network = $new_value if defined($new_value);
857 return $__local_network if defined($__local_network);
860 my $nodename = PVE
::INotify
::nodename
();
862 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
864 my $testip = Net
::IP-
>new($ip);
866 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
867 foreach my $entry (@$routes) {
868 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
869 next if !defined($mask);
870 return if $mask eq '0.0.0.0';
871 my $cidr = "$entry->{dest}/$mask";
872 my $testnet = Net
::IP-
>new($cidr);
873 if ($testnet->overlaps($testip)) {
874 $__local_network = $cidr;
881 return $__local_network;
884 # ipset names are limited to 31 characters,
885 # and we use '-v4' or '-v6' to indicate IP versions,
886 # and we use '_swap' suffix for atomic update,
887 # for example PVEFW-${VMID}-${ipset_name}_swap
889 my $max_iptables_ipset_name_length = 31 - length("_swap") - length("-v4");
891 sub compute_ipset_chain_name
{
892 my ($vmid, $ipset_name) = @_;
894 $vmid = 0 if !defined($vmid);
896 my $id = "$vmid-${ipset_name}";
898 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
899 $id = PVE
::Tools
::fnv31a_hex
($id);
905 sub compute_ipfilter_ipset_name
{
908 return "ipfilter-$iface";
911 sub parse_address_list
{
914 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
915 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
919 if ($str =~ m/^${ip_alias_pattern}$/) {
920 die "alias name too long\n" if length($str) > $max_alias_name_length;
928 foreach my $elem (split(/,/, $str)) {
930 my $ip = Net
::IP-
>new($elem);
932 my $err = Net
::IP
::Error
();
933 die "invalid IP address: $err\n";
935 $iprange = 1 if $elem =~ m/-/;
937 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
939 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
940 if $ipversion && ($new_ipversion != $ipversion);
942 $ipversion = $new_ipversion;
945 die "you can't use a range in a list\n" if $iprange && $count > 1;
950 sub parse_port_name_number_or_range
{
953 my $services = PVE
::Firewall
::get_etc_services
();
957 foreach my $item (split(/,/, $str)) {
959 if ($item =~ m/^(\d+):(\d+)$/) {
960 my ($port1, $port2) = ($1, $2);
961 die "invalid port '$port1'\n" if $port1 > 65535;
962 die "invalid port '$port2'\n" if $port2 > 65535;
963 } elsif ($item =~ m/^(\d+)$/) {
965 die "invalid port '$port'\n" if $port > 65535;
967 if ($icmp_type_names->{$item}) {
969 } elsif ($icmpv6_type_names->{$item}) {
972 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
977 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
982 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
983 sub pve_fw_verify_port_spec
{
986 parse_port_name_number_or_range
($portstr);
991 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
992 sub pve_fw_verify_addr_spec
{
995 parse_address_list
($list);
1000 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1001 sub pve_fw_verify_protocol_spec
{
1004 my $protocols = get_etc_protocols
();
1006 die "unknown protocol '$proto'\n" if $proto &&
1007 !(defined($protocols->{byname
}->{$proto}) ||
1008 defined($protocols->{byid
}->{$proto}));
1014 # helper function for API
1016 sub copy_opject_with_digest
{
1019 my $sha = Digest
::SHA-
>new('sha1');
1022 foreach my $k (sort keys %$object) {
1023 my $v = $object->{$k};
1024 next if !defined($v);
1026 $sha->add($k, ':', $v, "\n");
1029 my $digest = $sha->hexdigest;
1031 $res->{digest
} = $digest;
1033 return wantarray ?
($res, $digest) : $res;
1036 sub copy_list_with_digest
{
1039 my $sha = Digest
::SHA-
>new('sha1');
1042 foreach my $entry (@$list) {
1044 foreach my $k (sort keys %$entry) {
1045 my $v = $entry->{$k};
1046 next if !defined($v);
1048 # Note: digest ignores refs ($rule->{errors})
1049 $sha->add($k, ':', $v, "\n") if !ref($v); ;
1054 my $digest = $sha->hexdigest;
1056 foreach my $entry (@$res) {
1057 $entry->{digest
} = $digest;
1060 return wantarray ?
($res, $digest) : $res;
1063 my $rule_properties = {
1065 description
=> "Update rule at position <pos>.",
1070 digest
=> get_standard_option
('pve-config-digest'),
1074 enum
=> ['in', 'out', 'group'],
1077 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1080 pattern
=> $security_group_name_pattern,
1089 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
1091 type
=> 'string', format
=> 'pve-fw-addr-spec',
1095 type
=> 'string', format
=> 'pve-fw-addr-spec',
1099 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1107 type
=> 'string', format
=> 'pve-fw-port-spec',
1111 type
=> 'string', format
=> 'pve-fw-port-spec',
1120 sub add_rule_properties
{
1121 my ($properties) = @_;
1123 foreach my $k (keys %$rule_properties) {
1124 my $h = $rule_properties->{$k};
1125 # copy data, so that we can modify later without side effects
1126 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1132 sub delete_rule_properties
{
1133 my ($rule, $delete_str) = @_;
1135 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1136 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1137 if !defined($rule_properties->{$opt});
1138 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1139 if $opt eq 'type' || $opt eq 'action';
1140 delete $rule->{$opt};
1146 my $apply_macro = sub {
1147 my ($macro_name, $param, $verify) = @_;
1149 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1150 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1154 foreach my $templ (@$macro_rules) {
1156 my $param_used = {};
1157 foreach my $k (keys %$templ) {
1158 my $v = $templ->{$k};
1159 if ($v eq 'PARAM') {
1161 $param_used->{$k} = 1;
1162 } elsif ($v eq 'DEST') {
1163 $v = $param->{dest
};
1164 $param_used->{dest
} = 1;
1165 } elsif ($v eq 'SOURCE') {
1166 $v = $param->{source
};
1167 $param_used->{source
} = 1;
1171 my $msg = "missing parameter '$k' in macro '$macro_name'";
1172 raise_param_exc
({ macro => $msg }) if $verify;
1177 foreach my $k (keys %$param) {
1178 next if $k eq 'macro';
1179 next if !defined($param->{$k});
1180 next if $param_used->{$k};
1181 if (defined($rule->{$k})) {
1182 if ($rule->{$k} ne $param->{$k}) {
1183 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1184 raise_param_exc
({ $k => $msg }) if $verify;
1188 $rule->{$k} = $param->{$k};
1191 push @$rules, $rule;
1197 my $rule_env_iface_lookup = {
1206 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1208 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1210 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1211 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1213 my $errors = $rule->{errors
} || {};
1215 my $error_count = 0;
1217 my $add_error = sub {
1218 my ($param, $msg) = @_;
1220 raise_param_exc
({ $param => $msg }) if !$noerr;
1222 $errors->{$param} = $msg if !$errors->{$param};
1225 my $check_ipset_or_alias_property = sub {
1226 my ($name, $expected_ipversion) = @_;
1228 if (my $value = $rule->{$name}) {
1229 if ($value =~ m/^\+/) {
1230 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1231 &$add_error($name, "no such ipset '$1'")
1232 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1235 &$add_error($name, "invalid ipset name '$value'");
1237 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1238 my $alias = lc($value);
1239 &$add_error($name, "no such alias '$value'")
1240 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1242 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1243 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1245 die "detected mixed ipv4/ipv6 adresses in rule\n"
1246 if $expected_ipversion && ($expected_ipversion != $e->{ipversion
});
1251 my $type = $rule->{type
};
1252 my $action = $rule->{action
};
1254 &$add_error('type', "missing property") if !$type;
1255 &$add_error('action', "missing property") if !$action;
1258 if ($type eq 'in' || $type eq 'out') {
1259 &$add_error('action', "unknown action '$action'")
1260 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1261 } elsif ($type eq 'group') {
1262 &$add_error('type', "security groups not allowed")
1264 &$add_error('action', "invalid characters in security group name")
1265 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1267 &$add_error('type', "unknown rule type '$type'");
1271 if ($rule->{iface
}) {
1272 &$add_error('type', "parameter -i not allowed for this rule type")
1274 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1275 &$add_error('iface', $@) if $@;
1276 if ($rule_env eq 'vm') {
1277 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1278 if $rule->{iface
} !~ m/^net(\d+)$/;
1279 } elsif ($rule_env eq 'ct') {
1280 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1281 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1285 if ($rule->{macro}) {
1286 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1287 $rule->{macro} = $preferred_name;
1289 &$add_error('macro', "unknown macro '$rule->{macro}'");
1294 my $set_ip_version = sub {
1297 die "detected mixed ipv4/ipv6 adresses in rule\n"
1298 if $ipversion && ($vers != $ipversion);
1303 if ($rule->{proto
}) {
1304 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1305 &$add_error('proto', $@) if $@;
1306 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1307 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1310 if ($rule->{dport
}) {
1311 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1312 &$add_error('dport', $@) if $@;
1313 &$add_error('proto', "missing property - 'dport' requires this property")
1317 if ($rule->{sport
}) {
1318 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1319 &$add_error('sport', $@) if $@;
1320 &$add_error('proto', "missing property - 'sport' requires this property")
1324 if ($rule->{source
}) {
1326 my $source_ipversion = parse_address_list
($rule->{source
});
1327 &$set_ip_version($source_ipversion);
1329 &$add_error('source', $@) if $@;
1330 &$check_ipset_or_alias_property('source', $ipversion);
1333 if ($rule->{dest
}) {
1335 my $dest_ipversion = parse_address_list
($rule->{dest
});
1336 &$set_ip_version($dest_ipversion);
1338 &$add_error('dest', $@) if $@;
1339 &$check_ipset_or_alias_property('dest', $ipversion);
1342 if ($rule->{macro} && !$error_count) {
1343 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1345 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1346 my $eh = $err->{errors
};
1347 foreach my $p (keys %$eh) {
1348 &$add_error($p, $eh->{$p});
1351 &$add_error('macro', "$err");
1356 $rule->{errors
} = $errors if $error_count;
1357 $rule->{ipversion
} = $ipversion if $ipversion;
1362 sub copy_rule_data
{
1363 my ($rule, $param) = @_;
1365 foreach my $k (keys %$rule_properties) {
1366 if (defined(my $v = $param->{$k})) {
1367 if ($v eq '' || $v eq '-') {
1378 sub rules_modify_permissions
{
1379 my ($rule_env) = @_;
1381 if ($rule_env eq 'host') {
1383 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1385 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1387 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1389 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1391 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1398 sub rules_audit_permissions
{
1399 my ($rule_env) = @_;
1401 if ($rule_env eq 'host') {
1403 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1405 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1407 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1409 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1411 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1419 my $bridge_firewall_enabled = 0;
1421 sub enable_bridge_firewall
{
1423 return if $bridge_firewall_enabled; # only once
1425 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1426 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1428 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1429 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1431 $bridge_firewall_enabled = 1;
1434 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1436 sub iptables_restore_cmdlist
{
1439 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1442 sub ip6tables_restore_cmdlist
{
1445 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist);
1448 sub ipset_restore_cmdlist
{
1451 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1454 sub iptables_get_chains
{
1455 my ($iptablescmd) = @_;
1457 $iptablescmd = "iptables" if !$iptablescmd;
1461 # check what chains we want to track
1462 my $is_pvefw_chain = sub {
1465 return 1 if $name =~ m/^PVEFW-\S+$/;
1467 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1469 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1471 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1473 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1474 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1486 return if $line =~ m/^#/;
1487 return if $line =~ m/^\s*$/;
1489 if ($line =~ m/^\*(\S+)$/) {
1494 return if $table ne 'filter';
1496 if ($line =~ m/^:(\S+)\s/) {
1498 return if !&$is_pvefw_chain($chain);
1499 $res->{$chain} = "unknown";
1500 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1501 my ($chain, $sig) = ($1, $2);
1502 return if !&$is_pvefw_chain($chain);
1503 $res->{$chain} = $sig;
1504 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1507 # simply ignore the rest
1512 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1514 return wantarray ?
($res, $hooks) : $res;
1517 sub iptables_chain_digest
{
1519 my $digest = Digest
::SHA-
>new('sha1');
1520 foreach my $rule (@$rules) { # order is important
1521 $digest->add($rule);
1523 return $digest->b64digest;
1526 sub ipset_chain_digest
{
1529 my $digest = Digest
::SHA-
>new('sha1');
1530 foreach my $rule (sort @$rules) { # note: sorted
1531 $digest->add($rule);
1533 return $digest->b64digest;
1536 sub ipset_get_chains
{
1544 return if $line =~ m/^#/;
1545 return if $line =~ m/^\s*$/;
1546 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1548 $line =~ s/\s+$//; # delete trailing white space
1549 push @{$chains->{$chain}}, $line;
1551 # simply ignore the rest
1556 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1558 # compute digest for each chain
1559 foreach my $chain (keys %$chains) {
1560 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1566 sub ruleset_generate_cmdstr
{
1567 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1569 return if defined($rule->{enable
}) && !$rule->{enable
};
1570 return if $rule->{errors
};
1572 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1574 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1575 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1579 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1580 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1582 my $source = $rule->{source
};
1583 my $dest = $rule->{dest
};
1586 if ($source =~ m/^\+/) {
1587 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1589 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1590 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1591 push @cmd, "-m set --match-set ${ipset_chain} src";
1592 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1593 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1594 push @cmd, "-m set --match-set ${ipset_chain} src";
1596 die "no such ipset '$name'\n";
1599 die "invalid security group name '$source'\n";
1601 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1602 my $alias = lc($source);
1603 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1604 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1605 die "no such alias '$source'\n" if !$e;
1606 push @cmd, "-s $e->{cidr}";
1607 } elsif ($source =~ m/\-/){
1608 push @cmd, "-m iprange --src-range $source";
1610 push @cmd, "-s $source";
1615 if ($dest =~ m/^\+/) {
1616 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1618 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1619 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1620 push @cmd, "-m set --match-set ${ipset_chain} dst";
1621 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1622 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1623 push @cmd, "-m set --match-set ${ipset_chain} dst";
1625 die "no such ipset '$name'\n";
1628 die "invalid security group name '$dest'\n";
1630 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1631 my $alias = lc($dest);
1632 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1633 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1634 die "no such alias '$dest'\n" if !$e;
1635 push @cmd, "-d $e->{cidr}";
1636 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1637 push @cmd, "-m iprange --dst-range $dest";
1639 push @cmd, "-d $dest";
1643 if ($rule->{proto
}) {
1644 push @cmd, "-p $rule->{proto}";
1647 $multiport++ if $nbdport > 1;
1648 $multiport++ if $nbsport > 1;
1650 push @cmd, "--match multiport" if $multiport;
1652 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1653 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1655 if ($rule->{dport
}) {
1656 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1657 # Note: we use dport to store --icmp-type
1658 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1659 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1660 } elsif ($rule->{proto
} && $rule->{proto
} eq 'icmpv6') {
1661 # Note: we use dport to store --icmpv6-type
1662 die "unknown icmpv6-type '$rule->{dport}'\n" if !defined($icmpv6_type_names->{$rule->{dport
}});
1663 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1666 if ($multiport == 2) {
1667 push @cmd, "--ports $rule->{dport}";
1669 push @cmd, "--dports $rule->{dport}";
1672 push @cmd, "--dport $rule->{dport}";
1677 if ($rule->{sport
}) {
1679 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1681 push @cmd, "--sport $rule->{sport}";
1684 } elsif ($rule->{dport
} || $rule->{sport
}) {
1685 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1686 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1689 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1691 if (my $action = $rule->{action
}) {
1692 $action = $actions->{$action} if defined($actions->{$action});
1693 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1694 push @cmd, $goto ?
"-g $action" : "-j $action";
1697 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1700 sub ruleset_generate_rule
{
1701 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1705 if ($rule->{macro}) {
1706 $rules = &$apply_macro($rule->{macro}, $rule);
1711 # update all or nothing
1714 foreach my $tmp (@$rules) {
1715 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1716 push @cmds, $cmdstr;
1720 foreach my $cmdstr (@cmds) {
1721 ruleset_addrule
($ruleset, $chain, $cmdstr);
1725 sub ruleset_generate_rule_insert
{
1726 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1728 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1730 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1731 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1735 sub ruleset_create_chain
{
1736 my ($ruleset, $chain) = @_;
1738 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1739 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1741 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1743 $ruleset->{$chain} = [];
1746 sub ruleset_chain_exist
{
1747 my ($ruleset, $chain) = @_;
1749 return $ruleset->{$chain} ?
1 : undef;
1752 sub ruleset_addrule
{
1753 my ($ruleset, $chain, $rule) = @_;
1755 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1757 push @{$ruleset->{$chain}}, "-A $chain $rule";
1760 sub ruleset_insertrule
{
1761 my ($ruleset, $chain, $rule) = @_;
1763 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1765 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1768 sub get_log_rule_base
{
1769 my ($chain, $vmid, $msg, $loglevel) = @_;
1771 die "internal error - no log level" if !defined($loglevel);
1773 $vmid = 0 if !defined($vmid);
1775 # Note: we use special format for prefix to pass further
1776 # info to log daemon (VMID, LOGVELEL and CHAIN)
1778 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1781 sub ruleset_addlog {
1782 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1784 return if !defined($loglevel);
1786 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1788 $logrule = "$rule $logrule" if defined($rule);
1790 ruleset_addrule($ruleset, $chain, $logrule);
1793 sub ruleset_add_chain_policy {
1794 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1796 if ($policy eq 'ACCEPT') {
1798 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1799 { ACCEPT => $accept_action});
1801 } elsif ($policy eq 'DROP') {
1803 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1805 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1807 ruleset_addrule($ruleset, $chain, "-j DROP
");
1808 } elsif ($policy eq 'REJECT') {
1809 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1811 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1813 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1816 die "internal error
: unknown policy
'$policy'";
1820 sub ruleset_chain_add_conn_filters {
1821 my ($ruleset, $chain, $accept) = @_;
1823 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1824 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1827 sub ruleset_chain_add_input_filters {
1828 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1830 if ($cluster_conf->{ipset}->{blacklist}){
1831 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1832 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1833 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1834 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1836 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1837 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1840 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1841 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1844 if ($options->{tcpflags}) {
1845 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1849 sub ruleset_create_vm_chain {
1850 my ($ruleset, $chain, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1852 ruleset_create_chain($ruleset, $chain);
1853 my $accept = generate_nfqueue($options);
1855 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1856 if ($direction eq 'OUT') {
1857 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1858 proto => 'udp', sport => 68, dport => 67 });
1860 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1861 proto => 'udp', sport => 67, dport => 68 });
1865 if ($direction eq 'OUT') {
1866 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1867 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1869 if ($ipfilter_ipset) {
1870 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
1872 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1876 sub ruleset_add_group_rule {
1877 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1879 my $group = $rule->{action};
1880 my $group_chain = "GROUP-
$group-$direction";
1881 if(!ruleset_chain_exist($ruleset, $group_chain)){
1882 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1885 if ($direction eq 'OUT' && $rule->{iface_out}) {
1886 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1887 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1888 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1890 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1893 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1896 sub ruleset_generate_vm_rules {
1897 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
1899 my $lc_direction = lc($direction);
1901 my $in_accept = generate_nfqueue($options);
1903 foreach my $rule (@$rules) {
1904 next if $rule->{iface} && $rule->{iface} ne $netid;
1905 next if !$rule->{enable} || $rule->{errors};
1906 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
1908 if ($rule->{type} eq 'group') {
1909 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1910 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
1912 next if $rule->{type} ne $lc_direction;
1914 if ($direction eq 'OUT') {
1915 ruleset_generate_rule($ruleset, $chain, $rule,
1916 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1917 undef, $cluster_conf, $vmfw_conf);
1919 ruleset_generate_rule($ruleset, $chain, $rule,
1920 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1921 undef, $cluster_conf, $vmfw_conf);
1929 sub generate_nfqueue {
1932 if ($options->{ips}) {
1933 my $action = "NFQUEUE
";
1934 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1935 if (defined($3) && defined($1)) {
1936 $action .= " --queue-balance
$1:$3";
1937 } elsif (defined($1)) {
1938 $action .= " --queue-num
$1";
1941 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1948 sub ruleset_generate_vm_ipsrules {
1949 my ($ruleset, $options, $direction, $iface) = @_;
1951 if ($options->{ips} && $direction eq 'IN') {
1952 my $nfqueue = generate_nfqueue($options);
1954 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1955 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1958 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1962 sub generate_venet_rules_direction {
1963 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction, $ipversion) = @_;
1965 my $lc_direction = lc($direction);
1967 my $rules = $vmfw_conf->{rules};
1969 my $options = $vmfw_conf->{options};
1970 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1972 my $chain = "venet0-
$vmid-$direction";
1974 ruleset_create_vm_chain($ruleset, $chain, $options, undef, undef, $direction);
1976 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction, undef, $ipversion);
1981 if ($direction eq 'OUT') {
1982 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1984 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1987 my $accept = generate_nfqueue($options);
1988 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1989 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1991 if ($direction eq 'OUT') {
1992 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1995 iface_in => 'venet0'});
1997 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
2000 iface_out => 'venet0'});
2004 sub generate_tap_rules_direction {
2005 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2007 my $lc_direction = lc($direction);
2009 my $rules = $vmfw_conf->{rules};
2011 my $options = $vmfw_conf->{options};
2012 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2014 my $tapchain = "$iface-$direction";
2016 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2017 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name)
2018 if $vmfw_conf->{ipset}->{$ipfilter_name};
2020 # create chain with mac and ip filter
2021 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $ipfilter_ipset, $direction);
2023 if ($options->{enable}) {
2024 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2026 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2031 if ($direction eq 'OUT') {
2032 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2034 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2037 my $accept = generate_nfqueue($options);
2038 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2039 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
2041 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2042 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, 'ACCEPT', $loglevel, $accept_action);
2045 # plug the tap chain to bridge chain
2046 if ($direction eq 'IN') {
2047 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2048 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2050 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2051 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2055 sub enable_host_firewall {
2056 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2058 my $options = $hostfw_conf->{options};
2059 my $cluster_options = $cluster_conf->{options};
2060 my $rules = $hostfw_conf->{rules};
2061 my $cluster_rules = $cluster_conf->{rules};
2063 # host inbound firewall
2064 my $chain = "PVEFW-HOST-IN
";
2065 ruleset_create_chain($ruleset, $chain);
2067 my $loglevel = get_option_log_level($options, "log_level_in
");
2069 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2071 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2072 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
2074 # we use RETURN because we need to check also tap rules
2075 my $accept_action = 'RETURN';
2077 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2079 # add host rules first, so that cluster wide rules can be overwritten
2080 foreach my $rule (@$rules, @$cluster_rules) {
2081 next if !$rule->{enable} || $rule->{errors};
2083 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2086 if ($rule->{type} eq 'group') {
2087 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2088 } elsif ($rule->{type} eq 'in') {
2089 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2090 undef, $cluster_conf, $hostfw_conf);
2094 delete $rule->{iface_in};
2097 # allow standard traffic for management ipset (includes cluster network)
2098 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
");
2099 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2100 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2101 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2102 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2103 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2105 my $localnet = local_network();
2109 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2110 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2111 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2114 # implement input policy
2115 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2116 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
2118 # host outbound firewall
2119 $chain = "PVEFW-HOST-OUT
";
2120 ruleset_create_chain($ruleset, $chain);
2122 $loglevel = get_option_log_level($options, "log_level_out
");
2124 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2126 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2128 # we use RETURN because we may want to check other thigs later
2129 $accept_action = 'RETURN';
2131 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2133 # add host rules first, so that cluster wide rules can be overwritten
2134 foreach my $rule (@$rules, @$cluster_rules) {
2135 next if !$rule->{enable} || $rule->{errors};
2137 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2139 if ($rule->{type} eq 'group') {
2140 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2141 } elsif ($rule->{type} eq 'out') {
2142 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2143 undef, $cluster_conf, $hostfw_conf);
2147 delete $rule->{iface_out};
2150 # allow standard traffic on cluster network
2152 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2153 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2154 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2155 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2157 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2158 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2159 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2162 # implement output policy
2163 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2164 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
2166 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2167 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2170 sub generate_group_rules {
2171 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2173 my $rules = $cluster_conf->{groups}->{$group};
2176 warn "no such security group
'$group'\n";
2177 $rules = []; # create empty chain
2180 my $chain = "GROUP-
${group
}-IN
";
2182 ruleset_create_chain($ruleset, $chain);
2183 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2185 foreach my $rule (@$rules) {
2186 next if $rule->{type} ne 'in';
2187 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2188 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
2191 $chain = "GROUP-
${group
}-OUT
";
2193 ruleset_create_chain($ruleset, $chain);
2194 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2196 foreach my $rule (@$rules) {
2197 next if $rule->{type} ne 'out';
2198 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2199 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2200 # check also other tap rules later
2201 ruleset_generate_rule($ruleset, $chain, $rule,
2202 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
2207 my $valid_netdev_names = {};
2208 for (my $i = 0; $i < $MAX_NETS; $i++) {
2209 $valid_netdev_names->{"net
$i"} = 1;
2213 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2215 my $orig_line = $line;
2219 # we can add single line comments to the end of the rule
2220 if ($line =~ s/#\s*(.*?)\s*$//) {
2221 $rule->{comment} = decode('utf8', $1);
2224 # we can disable a rule when prefixed with '|'
2226 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2228 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2229 die "unable to parse rule
: $line\n";
2231 $rule->{type} = lc($1);
2232 $rule->{action} = $2;
2234 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2235 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2236 $rule->{macro} = $1;
2237 $rule->{action} = $2;
2241 while (length($line)) {
2242 if ($line =~ s/^-i (\S+)\s*//) {
2243 $rule->{iface} = $1;
2247 last if $rule->{type} eq 'group';
2249 if ($line =~ s/^-p (\S+)\s*//) {
2250 $rule->{proto} = $1;
2254 if ($line =~ s/^-dport (\S+)\s*//) {
2255 $rule->{dport} = $1;
2259 if ($line =~ s/^-sport (\S+)\s*//) {
2260 $rule->{sport} = $1;
2263 if ($line =~ s/^-source (\S+)\s*//) {
2264 $rule->{source} = $1;
2267 if ($line =~ s/^-dest (\S+)\s*//) {
2275 die "unable to parse rule parameters
: $line\n" if length($line);
2277 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2278 if ($verbose && $rule->{errors}) {
2279 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2280 foreach my $p (keys %{$rule->{errors}}) {
2281 warn " $p: $rule->{errors
}->{$p}\n";
2288 sub parse_vmfw_option {
2293 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2295 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2298 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2300 $value = $2 ? lc($3) : '';
2301 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2304 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2308 die "can
't parse option '$line'\n"
2311 return ($opt, $value);
2314 sub parse_hostfw_option {
2319 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2321 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2324 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2326 $value = $2 ? lc($3) : '';
2327 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2331 die "can't parse option
'$line'\n"
2334 return ($opt, $value);
2337 sub parse_clusterfw_option {
2342 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2345 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2349 die "can
't parse option '$line'\n"
2352 return ($opt, $value);
2356 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2358 my $alias = lc($cidr);
2359 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2360 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2362 die "no such alias '$cidr'\n" if !$e;;
2364 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2367 sub parse_ip_or_cidr {
2372 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2375 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2379 die "value does not look like a valid IP address or CIDR network\n";
2382 return wantarray ? ($cidr, $ipversion) : $cidr;
2388 # we can add single line comments to the end of the line
2389 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2391 if ($line =~ m/^(\S+)\s(\S+)$/) {
2392 my ($name, $cidr) = ($1, $2);
2395 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2400 ipversion => $ipversion,
2402 $data->{comment} = $comment if $comment;
2409 sub generic_fw_config_parser {
2410 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2415 my $res = $empty_conf;
2417 while (defined(my $line = <$fh>)) {
2418 next if $line =~ m/^#/;
2419 next if $line =~ m/^\s*$/;
2423 my $linenr = $fh->input_line_number();
2424 my $prefix = "$filename (line $linenr)";
2426 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2427 $section = 'options
';
2431 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2432 $section = 'aliases
';
2436 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2437 $section = 'groups
';
2441 die "security group name too long\n" if length($group) > $max_group_name_length;
2442 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2445 ($section, $group, $comment) = undef;
2446 warn "$prefix: $err";
2450 $res->{$section}->{$group} = [];
2451 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2456 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2461 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2466 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2467 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2470 ($section, $group, $comment) = undef;
2471 warn "$prefix: $err";
2475 $res->{$section}->{$group} = [];
2476 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2482 warn "$prefix: skip line - no section\n";
2486 if ($section eq 'options
') {
2489 if ($rule_env eq 'cluster
') {
2490 ($opt, $value) = parse_clusterfw_option($line);
2491 } elsif ($rule_env eq 'host
') {
2492 ($opt, $value) = parse_hostfw_option($line);
2494 ($opt, $value) = parse_vmfw_option($line);
2496 $res->{options}->{$opt} = $value;
2498 warn "$prefix: $@" if $@;
2499 } elsif ($section eq 'aliases
') {
2501 my $data = parse_alias($line);
2502 $res->{aliases}->{lc($data->{name})} = $data;
2504 warn "$prefix: $@" if $@;
2505 } elsif ($section eq 'rules
') {
2507 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2509 warn "$prefix: $err";
2512 push @{$res->{$section}}, $rule;
2513 } elsif ($section eq 'groups
') {
2515 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2517 warn "$prefix: $err";
2520 push @{$res->{$section}->{$group}}, $rule;
2521 } elsif ($section eq 'ipset
') {
2522 # we can add single line comments to the end of the rule
2523 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2525 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2530 if ($nomatch && !$feature_ipset_nomatch) {
2531 $errors->{nomatch} = "nomatch not supported by kernel";
2535 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2536 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2538 $cidr = parse_ip_or_cidr($cidr);
2543 $errors->{cidr} = $err;
2546 my $entry = { cidr => $cidr };
2547 $entry->{nomatch} = 1 if $nomatch;
2548 $entry->{comment} = $comment if $comment;
2549 $entry->{errors} = $errors if $errors;
2551 if ($verbose && $errors) {
2552 warn "$prefix - errors in ipset '$group': $line\n";
2553 foreach my $p (keys %{$errors}) {
2554 warn " $p: $errors->{$p}\n";
2558 push @{$res->{$section}->{$group}}, $entry;
2560 warn "$prefix: skip line - unknown section\n";
2568 sub parse_hostfw_config {
2569 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2571 my $empty_conf = { rules => [], options => {}};
2573 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2576 sub parse_vmfw_config {
2577 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2584 ipset_comments => {},
2587 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2590 sub parse_clusterfw_config {
2591 my ($filename, $fh, $verbose) = @_;
2601 group_comments => {},
2603 ipset_comments => {},
2606 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2610 my ($code, @param) = @_;
2614 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2621 sub read_local_vm_config {
2626 my $vmdata = { openvz => $openvz, qemu => $qemu };
2628 my $vmlist = PVE::Cluster::get_vmlist();
2629 return $vmdata if !$vmlist || !$vmlist->{ids};
2630 my $ids = $vmlist->{ids};
2632 foreach my $vmid (keys %$ids) {
2633 next if !$vmid; # skip VE0
2634 my $d = $ids->{$vmid};
2635 next if !$d->{node} || $d->{node} ne $nodename;
2636 next if !$d->{type};
2637 if ($d->{type} eq 'openvz
') {
2638 if ($have_pve_manager) {
2639 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2640 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2641 $openvz->{$vmid} = $conf;
2644 } elsif ($d->{type} eq 'qemu
') {
2645 if ($have_qemu_server) {
2646 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2647 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2648 $qemu->{$vmid} = $conf;
2657 sub load_vmfw_conf {
2658 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2662 $dir = $pvefw_conf_dir if !defined($dir);
2664 my $filename = "$dir/$vmid.fw";
2665 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2666 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2667 $vmfw_conf->{vmid} = $vmid;
2673 my $format_rules = sub {
2674 my ($rules, $allow_iface) = @_;
2678 foreach my $rule (@$rules) {
2679 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2680 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2681 $raw .= uc($rule->{type});
2682 if ($rule->{macro}) {
2683 $raw .= " $rule->{macro}($rule->{action})";
2685 $raw .= " " . $rule->{action};
2687 if ($allow_iface && $rule->{iface}) {
2688 $raw .= " -i $rule->{iface}";
2691 if ($rule->{type} ne 'group
') {
2692 $raw .= " -source $rule->{source}" if $rule->{source};
2693 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2694 $raw .= " -p $rule->{proto}" if $rule->{proto};
2695 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2696 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2699 $raw .= " # " . encode('utf8
', $rule->{comment})
2700 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2703 die "unknown rule type '$rule->{type
}'";
2710 my $format_options = sub {
2715 $raw .= "[OPTIONS]\n\n";
2716 foreach my $opt (keys %$options) {
2717 $raw .= "$opt: $options->{$opt}\n";
2724 my $format_aliases = sub {
2729 $raw .= "[ALIASES]\n\n";
2730 foreach my $k (keys %$aliases) {
2731 my $e = $aliases->{$k};
2732 $raw .= "$e->{name} $e->{cidr}";
2733 $raw .= " # " . encode('utf8
', $e->{comment})
2734 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2742 my $format_ipsets = sub {
2747 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2748 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2749 my $utf8comment = encode('utf8
', $comment);
2750 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2752 $raw .= "[IPSET $ipset]\n\n";
2754 my $options = $fw_conf->{ipset}->{$ipset};
2757 foreach my $entry (@$options) {
2758 $nethash->{$entry->{cidr}} = $entry;
2761 foreach my $cidr (sort keys %$nethash) {
2762 my $entry = $nethash->{$cidr};
2763 my $line = $entry->{nomatch} ? '!' : '';
2764 $line .= $entry->{cidr};
2765 $line .= " # " . encode('utf8
', $entry->{comment})
2766 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2776 sub save_vmfw_conf {
2777 my ($vmid, $vmfw_conf) = @_;
2781 my $options = $vmfw_conf->{options};
2782 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2784 my $aliases = $vmfw_conf->{aliases};
2785 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2787 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2789 my $rules = $vmfw_conf->{rules} || [];
2790 if ($rules && scalar(@$rules)) {
2791 $raw .= "[RULES]\n\n";
2792 $raw .= &$format_rules($rules, 1);
2796 mkdir $pvefw_conf_dir;
2798 my $filename = "$pvefw_conf_dir/$vmid.fw";
2799 PVE::Tools::file_set_contents($filename, $raw);
2802 sub read_vm_firewall_configs {
2803 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2805 my $vmfw_configs = {};
2807 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2808 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2809 next if !$vmfw_conf->{options}; # skip if file does not exists
2810 $vmfw_configs->{$vmid} = $vmfw_conf;
2812 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2813 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2814 next if !$vmfw_conf->{options}; # skip if file does not exists
2815 $vmfw_configs->{$vmid} = $vmfw_conf;
2818 return $vmfw_configs;
2821 sub get_option_log_level {
2822 my ($options, $k) = @_;
2824 my $v = $options->{$k};
2825 $v = $default_log_level if !defined($v);
2827 return undef if $v eq '' || $v eq 'nolog
';
2829 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2831 return $v if ($v >= 0) && ($v <= 7);
2833 warn "unknown log level ($k = '$v')\n";
2838 sub generate_std_chains {
2839 my ($ruleset, $options, $ipversion) = @_;
2841 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2843 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2847 if ($ipversion == 4) {
2848 # same as shorewall smurflog.
2849 $chain = 'PVEFW-smurflog
';
2850 $std_chains->{$chain} = [];
2852 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2853 push @{$std_chains->{$chain}}, "-j DROP";
2856 # same as shorewall logflags action.
2857 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2858 $chain = 'PVEFW-logflags
';
2859 $std_chains->{$chain} = [];
2861 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2862 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2863 push @{$std_chains->{$chain}}, "-j DROP";
2865 foreach my $chain (keys %$std_chains) {
2866 ruleset_create_chain($ruleset, $chain);
2867 foreach my $rule (@{$std_chains->{$chain}}) {
2869 ruleset_generate_rule($ruleset, $chain, $rule);
2871 ruleset_addrule($ruleset, $chain, $rule);
2877 sub generate_ipset_chains {
2878 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2880 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2881 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2882 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2886 sub generate_ipset {
2887 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2889 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2891 $ipset_ruleset->{$name} = ["create $name list:set size 4"];
2895 foreach my $entry (@$options) {
2896 next if $entry->{errors}; # skip entries with errors
2898 my ($cidr, $ipversion);
2899 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2900 ($cidr, $ipversion) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2902 ($cidr, $ipversion) = parse_ip_or_cidr($entry->{cidr});
2904 #http://backreference.org/2013/03/01/ipv6-address-normalization/
2905 if ($ipversion == 6) {
2906 my $ipv6 = inet_pton(AF_INET6, lc($cidr));
2907 $cidr = inet_ntop(AF_INET6, $ipv6);
2913 $nethash->{$ipversion}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2918 foreach my $ipversion (sort keys %$nethash) {
2919 my $data = $nethash->{$ipversion};
2920 my $subname = "$name-v$ipversion";
2922 my $hashsize = scalar(@$options);
2923 if ($hashsize <= 64) {
2926 $hashsize = round_powerof2($hashsize);
2929 my $family = $ipversion == "6" ? "inet6" : "inet";
2931 $ipset_ruleset->{$subname} = ["create $subname hash:net family $family hashsize $hashsize maxelem $hashsize"];
2933 foreach my $cidr (sort keys %$data) {
2934 my $entry = $data->{$cidr};
2936 my $cmd = "add $subname $cidr";
2937 if ($entry->{nomatch}) {
2938 if ($feature_ipset_nomatch) {
2939 push @{$ipset_ruleset->{$subname}}, "$cmd nomatch";
2941 warn "ignore !$cidr - nomatch not supported by kernel\n";
2944 push @{$ipset_ruleset->{$subname}}, $cmd;
2948 push @{$ipset_ruleset->{$name}}, "add $name $subname";
2952 sub round_powerof2 {
2956 $int |= $int >> $_ foreach (1,2,4,8,16);
2960 sub load_clusterfw_conf {
2961 my ($filename, $verbose) = @_;
2963 $filename = $clusterfw_conf_filename if !defined($filename);
2965 my $cluster_conf = {};
2966 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2967 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
2970 return $cluster_conf;
2973 sub save_clusterfw_conf {
2974 my ($cluster_conf) = @_;
2978 my $options = $cluster_conf->{options};
2979 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2981 my $aliases = $cluster_conf->{aliases};
2982 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2984 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
2986 my $rules = $cluster_conf->{rules};
2987 if ($rules && scalar(@$rules)) {
2988 $raw .= "[RULES]\n\n";
2989 $raw .= &$format_rules($rules, 1);
2993 if ($cluster_conf->{groups}) {
2994 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2995 my $rules = $cluster_conf->{groups}->{$group};
2996 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2997 my $utf8comment = encode('utf8
', $comment);
2998 $raw .= "[group $group] # $utf8comment\n\n";
3000 $raw .= "[group $group]\n\n";
3003 $raw .= &$format_rules($rules, 0);
3008 mkdir $pvefw_conf_dir;
3009 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3012 sub load_hostfw_conf {
3013 my ($cluster_conf, $filename, $verbose) = @_;
3015 $filename = $hostfw_conf_filename if !defined($filename);
3017 my $hostfw_conf = {};
3018 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3019 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3021 return $hostfw_conf;
3024 sub save_hostfw_conf {
3025 my ($hostfw_conf) = @_;
3029 my $options = $hostfw_conf->{options};
3030 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3032 my $rules = $hostfw_conf->{rules};
3033 if ($rules && scalar(@$rules)) {
3034 $raw .= "[RULES]\n\n";
3035 $raw .= &$format_rules($rules, 1);
3039 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3043 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3047 if ($vmdata) { # test mode
3048 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3049 my $filename = "$testdir/cluster.fw";
3050 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3052 $filename = "$testdir/host.fw";
3053 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3055 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3056 } else { # normal operation
3057 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3059 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3061 $vmdata = read_local_vm_config();
3062 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3065 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3066 my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3068 return ($ruleset, $ipset_ruleset, $rulesetv6);
3071 sub compile_iptables_filter {
3072 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3074 $cluster_conf->{ipset}->{venet0} = [];
3075 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
3078 if ($cluster_conf->{aliases}->{local_network}) {
3079 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3081 $localnet = local_network() || '127.0.0.0/8';
3082 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
3085 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3087 return ({}, {}) if !$cluster_conf->{options}->{enable};
3091 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3092 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3094 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3096 my $hostfw_options = $hostfw_conf->{options} || {};
3098 # fixme: what log level should we use here?
3099 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3101 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3104 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
3105 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3106 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3108 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3109 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
3111 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3113 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3114 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3116 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
3117 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
3119 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3121 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3123 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3125 my $ipset_ruleset = {};
3127 # currently pveproxy don't works with ipv6
, so let
's generate host fw ipv4 only for the moment
3128 if ($hostfw_enable && ($ipversion == 4)) {
3129 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3130 warn $@ if $@; # just to be sure - should not happen
3133 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3135 # generate firewall rules for QEMU VMs
3136 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3138 my $conf = $vmdata->{qemu}->{$vmid};
3139 my $vmfw_conf = $vmfw_configs->{$vmid};
3140 return if !$vmfw_conf;
3142 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3144 foreach my $netid (keys %$conf) {
3145 next if $netid !~ m/^net(\d+)$/;
3146 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3147 next if !$net->{firewall};
3148 my $iface = "tap${vmid}i$1";
3150 my $macaddr = $net->{macaddr};
3151 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3152 $vmfw_conf, $vmid, 'IN
', $ipversion);
3153 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3154 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3157 warn $@ if $@; # just to be sure - should not happen
3160 # generate firewall rules for OpenVZ containers
3161 foreach my $vmid (keys %{$vmdata->{openvz}}) {
3163 my $conf = $vmdata->{openvz}->{$vmid};
3165 my $vmfw_conf = $vmfw_configs->{$vmid};
3166 return if !$vmfw_conf;
3168 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3170 if ($vmfw_conf->{options}->{enable}) {
3171 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
3172 my $ip = $conf->{ip_address}->{value};
3177 foreach my $singleip (split(',', $ip)) {
3178 my $singleip_ver = parse_address_list($singleip); # make sure we have a valid $ip list
3179 push @{$cluster_conf->{ipset}->{venet0}}, { cidr => $singleip };
3180 push @ips, $singleip if $singleip_ver == $ipversion;
3184 my $ip_list = join(',', @ips);
3185 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'IN
', $ipversion);
3186 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'OUT
', $ipversion);
3191 if ($conf->{netif} && $conf->{netif}->{value}) {
3192 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
3193 foreach my $netid (keys %$netif) {
3194 my $d = $netif->{$netid};
3195 my $bridge = $d->{bridge};
3196 next if !$bridge || $bridge !~ m/^vmbr\d+(v(\d+))?f$/; # firewall enabled ?
3197 my $macaddr = $d->{mac};
3198 my $iface = $d->{host_ifname};
3199 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3200 $vmfw_conf, $vmid, 'IN
', $ipversion);
3201 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3202 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3206 warn $@ if $@; # just to be sure - should not happen
3209 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3210 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3213 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
3215 return ($ruleset, $ipset_ruleset);
3218 sub get_ruleset_status {
3219 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3221 my $statushash = {};
3223 foreach my $chain (sort keys %$ruleset) {
3224 my $sig = &$digest_fn($ruleset->{$chain});
3226 $statushash->{$chain}->{sig} = $sig;
3228 my $oldsig = $active_chains->{$chain};
3229 if (!defined($oldsig)) {
3230 $statushash->{$chain}->{action} = 'create
';
3232 if ($oldsig eq $sig) {
3233 $statushash->{$chain}->{action} = 'exists';
3235 $statushash->{$chain}->{action} = 'update
';
3238 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3239 foreach my $cmd (@{$ruleset->{$chain}}) {
3240 print "\t$cmd\n" if $verbose;
3244 foreach my $chain (sort keys %$active_chains) {
3245 if (!defined($ruleset->{$chain})) {
3246 my $sig = $active_chains->{$chain};
3247 $statushash->{$chain}->{action} = 'delete';
3248 $statushash->{$chain}->{sig} = $sig;
3249 print "delete $chain ($sig)\n" if $verbose;
3256 sub print_sig_rule {
3257 my ($chain, $sig) = @_;
3259 # We just use this to store a SHA1 checksum used to detect changes
3260 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3263 sub get_ruleset_cmdlist {
3264 my ($ruleset, $verbose, $iptablescmd) = @_;
3266 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3268 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3269 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3271 # create missing chains first
3272 foreach my $chain (sort keys %$ruleset) {
3273 my $stat = $statushash->{$chain};
3274 die "internal error" if !$stat;
3275 next if $stat->{action} ne 'create
';
3277 $cmdlist .= ":$chain - [0:0]\n";
3280 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3281 my $chain = "PVEFW-$h";
3282 if ($ruleset->{$chain} && !$hooks->{$h}) {
3283 $cmdlist .= "-A $h -j $chain\n";
3287 foreach my $chain (sort keys %$ruleset) {
3288 my $stat = $statushash->{$chain};
3289 die "internal error" if !$stat;
3291 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3292 $cmdlist .= "-F $chain\n";
3293 foreach my $cmd (@{$ruleset->{$chain}}) {
3294 $cmdlist .= "$cmd\n";
3296 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3297 } elsif ($stat->{action
} eq 'delete') {
3298 die "internal error"; # this should not happen
3299 } elsif ($stat->{action
} eq 'exists') {
3302 die "internal error - unknown status '$stat->{action}'";
3306 foreach my $chain (keys %$statushash) {
3307 next if $statushash->{$chain}->{action
} ne 'delete';
3308 $cmdlist .= "-F $chain\n";
3310 foreach my $chain (keys %$statushash) {
3311 next if $statushash->{$chain}->{action
} ne 'delete';
3312 next if $chain eq 'PVEFW-INPUT';
3313 next if $chain eq 'PVEFW-OUTPUT';
3314 next if $chain eq 'PVEFW-FORWARD';
3315 $cmdlist .= "-X $chain\n";
3318 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3320 $cmdlist .= "COMMIT\n";
3322 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3325 sub get_ipset_cmdlist
{
3326 my ($ruleset, $verbose) = @_;
3330 my $delete_cmdlist = "";
3332 my $active_chains = ipset_get_chains
();
3333 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3335 # remove stale _swap chains
3336 foreach my $chain (keys %$active_chains) {
3337 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3338 $cmdlist .= "destroy $chain\n";
3342 foreach my $chain (sort keys %$ruleset) {
3343 my $stat = $statushash->{$chain};
3344 die "internal error" if !$stat;
3346 if ($stat->{action
} eq 'create') {
3347 foreach my $cmd (@{$ruleset->{$chain}}) {
3348 $cmdlist .= "$cmd\n";
3353 foreach my $chain (sort keys %$ruleset) {
3354 my $stat = $statushash->{$chain};
3355 die "internal error" if !$stat;
3357 if ($stat->{action
} eq 'update') {
3358 my $chain_swap = $chain."_swap";
3360 foreach my $cmd (@{$ruleset->{$chain}}) {
3361 $cmd =~ s/$chain/$chain_swap/;
3362 $cmdlist .= "$cmd\n";
3364 $cmdlist .= "swap $chain_swap $chain\n";
3365 $cmdlist .= "flush $chain_swap\n";
3366 $cmdlist .= "destroy $chain_swap\n";
3370 foreach my $chain (sort keys %$statushash) {
3371 next if $statushash->{$chain}->{action
} ne 'delete';
3373 $delete_cmdlist .= "flush $chain\n";
3374 $delete_cmdlist .= "destroy $chain\n";
3377 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3379 return ($cmdlist, $delete_cmdlist, $changes);
3383 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3385 enable_bridge_firewall
();
3387 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3388 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3390 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3391 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3394 if ($ipset_changes) {
3395 print "ipset changes:\n";
3396 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3397 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3401 print "iptables changes:\n";
3406 print "ip6tables changes:\n";
3411 ipset_restore_cmdlist
($ipset_create_cmdlist);
3413 iptables_restore_cmdlist
($cmdlist);
3414 ip6tables_restore_cmdlist
($cmdlistv6);
3416 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3418 # test: re-read status and check if everything is up to date
3419 my $active_chains = iptables_get_chains
();
3420 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3423 foreach my $chain (sort keys %$ruleset) {
3424 my $stat = $statushash->{$chain};
3425 if ($stat->{action
} ne 'exists') {
3426 warn "unable to update chain '$chain'\n";
3431 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3432 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3434 foreach my $chain (sort keys %$rulesetv6) {
3435 my $stat = $statushashv6->{$chain};
3436 if ($stat->{action
} ne 'exists') {
3437 warn "unable to update chain '$chain'\n";
3442 die "unable to apply firewall changes\n" if $errors;
3444 update_nf_conntrack_max
($hostfw_conf);
3446 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3450 sub update_nf_conntrack_max
{
3451 my ($hostfw_conf) = @_;
3453 my $max = 65536; # reasonable default
3455 my $options = $hostfw_conf->{options
} || {};
3457 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3458 $max = $options->{nf_conntrack_max
};
3459 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3462 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3463 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3465 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3467 if ($current != $max) {
3468 my $hashsize = int($max/4);
3469 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3470 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3474 sub update_nf_conntrack_tcp_timeout_established
{
3475 my ($hostfw_conf) = @_;
3477 my $options = $hostfw_conf->{options
} || {};
3479 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3481 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3484 sub remove_pvefw_chains
{
3486 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3487 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3488 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3492 sub remove_pvefw_chains_iptables
{
3493 my ($iptablescmd) = @_;
3495 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3496 my $cmdlist = "*filter\n";
3498 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3500 $cmdlist .= "-D $h -j PVEFW-$h\n";
3504 foreach my $chain (keys %$chash) {
3505 $cmdlist .= "-F $chain\n";
3508 foreach my $chain (keys %$chash) {
3509 $cmdlist .= "-X $chain\n";
3511 $cmdlist .= "COMMIT\n";
3513 if($iptablescmd eq "ip6tables") {
3514 ip6tables_restore_cmdlist
($cmdlist);
3516 iptables_restore_cmdlist
($cmdlist);
3520 sub remove_pvefw_chains_ipset
{
3522 my $ipset_chains = ipset_get_chains
();
3524 my $sub_cmdlist = "";
3527 foreach my $chain (keys %$ipset_chains) {
3528 if ($chain =~ m/^PVEFW-\S+\-(v4|v6)$/) {
3529 $sub_cmdlist .= "flush $chain\n";
3530 $sub_cmdlist .= "destroy $chain\n";
3532 $cmdlist .= "flush $chain\n";
3533 $cmdlist .= "destroy $chain\n";
3537 $cmdlist .= $sub_cmdlist;
3539 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3543 my $cluster_conf = load_clusterfw_conf
();
3544 my $cluster_options = $cluster_conf->{options
};
3545 my $enable = $cluster_options->{enable
};
3549 # load required modules here
3555 my $cluster_conf = load_clusterfw_conf
();
3556 my $cluster_options = $cluster_conf->{options
};
3558 if (!$cluster_options->{enable
}) {
3559 PVE
::Firewall
::remove_pvefw_chains
();
3563 my $hostfw_conf = load_hostfw_conf
();
3565 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3567 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);