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 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
585 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
586 #{ action => 'DROP', dest => '224.0.0.0/4' },
589 # same as shorewall 'reject'
590 #{ action => 'DROP', dsttype => 'BROADCAST' },
591 #{ action => 'DROP', source => '224.0.0.0/4' },
592 { action
=> 'DROP', proto
=> 'icmpv6' },
593 "-p tcp -j REJECT --reject-with tcp-reset",
594 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
595 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
596 #"-j REJECT --reject-with icmp-host-prohibited",
599 # same as shorewall 'Drop', which is equal to DROP,
600 # but REJECT/DROP some packages to reduce logging,
601 # and ACCEPT critical ICMP types
602 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
603 # we are not interested in BROADCAST/MULTICAST/ANYCAST
604 { action
=> 'PVEFW-DropBroadcast' },
605 # ACCEPT critical ICMP types
606 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
607 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
608 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
610 # Drop packets with INVALID state
611 "-m conntrack --ctstate INVALID -j DROP",
612 # Drop Microsoft SMB noise
613 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
614 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
615 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
616 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
617 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
618 # Drop new/NotSyn traffic so that it doesn't get logged
619 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
621 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
624 # same as shorewall 'Reject', which is equal to Reject,
625 # but REJECT/DROP some packages to reduce logging,
626 # and ACCEPT critical ICMP types
627 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
628 # we are not interested in BROADCAST/MULTICAST/ANYCAST
629 { action
=> 'PVEFW-DropBroadcast' },
630 # ACCEPT critical ICMP types
631 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
632 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
633 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
635 # Drop packets with INVALID state
636 "-m conntrack --ctstate INVALID -j DROP",
637 # Drop Microsoft SMB noise
638 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
639 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
640 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
641 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
642 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
643 # Drop new/NotSyn traffic so that it doesn't get logged
644 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
646 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
648 'PVEFW-tcpflags' => [
649 # same as shorewall tcpflags action.
650 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
651 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
652 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
653 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
654 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
655 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
658 #does smurf attack works with ipv6, as broadcast not exist ???
660 # same as shorewall smurfs action
661 # Filter packets for smurfs (packets with a broadcast address as the source).
662 #"-s 0.0.0.0/32 -j RETURN",
663 #"-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
664 #"-s 224.0.0.0/4 -g PVEFW-smurflog",
668 # iptables -p icmp -h
669 my $icmp_type_names = {
672 'destination-unreachable' => 1,
673 'network-unreachable' => 1,
674 'host-unreachable' => 1,
675 'protocol-unreachable' => 1,
676 'port-unreachable' => 1,
677 'fragmentation-needed' => 1,
678 'source-route-failed' => 1,
679 'network-unknown' => 1,
681 'network-prohibited' => 1,
682 'host-prohibited' => 1,
683 'TOS-network-unreachable' => 1,
684 'TOS-host-unreachable' => 1,
685 'communication-prohibited' => 1,
686 'host-precedence-violation' => 1,
687 'precedence-cutoff' => 1,
688 'source-quench' => 1,
690 'network-redirect' => 1,
691 'host-redirect' => 1,
692 'TOS-network-redirect' => 1,
693 'TOS-host-redirect' => 1,
695 'router-advertisement' => 1,
696 'router-solicitation' => 1,
697 'time-exceeded' => 1,
698 'ttl-zero-during-transit' => 1,
699 'ttl-zero-during-reassembly' => 1,
700 'parameter-problem' => 1,
701 'ip-header-bad' => 1,
702 'required-option-missing' => 1,
703 'timestamp-request' => 1,
704 'timestamp-reply' => 1,
705 'address-mask-request' => 1,
706 'address-mask-reply' => 1,
709 # ip6tables -p icmpv6 -h
711 my $icmpv6_type_names = {
713 'destination-unreachable' => 1,
715 'communication-prohibited' => 1,
716 'address-unreachable' => 1,
717 'port-unreachable' => 1,
718 'packet-too-big' => 1,
719 'time-exceeded' => 1,
720 'ttl-zero-during-transit' => 1,
721 'ttl-zero-during-reassembly' => 1,
722 'parameter-problem' => 1,
724 'unknown-header-type' => 1,
725 'unknown-option' => 1,
728 'router-solicitation' => 1,
729 'router-advertisement' => 1,
730 'neighbour-solicitation' => 1,
731 'neighbour-advertisement' => 1,
735 sub init_firewall_macros
{
737 $pve_fw_parsed_macros = {};
739 foreach my $k (keys %$pve_fw_macros) {
740 my $lc_name = lc($k);
741 my $macro = $pve_fw_macros->{$k};
742 if (!ref($macro->[0])) {
743 $pve_fw_macro_descr->{$k} = shift @$macro;
745 $pve_fw_preferred_macro_names->{$lc_name} = $k;
746 $pve_fw_parsed_macros->{$k} = $macro;
750 init_firewall_macros
();
753 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
758 sub get_etc_services
{
760 return $etc_services if $etc_services;
762 my $filename = "/etc/services";
764 my $fh = IO
::File-
>new($filename, O_RDONLY
);
766 warn "unable to read '$filename' - $!\n";
772 while (my $line = <$fh>) {
774 next if $line =~m/^#/;
775 next if ($line =~m/^\s*$/);
777 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
778 $services->{byid
}->{$2}->{name
} = $1;
779 $services->{byid
}->{$2}->{port
} = $2;
780 $services->{byid
}->{$2}->{$3} = 1;
781 $services->{byname
}->{$1} = $services->{byid
}->{$2};
787 $etc_services = $services;
790 return $etc_services;
795 sub get_etc_protocols
{
796 return $etc_protocols if $etc_protocols;
798 my $filename = "/etc/protocols";
800 my $fh = IO
::File-
>new($filename, O_RDONLY
);
802 warn "unable to read '$filename' - $!\n";
808 while (my $line = <$fh>) {
810 next if $line =~m/^#/;
811 next if ($line =~m/^\s*$/);
813 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
814 $protocols->{byid
}->{$2}->{name
} = $1;
815 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
821 # add special case for ICMP v6
822 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
823 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
825 $etc_protocols = $protocols;
827 return $etc_protocols;
830 my $ipv4_mask_hash_localnet = {
832 '255.255.128.0' => 17,
833 '255.255.192.0' => 18,
834 '255.255.224.0' => 19,
835 '255.255.240.0' => 20,
836 '255.255.248.0' => 21,
837 '255.255.252.0' => 22,
838 '255.255.254.0' => 23,
839 '255.255.255.0' => 24,
840 '255.255.255.128' => 25,
841 '255.255.255.192' => 26,
842 '255.255.255.224' => 27,
843 '255.255.255.240' => 28,
844 '255.255.255.248' => 29,
845 '255.255.255.252' => 30,
851 my ($new_value) = @_;
853 $__local_network = $new_value if defined($new_value);
855 return $__local_network if defined($__local_network);
858 my $nodename = PVE
::INotify
::nodename
();
860 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
862 my $testip = Net
::IP-
>new($ip);
864 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
865 foreach my $entry (@$routes) {
866 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
867 next if !defined($mask);
868 return if $mask eq '0.0.0.0';
869 my $cidr = "$entry->{dest}/$mask";
870 my $testnet = Net
::IP-
>new($cidr);
871 if ($testnet->overlaps($testip)) {
872 $__local_network = $cidr;
879 return $__local_network;
882 # ipset names are limited to 31 characters,
883 # and we use '-v4' or '-v6' to indicate IP versions,
884 # and we use '_swap' suffix for atomic update,
885 # for example PVEFW-${VMID}-${ipset_name}_swap
887 my $max_iptables_ipset_name_length = 31 - length("_swap") - length("-v4");
889 sub compute_ipset_chain_name
{
890 my ($vmid, $ipset_name) = @_;
892 $vmid = 0 if !defined($vmid);
894 my $id = "$vmid-${ipset_name}";
896 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
897 $id = PVE
::Tools
::fnv31a_hex
($id);
903 sub compute_ipfilter_ipset_name
{
906 return "ipfilter-$iface";
909 sub parse_address_list
{
912 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
913 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
917 if ($str =~ m/^${ip_alias_pattern}$/) {
918 die "alias name too long\n" if length($str) > $max_alias_name_length;
926 foreach my $elem (split(/,/, $str)) {
928 my $ip = Net
::IP-
>new($elem);
930 my $err = Net
::IP
::Error
();
931 die "invalid IP address: $err\n";
933 $iprange = 1 if $elem =~ m/-/;
935 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
937 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
938 if $ipversion && ($new_ipversion != $ipversion);
940 $ipversion = $new_ipversion;
943 die "you can't use a range in a list\n" if $iprange && $count > 1;
948 sub parse_port_name_number_or_range
{
951 my $services = PVE
::Firewall
::get_etc_services
();
955 foreach my $item (split(/,/, $str)) {
957 if ($item =~ m/^(\d+):(\d+)$/) {
958 my ($port1, $port2) = ($1, $2);
959 die "invalid port '$port1'\n" if $port1 > 65535;
960 die "invalid port '$port2'\n" if $port2 > 65535;
961 } elsif ($item =~ m/^(\d+)$/) {
963 die "invalid port '$port'\n" if $port > 65535;
965 if ($icmp_type_names->{$item}) {
967 } elsif ($icmpv6_type_names->{$item}) {
970 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
975 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
980 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
981 sub pve_fw_verify_port_spec
{
984 parse_port_name_number_or_range
($portstr);
989 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
990 sub pve_fw_verify_addr_spec
{
993 parse_address_list
($list);
998 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
999 sub pve_fw_verify_protocol_spec
{
1002 my $protocols = get_etc_protocols
();
1004 die "unknown protocol '$proto'\n" if $proto &&
1005 !(defined($protocols->{byname
}->{$proto}) ||
1006 defined($protocols->{byid
}->{$proto}));
1012 # helper function for API
1014 sub copy_opject_with_digest
{
1017 my $sha = Digest
::SHA-
>new('sha1');
1020 foreach my $k (sort keys %$object) {
1021 my $v = $object->{$k};
1022 next if !defined($v);
1024 $sha->add($k, ':', $v, "\n");
1027 my $digest = $sha->hexdigest;
1029 $res->{digest
} = $digest;
1031 return wantarray ?
($res, $digest) : $res;
1034 sub copy_list_with_digest
{
1037 my $sha = Digest
::SHA-
>new('sha1');
1040 foreach my $entry (@$list) {
1042 foreach my $k (sort keys %$entry) {
1043 my $v = $entry->{$k};
1044 next if !defined($v);
1046 # Note: digest ignores refs ($rule->{errors})
1047 $sha->add($k, ':', $v, "\n") if !ref($v); ;
1052 my $digest = $sha->hexdigest;
1054 foreach my $entry (@$res) {
1055 $entry->{digest
} = $digest;
1058 return wantarray ?
($res, $digest) : $res;
1061 my $rule_properties = {
1063 description
=> "Update rule at position <pos>.",
1068 digest
=> get_standard_option
('pve-config-digest'),
1072 enum
=> ['in', 'out', 'group'],
1075 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1078 pattern
=> $security_group_name_pattern,
1087 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
1089 type
=> 'string', format
=> 'pve-fw-addr-spec',
1093 type
=> 'string', format
=> 'pve-fw-addr-spec',
1097 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1105 type
=> 'string', format
=> 'pve-fw-port-spec',
1109 type
=> 'string', format
=> 'pve-fw-port-spec',
1118 sub add_rule_properties
{
1119 my ($properties) = @_;
1121 foreach my $k (keys %$rule_properties) {
1122 my $h = $rule_properties->{$k};
1123 # copy data, so that we can modify later without side effects
1124 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1130 sub delete_rule_properties
{
1131 my ($rule, $delete_str) = @_;
1133 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1134 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1135 if !defined($rule_properties->{$opt});
1136 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1137 if $opt eq 'type' || $opt eq 'action';
1138 delete $rule->{$opt};
1144 my $apply_macro = sub {
1145 my ($macro_name, $param, $verify) = @_;
1147 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1148 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1152 foreach my $templ (@$macro_rules) {
1154 my $param_used = {};
1155 foreach my $k (keys %$templ) {
1156 my $v = $templ->{$k};
1157 if ($v eq 'PARAM') {
1159 $param_used->{$k} = 1;
1160 } elsif ($v eq 'DEST') {
1161 $v = $param->{dest
};
1162 $param_used->{dest
} = 1;
1163 } elsif ($v eq 'SOURCE') {
1164 $v = $param->{source
};
1165 $param_used->{source
} = 1;
1169 my $msg = "missing parameter '$k' in macro '$macro_name'";
1170 raise_param_exc
({ macro => $msg }) if $verify;
1175 foreach my $k (keys %$param) {
1176 next if $k eq 'macro';
1177 next if !defined($param->{$k});
1178 next if $param_used->{$k};
1179 if (defined($rule->{$k})) {
1180 if ($rule->{$k} ne $param->{$k}) {
1181 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1182 raise_param_exc
({ $k => $msg }) if $verify;
1186 $rule->{$k} = $param->{$k};
1189 push @$rules, $rule;
1195 my $rule_env_iface_lookup = {
1204 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1206 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1208 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1209 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1211 my $errors = $rule->{errors
} || {};
1213 my $error_count = 0;
1215 my $add_error = sub {
1216 my ($param, $msg) = @_;
1218 raise_param_exc
({ $param => $msg }) if !$noerr;
1220 $errors->{$param} = $msg if !$errors->{$param};
1223 my $check_ipset_or_alias_property = sub {
1224 my ($name, $expected_ipversion) = @_;
1226 if (my $value = $rule->{$name}) {
1227 if ($value =~ m/^\+/) {
1228 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1229 &$add_error($name, "no such ipset '$1'")
1230 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1233 &$add_error($name, "invalid ipset name '$value'");
1235 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1236 my $alias = lc($value);
1237 &$add_error($name, "no such alias '$value'")
1238 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1240 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1241 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1243 die "detected mixed ipv4/ipv6 adresses in rule\n"
1244 if $expected_ipversion && ($expected_ipversion != $e->{ipversion
});
1249 my $type = $rule->{type
};
1250 my $action = $rule->{action
};
1252 &$add_error('type', "missing property") if !$type;
1253 &$add_error('action', "missing property") if !$action;
1256 if ($type eq 'in' || $type eq 'out') {
1257 &$add_error('action', "unknown action '$action'")
1258 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1259 } elsif ($type eq 'group') {
1260 &$add_error('type', "security groups not allowed")
1262 &$add_error('action', "invalid characters in security group name")
1263 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1265 &$add_error('type', "unknown rule type '$type'");
1269 if ($rule->{iface
}) {
1270 &$add_error('type', "parameter -i not allowed for this rule type")
1272 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1273 &$add_error('iface', $@) if $@;
1274 if ($rule_env eq 'vm') {
1275 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1276 if $rule->{iface
} !~ m/^net(\d+)$/;
1277 } elsif ($rule_env eq 'ct') {
1278 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1279 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1283 if ($rule->{macro}) {
1284 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1285 $rule->{macro} = $preferred_name;
1287 &$add_error('macro', "unknown macro '$rule->{macro}'");
1292 my $set_ip_version = sub {
1295 die "detected mixed ipv4/ipv6 adresses in rule\n"
1296 if $ipversion && ($vers != $ipversion);
1301 if ($rule->{proto
}) {
1302 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1303 &$add_error('proto', $@) if $@;
1304 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1305 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1308 if ($rule->{dport
}) {
1309 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1310 &$add_error('dport', $@) if $@;
1311 &$add_error('proto', "missing property - 'dport' requires this property")
1315 if ($rule->{sport
}) {
1316 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1317 &$add_error('sport', $@) if $@;
1318 &$add_error('proto', "missing property - 'sport' requires this property")
1322 if ($rule->{source
}) {
1324 my $source_ipversion = parse_address_list
($rule->{source
});
1325 &$set_ip_version($source_ipversion);
1327 &$add_error('source', $@) if $@;
1328 &$check_ipset_or_alias_property('source', $ipversion);
1331 if ($rule->{dest
}) {
1333 my $dest_ipversion = parse_address_list
($rule->{dest
});
1334 &$set_ip_version($dest_ipversion);
1336 &$add_error('dest', $@) if $@;
1337 &$check_ipset_or_alias_property('dest', $ipversion);
1340 if ($rule->{macro} && !$error_count) {
1341 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1343 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1344 my $eh = $err->{errors
};
1345 foreach my $p (keys %$eh) {
1346 &$add_error($p, $eh->{$p});
1349 &$add_error('macro', "$err");
1354 $rule->{errors
} = $errors if $error_count;
1355 $rule->{ipversion
} = $ipversion if $ipversion;
1360 sub copy_rule_data
{
1361 my ($rule, $param) = @_;
1363 foreach my $k (keys %$rule_properties) {
1364 if (defined(my $v = $param->{$k})) {
1365 if ($v eq '' || $v eq '-') {
1376 sub rules_modify_permissions
{
1377 my ($rule_env) = @_;
1379 if ($rule_env eq 'host') {
1381 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1383 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1385 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1387 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1389 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1396 sub rules_audit_permissions
{
1397 my ($rule_env) = @_;
1399 if ($rule_env eq 'host') {
1401 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1403 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1405 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1407 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1409 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1417 my $bridge_firewall_enabled = 0;
1419 sub enable_bridge_firewall
{
1421 return if $bridge_firewall_enabled; # only once
1423 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1424 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1426 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1427 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1429 $bridge_firewall_enabled = 1;
1432 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1434 sub iptables_restore_cmdlist
{
1437 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1440 sub ip6tables_restore_cmdlist
{
1443 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist);
1446 sub ipset_restore_cmdlist
{
1449 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1452 sub iptables_get_chains
{
1453 my ($iptablescmd) = @_;
1455 $iptablescmd = "iptables" if !$iptablescmd;
1459 # check what chains we want to track
1460 my $is_pvefw_chain = sub {
1463 return 1 if $name =~ m/^PVEFW-\S+$/;
1465 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1467 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1469 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1471 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1472 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1484 return if $line =~ m/^#/;
1485 return if $line =~ m/^\s*$/;
1487 if ($line =~ m/^\*(\S+)$/) {
1492 return if $table ne 'filter';
1494 if ($line =~ m/^:(\S+)\s/) {
1496 return if !&$is_pvefw_chain($chain);
1497 $res->{$chain} = "unknown";
1498 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1499 my ($chain, $sig) = ($1, $2);
1500 return if !&$is_pvefw_chain($chain);
1501 $res->{$chain} = $sig;
1502 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1505 # simply ignore the rest
1510 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1512 return wantarray ?
($res, $hooks) : $res;
1515 sub iptables_chain_digest
{
1517 my $digest = Digest
::SHA-
>new('sha1');
1518 foreach my $rule (@$rules) { # order is important
1519 $digest->add($rule);
1521 return $digest->b64digest;
1524 sub ipset_chain_digest
{
1527 my $digest = Digest
::SHA-
>new('sha1');
1528 foreach my $rule (sort @$rules) { # note: sorted
1529 $digest->add($rule);
1531 return $digest->b64digest;
1534 sub ipset_get_chains
{
1542 return if $line =~ m/^#/;
1543 return if $line =~ m/^\s*$/;
1544 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1546 $line =~ s/\s+$//; # delete trailing white space
1547 push @{$chains->{$chain}}, $line;
1549 # simply ignore the rest
1554 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1556 # compute digest for each chain
1557 foreach my $chain (keys %$chains) {
1558 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1564 sub ruleset_generate_cmdstr
{
1565 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1567 return if defined($rule->{enable
}) && !$rule->{enable
};
1568 return if $rule->{errors
};
1570 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1572 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1573 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1577 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1578 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1580 my $source = $rule->{source
};
1581 my $dest = $rule->{dest
};
1584 if ($source =~ m/^\+/) {
1585 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1587 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1588 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1589 push @cmd, "-m set --match-set ${ipset_chain} src";
1590 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1591 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1592 push @cmd, "-m set --match-set ${ipset_chain} src";
1594 die "no such ipset '$name'\n";
1597 die "invalid security group name '$source'\n";
1599 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1600 my $alias = lc($source);
1601 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1602 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1603 die "no such alias '$source'\n" if !$e;
1604 push @cmd, "-s $e->{cidr}";
1605 } elsif ($source =~ m/\-/){
1606 push @cmd, "-m iprange --src-range $source";
1608 push @cmd, "-s $source";
1613 if ($dest =~ m/^\+/) {
1614 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1616 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1617 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1618 push @cmd, "-m set --match-set ${ipset_chain} dst";
1619 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1620 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1621 push @cmd, "-m set --match-set ${ipset_chain} dst";
1623 die "no such ipset '$name'\n";
1626 die "invalid security group name '$dest'\n";
1628 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1629 my $alias = lc($dest);
1630 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1631 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1632 die "no such alias '$dest'\n" if !$e;
1633 push @cmd, "-d $e->{cidr}";
1634 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1635 push @cmd, "-m iprange --dst-range $dest";
1637 push @cmd, "-d $dest";
1641 if ($rule->{proto
}) {
1642 push @cmd, "-p $rule->{proto}";
1645 $multiport++ if $nbdport > 1;
1646 $multiport++ if $nbsport > 1;
1648 push @cmd, "--match multiport" if $multiport;
1650 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1651 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1653 if ($rule->{dport
}) {
1654 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1655 # Note: we use dport to store --icmp-type
1656 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1657 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1658 } elsif ($rule->{proto
} && $rule->{proto
} eq 'icmpv6') {
1659 # Note: we use dport to store --icmpv6-type
1660 die "unknown icmpv6-type '$rule->{dport}'\n" if !defined($icmpv6_type_names->{$rule->{dport
}});
1661 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1664 if ($multiport == 2) {
1665 push @cmd, "--ports $rule->{dport}";
1667 push @cmd, "--dports $rule->{dport}";
1670 push @cmd, "--dport $rule->{dport}";
1675 if ($rule->{sport
}) {
1677 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1679 push @cmd, "--sport $rule->{sport}";
1682 } elsif ($rule->{dport
} || $rule->{sport
}) {
1683 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1684 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1687 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1689 if (my $action = $rule->{action
}) {
1690 $action = $actions->{$action} if defined($actions->{$action});
1691 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1692 push @cmd, $goto ?
"-g $action" : "-j $action";
1695 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1698 sub ruleset_generate_rule
{
1699 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1703 if ($rule->{macro}) {
1704 $rules = &$apply_macro($rule->{macro}, $rule);
1709 # update all or nothing
1712 foreach my $tmp (@$rules) {
1713 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1714 push @cmds, $cmdstr;
1718 foreach my $cmdstr (@cmds) {
1719 ruleset_addrule
($ruleset, $chain, $cmdstr);
1723 sub ruleset_generate_rule_insert
{
1724 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1726 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1728 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1729 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1733 sub ruleset_create_chain
{
1734 my ($ruleset, $chain) = @_;
1736 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1737 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1739 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1741 $ruleset->{$chain} = [];
1744 sub ruleset_chain_exist
{
1745 my ($ruleset, $chain) = @_;
1747 return $ruleset->{$chain} ?
1 : undef;
1750 sub ruleset_addrule
{
1751 my ($ruleset, $chain, $rule) = @_;
1753 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1755 push @{$ruleset->{$chain}}, "-A $chain $rule";
1758 sub ruleset_insertrule
{
1759 my ($ruleset, $chain, $rule) = @_;
1761 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1763 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1766 sub get_log_rule_base
{
1767 my ($chain, $vmid, $msg, $loglevel) = @_;
1769 die "internal error - no log level" if !defined($loglevel);
1771 $vmid = 0 if !defined($vmid);
1773 # Note: we use special format for prefix to pass further
1774 # info to log daemon (VMID, LOGVELEL and CHAIN)
1776 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1779 sub ruleset_addlog {
1780 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1782 return if !defined($loglevel);
1784 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1786 $logrule = "$rule $logrule" if defined($rule);
1788 ruleset_addrule($ruleset, $chain, $logrule);
1791 sub ruleset_add_chain_policy {
1792 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1794 if ($policy eq 'ACCEPT') {
1796 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1797 { ACCEPT => $accept_action});
1799 } elsif ($policy eq 'DROP') {
1801 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1803 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1805 ruleset_addrule($ruleset, $chain, "-j DROP
");
1806 } elsif ($policy eq 'REJECT') {
1807 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1809 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1811 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1814 die "internal error
: unknown policy
'$policy'";
1818 sub ruleset_chain_add_conn_filters {
1819 my ($ruleset, $chain, $accept) = @_;
1821 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1822 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1825 sub ruleset_chain_add_input_filters {
1826 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1828 if ($cluster_conf->{ipset}->{blacklist}){
1829 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1830 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1831 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1832 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1834 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1835 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1838 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1839 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1842 if ($options->{tcpflags}) {
1843 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1847 sub ruleset_create_vm_chain {
1848 my ($ruleset, $chain, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1850 ruleset_create_chain($ruleset, $chain);
1851 my $accept = generate_nfqueue($options);
1853 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1854 if ($direction eq 'OUT') {
1855 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1856 proto => 'udp', sport => 68, dport => 67 });
1858 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1859 proto => 'udp', sport => 67, dport => 68 });
1863 if ($direction eq 'OUT') {
1864 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1865 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1867 if ($ipfilter_ipset) {
1868 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
1870 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1874 sub ruleset_add_group_rule {
1875 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1877 my $group = $rule->{action};
1878 my $group_chain = "GROUP-
$group-$direction";
1879 if(!ruleset_chain_exist($ruleset, $group_chain)){
1880 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1883 if ($direction eq 'OUT' && $rule->{iface_out}) {
1884 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1885 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1886 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1888 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1891 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1894 sub ruleset_generate_vm_rules {
1895 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
1897 my $lc_direction = lc($direction);
1899 my $in_accept = generate_nfqueue($options);
1901 foreach my $rule (@$rules) {
1902 next if $rule->{iface} && $rule->{iface} ne $netid;
1903 next if !$rule->{enable} || $rule->{errors};
1904 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
1906 if ($rule->{type} eq 'group') {
1907 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1908 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
1910 next if $rule->{type} ne $lc_direction;
1912 if ($direction eq 'OUT') {
1913 ruleset_generate_rule($ruleset, $chain, $rule,
1914 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1915 undef, $cluster_conf, $vmfw_conf);
1917 ruleset_generate_rule($ruleset, $chain, $rule,
1918 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1919 undef, $cluster_conf, $vmfw_conf);
1927 sub generate_nfqueue {
1930 if ($options->{ips}) {
1931 my $action = "NFQUEUE
";
1932 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1933 if (defined($3) && defined($1)) {
1934 $action .= " --queue-balance
$1:$3";
1935 } elsif (defined($1)) {
1936 $action .= " --queue-num
$1";
1939 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1946 sub ruleset_generate_vm_ipsrules {
1947 my ($ruleset, $options, $direction, $iface) = @_;
1949 if ($options->{ips} && $direction eq 'IN') {
1950 my $nfqueue = generate_nfqueue($options);
1952 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1953 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1956 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1960 sub generate_venet_rules_direction {
1961 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction, $ipversion) = @_;
1963 my $lc_direction = lc($direction);
1965 my $rules = $vmfw_conf->{rules};
1967 my $options = $vmfw_conf->{options};
1968 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1970 my $chain = "venet0-
$vmid-$direction";
1972 ruleset_create_vm_chain($ruleset, $chain, $options, undef, undef, $direction);
1974 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction, undef, $ipversion);
1979 if ($direction eq 'OUT') {
1980 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1982 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1985 my $accept = generate_nfqueue($options);
1986 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1987 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1989 if ($direction eq 'OUT') {
1990 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1993 iface_in => 'venet0'});
1995 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1998 iface_out => 'venet0'});
2002 sub generate_tap_rules_direction {
2003 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2005 my $lc_direction = lc($direction);
2007 my $rules = $vmfw_conf->{rules};
2009 my $options = $vmfw_conf->{options};
2010 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2012 my $tapchain = "$iface-$direction";
2014 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2015 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name)
2016 if $vmfw_conf->{ipset}->{$ipfilter_name};
2018 # create chain with mac and ip filter
2019 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $ipfilter_ipset, $direction);
2021 if ($options->{enable}) {
2022 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2024 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2029 if ($direction eq 'OUT') {
2030 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2032 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2035 my $accept = generate_nfqueue($options);
2036 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2037 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
2039 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2040 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, 'ACCEPT', $loglevel, $accept_action);
2043 # plug the tap chain to bridge chain
2044 if ($direction eq 'IN') {
2045 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2046 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2048 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2049 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2053 sub enable_host_firewall {
2054 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2056 my $options = $hostfw_conf->{options};
2057 my $cluster_options = $cluster_conf->{options};
2058 my $rules = $hostfw_conf->{rules};
2059 my $cluster_rules = $cluster_conf->{rules};
2061 # host inbound firewall
2062 my $chain = "PVEFW-HOST-IN
";
2063 ruleset_create_chain($ruleset, $chain);
2065 my $loglevel = get_option_log_level($options, "log_level_in
");
2067 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2069 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2070 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
2072 # we use RETURN because we need to check also tap rules
2073 my $accept_action = 'RETURN';
2075 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2077 # add host rules first, so that cluster wide rules can be overwritten
2078 foreach my $rule (@$rules, @$cluster_rules) {
2079 next if !$rule->{enable} || $rule->{errors};
2081 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2084 if ($rule->{type} eq 'group') {
2085 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2086 } elsif ($rule->{type} eq 'in') {
2087 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2088 undef, $cluster_conf, $hostfw_conf);
2092 delete $rule->{iface_in};
2095 # allow standard traffic for management ipset (includes cluster network)
2096 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
");
2097 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2098 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2099 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2100 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2101 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2103 my $localnet = local_network();
2107 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2108 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2109 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2112 # implement input policy
2113 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2114 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
2116 # host outbound firewall
2117 $chain = "PVEFW-HOST-OUT
";
2118 ruleset_create_chain($ruleset, $chain);
2120 $loglevel = get_option_log_level($options, "log_level_out
");
2122 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2124 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2126 # we use RETURN because we may want to check other thigs later
2127 $accept_action = 'RETURN';
2129 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2131 # add host rules first, so that cluster wide rules can be overwritten
2132 foreach my $rule (@$rules, @$cluster_rules) {
2133 next if !$rule->{enable} || $rule->{errors};
2135 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2137 if ($rule->{type} eq 'group') {
2138 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2139 } elsif ($rule->{type} eq 'out') {
2140 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2141 undef, $cluster_conf, $hostfw_conf);
2145 delete $rule->{iface_out};
2148 # allow standard traffic on cluster network
2150 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2151 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2152 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2153 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2155 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2156 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2157 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2160 # implement output policy
2161 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2162 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
2164 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2165 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2168 sub generate_group_rules {
2169 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2171 my $rules = $cluster_conf->{groups}->{$group};
2174 warn "no such security group
'$group'\n";
2175 $rules = []; # create empty chain
2178 my $chain = "GROUP-
${group
}-IN
";
2180 ruleset_create_chain($ruleset, $chain);
2181 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2183 foreach my $rule (@$rules) {
2184 next if $rule->{type} ne 'in';
2185 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2186 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
2189 $chain = "GROUP-
${group
}-OUT
";
2191 ruleset_create_chain($ruleset, $chain);
2192 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2194 foreach my $rule (@$rules) {
2195 next if $rule->{type} ne 'out';
2196 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2197 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2198 # check also other tap rules later
2199 ruleset_generate_rule($ruleset, $chain, $rule,
2200 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
2205 my $valid_netdev_names = {};
2206 for (my $i = 0; $i < $MAX_NETS; $i++) {
2207 $valid_netdev_names->{"net
$i"} = 1;
2211 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2213 my $orig_line = $line;
2217 # we can add single line comments to the end of the rule
2218 if ($line =~ s/#\s*(.*?)\s*$//) {
2219 $rule->{comment} = decode('utf8', $1);
2222 # we can disable a rule when prefixed with '|'
2224 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2226 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2227 die "unable to parse rule
: $line\n";
2229 $rule->{type} = lc($1);
2230 $rule->{action} = $2;
2232 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2233 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2234 $rule->{macro} = $1;
2235 $rule->{action} = $2;
2239 while (length($line)) {
2240 if ($line =~ s/^-i (\S+)\s*//) {
2241 $rule->{iface} = $1;
2245 last if $rule->{type} eq 'group';
2247 if ($line =~ s/^-p (\S+)\s*//) {
2248 $rule->{proto} = $1;
2252 if ($line =~ s/^-dport (\S+)\s*//) {
2253 $rule->{dport} = $1;
2257 if ($line =~ s/^-sport (\S+)\s*//) {
2258 $rule->{sport} = $1;
2261 if ($line =~ s/^-source (\S+)\s*//) {
2262 $rule->{source} = $1;
2265 if ($line =~ s/^-dest (\S+)\s*//) {
2273 die "unable to parse rule parameters
: $line\n" if length($line);
2275 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2276 if ($verbose && $rule->{errors}) {
2277 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2278 foreach my $p (keys %{$rule->{errors}}) {
2279 warn " $p: $rule->{errors
}->{$p}\n";
2286 sub parse_vmfw_option {
2291 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2293 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2296 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2298 $value = $2 ? lc($3) : '';
2299 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2302 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2306 die "can
't parse option '$line'\n"
2309 return ($opt, $value);
2312 sub parse_hostfw_option {
2317 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2319 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2322 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2324 $value = $2 ? lc($3) : '';
2325 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2329 die "can't parse option
'$line'\n"
2332 return ($opt, $value);
2335 sub parse_clusterfw_option {
2340 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2343 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2347 die "can
't parse option '$line'\n"
2350 return ($opt, $value);
2354 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2356 my $alias = lc($cidr);
2357 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2358 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2360 die "no such alias '$cidr'\n" if !$e;;
2362 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2365 sub parse_ip_or_cidr {
2370 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2373 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2377 die "value does not look like a valid IP address or CIDR network\n";
2380 return wantarray ? ($cidr, $ipversion) : $cidr;
2386 # we can add single line comments to the end of the line
2387 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2389 if ($line =~ m/^(\S+)\s(\S+)$/) {
2390 my ($name, $cidr) = ($1, $2);
2393 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2398 ipversion => $ipversion,
2400 $data->{comment} = $comment if $comment;
2407 sub generic_fw_config_parser {
2408 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2413 my $res = $empty_conf;
2415 while (defined(my $line = <$fh>)) {
2416 next if $line =~ m/^#/;
2417 next if $line =~ m/^\s*$/;
2421 my $linenr = $fh->input_line_number();
2422 my $prefix = "$filename (line $linenr)";
2424 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2425 $section = 'options
';
2429 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2430 $section = 'aliases
';
2434 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2435 $section = 'groups
';
2439 die "security group name too long\n" if length($group) > $max_group_name_length;
2440 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2443 ($section, $group, $comment) = undef;
2444 warn "$prefix: $err";
2448 $res->{$section}->{$group} = [];
2449 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2454 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2459 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2464 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2465 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2468 ($section, $group, $comment) = undef;
2469 warn "$prefix: $err";
2473 $res->{$section}->{$group} = [];
2474 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2480 warn "$prefix: skip line - no section\n";
2484 if ($section eq 'options
') {
2487 if ($rule_env eq 'cluster
') {
2488 ($opt, $value) = parse_clusterfw_option($line);
2489 } elsif ($rule_env eq 'host
') {
2490 ($opt, $value) = parse_hostfw_option($line);
2492 ($opt, $value) = parse_vmfw_option($line);
2494 $res->{options}->{$opt} = $value;
2496 warn "$prefix: $@" if $@;
2497 } elsif ($section eq 'aliases
') {
2499 my $data = parse_alias($line);
2500 $res->{aliases}->{lc($data->{name})} = $data;
2502 warn "$prefix: $@" if $@;
2503 } elsif ($section eq 'rules
') {
2505 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2507 warn "$prefix: $err";
2510 push @{$res->{$section}}, $rule;
2511 } elsif ($section eq 'groups
') {
2513 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2515 warn "$prefix: $err";
2518 push @{$res->{$section}->{$group}}, $rule;
2519 } elsif ($section eq 'ipset
') {
2520 # we can add single line comments to the end of the rule
2521 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2523 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2528 if ($nomatch && !$feature_ipset_nomatch) {
2529 $errors->{nomatch} = "nomatch not supported by kernel";
2533 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2534 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2536 $cidr = parse_ip_or_cidr($cidr);
2541 $errors->{cidr} = $err;
2544 my $entry = { cidr => $cidr };
2545 $entry->{nomatch} = 1 if $nomatch;
2546 $entry->{comment} = $comment if $comment;
2547 $entry->{errors} = $errors if $errors;
2549 if ($verbose && $errors) {
2550 warn "$prefix - errors in ipset '$group': $line\n";
2551 foreach my $p (keys %{$errors}) {
2552 warn " $p: $errors->{$p}\n";
2556 push @{$res->{$section}->{$group}}, $entry;
2558 warn "$prefix: skip line - unknown section\n";
2566 sub parse_hostfw_config {
2567 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2569 my $empty_conf = { rules => [], options => {}};
2571 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2574 sub parse_vmfw_config {
2575 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2582 ipset_comments => {},
2585 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2588 sub parse_clusterfw_config {
2589 my ($filename, $fh, $verbose) = @_;
2599 group_comments => {},
2601 ipset_comments => {},
2604 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2608 my ($code, @param) = @_;
2612 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2619 sub read_local_vm_config {
2624 my $vmdata = { openvz => $openvz, qemu => $qemu };
2626 my $vmlist = PVE::Cluster::get_vmlist();
2627 return $vmdata if !$vmlist || !$vmlist->{ids};
2628 my $ids = $vmlist->{ids};
2630 foreach my $vmid (keys %$ids) {
2631 next if !$vmid; # skip VE0
2632 my $d = $ids->{$vmid};
2633 next if !$d->{node} || $d->{node} ne $nodename;
2634 next if !$d->{type};
2635 if ($d->{type} eq 'openvz
') {
2636 if ($have_pve_manager) {
2637 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2638 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2639 $openvz->{$vmid} = $conf;
2642 } elsif ($d->{type} eq 'qemu
') {
2643 if ($have_qemu_server) {
2644 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2645 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2646 $qemu->{$vmid} = $conf;
2655 sub load_vmfw_conf {
2656 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2660 $dir = $pvefw_conf_dir if !defined($dir);
2662 my $filename = "$dir/$vmid.fw";
2663 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2664 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2665 $vmfw_conf->{vmid} = $vmid;
2671 my $format_rules = sub {
2672 my ($rules, $allow_iface) = @_;
2676 foreach my $rule (@$rules) {
2677 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2678 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2679 $raw .= uc($rule->{type});
2680 if ($rule->{macro}) {
2681 $raw .= " $rule->{macro}($rule->{action})";
2683 $raw .= " " . $rule->{action};
2685 if ($allow_iface && $rule->{iface}) {
2686 $raw .= " -i $rule->{iface}";
2689 if ($rule->{type} ne 'group
') {
2690 $raw .= " -source $rule->{source}" if $rule->{source};
2691 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2692 $raw .= " -p $rule->{proto}" if $rule->{proto};
2693 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2694 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2697 $raw .= " # " . encode('utf8
', $rule->{comment})
2698 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2701 die "unknown rule type '$rule->{type
}'";
2708 my $format_options = sub {
2713 $raw .= "[OPTIONS]\n\n";
2714 foreach my $opt (keys %$options) {
2715 $raw .= "$opt: $options->{$opt}\n";
2722 my $format_aliases = sub {
2727 $raw .= "[ALIASES]\n\n";
2728 foreach my $k (keys %$aliases) {
2729 my $e = $aliases->{$k};
2730 $raw .= "$e->{name} $e->{cidr}";
2731 $raw .= " # " . encode('utf8
', $e->{comment})
2732 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2740 my $format_ipsets = sub {
2745 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2746 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2747 my $utf8comment = encode('utf8
', $comment);
2748 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2750 $raw .= "[IPSET $ipset]\n\n";
2752 my $options = $fw_conf->{ipset}->{$ipset};
2755 foreach my $entry (@$options) {
2756 $nethash->{$entry->{cidr}} = $entry;
2759 foreach my $cidr (sort keys %$nethash) {
2760 my $entry = $nethash->{$cidr};
2761 my $line = $entry->{nomatch} ? '!' : '';
2762 $line .= $entry->{cidr};
2763 $line .= " # " . encode('utf8
', $entry->{comment})
2764 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2774 sub save_vmfw_conf {
2775 my ($vmid, $vmfw_conf) = @_;
2779 my $options = $vmfw_conf->{options};
2780 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2782 my $aliases = $vmfw_conf->{aliases};
2783 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2785 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2787 my $rules = $vmfw_conf->{rules} || [];
2788 if ($rules && scalar(@$rules)) {
2789 $raw .= "[RULES]\n\n";
2790 $raw .= &$format_rules($rules, 1);
2794 mkdir $pvefw_conf_dir;
2796 my $filename = "$pvefw_conf_dir/$vmid.fw";
2797 PVE::Tools::file_set_contents($filename, $raw);
2800 sub read_vm_firewall_configs {
2801 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2803 my $vmfw_configs = {};
2805 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2806 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2807 next if !$vmfw_conf->{options}; # skip if file does not exists
2808 $vmfw_configs->{$vmid} = $vmfw_conf;
2810 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2811 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2812 next if !$vmfw_conf->{options}; # skip if file does not exists
2813 $vmfw_configs->{$vmid} = $vmfw_conf;
2816 return $vmfw_configs;
2819 sub get_option_log_level {
2820 my ($options, $k) = @_;
2822 my $v = $options->{$k};
2823 $v = $default_log_level if !defined($v);
2825 return undef if $v eq '' || $v eq 'nolog
';
2827 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2829 return $v if ($v >= 0) && ($v <= 7);
2831 warn "unknown log level ($k = '$v')\n";
2836 sub generate_std_chains {
2837 my ($ruleset, $options, $ipversion) = @_;
2839 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2841 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2845 if ($ipversion == 4) {
2846 # same as shorewall smurflog.
2847 $chain = 'PVEFW-smurflog
';
2848 $std_chains->{$chain} = [];
2850 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2851 push @{$std_chains->{$chain}}, "-j DROP";
2854 # same as shorewall logflags action.
2855 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2856 $chain = 'PVEFW-logflags
';
2857 $std_chains->{$chain} = [];
2859 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2860 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2861 push @{$std_chains->{$chain}}, "-j DROP";
2863 foreach my $chain (keys %$std_chains) {
2864 ruleset_create_chain($ruleset, $chain);
2865 foreach my $rule (@{$std_chains->{$chain}}) {
2867 ruleset_generate_rule($ruleset, $chain, $rule);
2869 ruleset_addrule($ruleset, $chain, $rule);
2875 sub generate_ipset_chains {
2876 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2878 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2879 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2880 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2884 sub generate_ipset {
2885 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2887 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2889 $ipset_ruleset->{$name} = ["create $name list:set size 4"];
2893 foreach my $entry (@$options) {
2894 next if $entry->{errors}; # skip entries with errors
2896 my ($cidr, $ipversion);
2897 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2898 ($cidr, $ipversion) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2900 ($cidr, $ipversion) = parse_ip_or_cidr($entry->{cidr});
2902 #http://backreference.org/2013/03/01/ipv6-address-normalization/
2903 if ($ipversion == 6) {
2904 my $ipv6 = inet_pton(AF_INET6, lc($cidr));
2905 $cidr = inet_ntop(AF_INET6, $ipv6);
2911 $nethash->{$ipversion}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2916 foreach my $ipversion (sort keys %$nethash) {
2917 my $data = $nethash->{$ipversion};
2918 my $subname = "$name-v$ipversion";
2920 my $hashsize = scalar(@$options);
2921 if ($hashsize <= 64) {
2924 $hashsize = round_powerof2($hashsize);
2927 my $family = $ipversion == "6" ? "inet6" : "inet";
2929 $ipset_ruleset->{$subname} = ["create $subname hash:net family $family hashsize $hashsize maxelem $hashsize"];
2931 foreach my $cidr (sort keys %$data) {
2932 my $entry = $data->{$cidr};
2934 my $cmd = "add $subname $cidr";
2935 if ($entry->{nomatch}) {
2936 if ($feature_ipset_nomatch) {
2937 push @{$ipset_ruleset->{$subname}}, "$cmd nomatch";
2939 warn "ignore !$cidr - nomatch not supported by kernel\n";
2942 push @{$ipset_ruleset->{$subname}}, $cmd;
2946 push @{$ipset_ruleset->{$name}}, "add $name $subname";
2950 sub round_powerof2 {
2954 $int |= $int >> $_ foreach (1,2,4,8,16);
2958 sub load_clusterfw_conf {
2959 my ($filename, $verbose) = @_;
2961 $filename = $clusterfw_conf_filename if !defined($filename);
2963 my $cluster_conf = {};
2964 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2965 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
2968 return $cluster_conf;
2971 sub save_clusterfw_conf {
2972 my ($cluster_conf) = @_;
2976 my $options = $cluster_conf->{options};
2977 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2979 my $aliases = $cluster_conf->{aliases};
2980 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2982 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
2984 my $rules = $cluster_conf->{rules};
2985 if ($rules && scalar(@$rules)) {
2986 $raw .= "[RULES]\n\n";
2987 $raw .= &$format_rules($rules, 1);
2991 if ($cluster_conf->{groups}) {
2992 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2993 my $rules = $cluster_conf->{groups}->{$group};
2994 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2995 my $utf8comment = encode('utf8
', $comment);
2996 $raw .= "[group $group] # $utf8comment\n\n";
2998 $raw .= "[group $group]\n\n";
3001 $raw .= &$format_rules($rules, 0);
3006 mkdir $pvefw_conf_dir;
3007 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3010 sub load_hostfw_conf {
3011 my ($cluster_conf, $filename, $verbose) = @_;
3013 $filename = $hostfw_conf_filename if !defined($filename);
3015 my $hostfw_conf = {};
3016 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3017 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3019 return $hostfw_conf;
3022 sub save_hostfw_conf {
3023 my ($hostfw_conf) = @_;
3027 my $options = $hostfw_conf->{options};
3028 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3030 my $rules = $hostfw_conf->{rules};
3031 if ($rules && scalar(@$rules)) {
3032 $raw .= "[RULES]\n\n";
3033 $raw .= &$format_rules($rules, 1);
3037 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3041 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3045 if ($vmdata) { # test mode
3046 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3047 my $filename = "$testdir/cluster.fw";
3048 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3050 $filename = "$testdir/host.fw";
3051 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3053 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3054 } else { # normal operation
3055 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3057 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3059 $vmdata = read_local_vm_config();
3060 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3063 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3064 my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3066 return ($ruleset, $ipset_ruleset, $rulesetv6);
3069 sub compile_iptables_filter {
3070 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3072 $cluster_conf->{ipset}->{venet0} = [];
3073 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
3076 if ($cluster_conf->{aliases}->{local_network}) {
3077 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3079 $localnet = local_network() || '127.0.0.0/8';
3080 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
3083 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3085 return ({}, {}) if !$cluster_conf->{options}->{enable};
3089 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3090 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3092 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3094 my $hostfw_options = $hostfw_conf->{options} || {};
3096 # fixme: what log level should we use here?
3097 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3099 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3102 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
3103 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3104 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3106 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3107 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
3109 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3111 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3112 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3114 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
3115 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
3117 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3119 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3121 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3123 my $ipset_ruleset = {};
3125 # currently pveproxy don't works with ipv6
, so let
's generate host fw ipv4 only for the moment
3126 if ($hostfw_enable && ($ipversion == 4)) {
3127 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3128 warn $@ if $@; # just to be sure - should not happen
3131 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3133 # generate firewall rules for QEMU VMs
3134 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3136 my $conf = $vmdata->{qemu}->{$vmid};
3137 my $vmfw_conf = $vmfw_configs->{$vmid};
3138 return if !$vmfw_conf;
3140 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3142 foreach my $netid (keys %$conf) {
3143 next if $netid !~ m/^net(\d+)$/;
3144 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3145 next if !$net->{firewall};
3146 my $iface = "tap${vmid}i$1";
3148 my $macaddr = $net->{macaddr};
3149 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3150 $vmfw_conf, $vmid, 'IN
', $ipversion);
3151 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3152 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3155 warn $@ if $@; # just to be sure - should not happen
3158 # generate firewall rules for OpenVZ containers
3159 foreach my $vmid (keys %{$vmdata->{openvz}}) {
3161 my $conf = $vmdata->{openvz}->{$vmid};
3163 my $vmfw_conf = $vmfw_configs->{$vmid};
3164 return if !$vmfw_conf;
3166 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3168 if ($vmfw_conf->{options}->{enable}) {
3169 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
3170 my $ip = $conf->{ip_address}->{value};
3175 foreach my $singleip (split(',', $ip)) {
3176 my $singleip_ver = parse_address_list($singleip); # make sure we have a valid $ip list
3177 push @{$cluster_conf->{ipset}->{venet0}}, { cidr => $singleip };
3178 push @ips, $singleip if $singleip_ver == $ipversion;
3182 my $ip_list = join(',', @ips);
3183 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'IN
', $ipversion);
3184 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'OUT
', $ipversion);
3189 if ($conf->{netif} && $conf->{netif}->{value}) {
3190 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
3191 foreach my $netid (keys %$netif) {
3192 my $d = $netif->{$netid};
3193 my $bridge = $d->{bridge};
3194 next if !$bridge || $bridge !~ m/^vmbr\d+(v(\d+))?f$/; # firewall enabled ?
3195 my $macaddr = $d->{mac};
3196 my $iface = $d->{host_ifname};
3197 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3198 $vmfw_conf, $vmid, 'IN
', $ipversion);
3199 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3200 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3204 warn $@ if $@; # just to be sure - should not happen
3207 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3208 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3211 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
3213 return ($ruleset, $ipset_ruleset);
3216 sub get_ruleset_status {
3217 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3219 my $statushash = {};
3221 foreach my $chain (sort keys %$ruleset) {
3222 my $sig = &$digest_fn($ruleset->{$chain});
3224 $statushash->{$chain}->{sig} = $sig;
3226 my $oldsig = $active_chains->{$chain};
3227 if (!defined($oldsig)) {
3228 $statushash->{$chain}->{action} = 'create
';
3230 if ($oldsig eq $sig) {
3231 $statushash->{$chain}->{action} = 'exists';
3233 $statushash->{$chain}->{action} = 'update
';
3236 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3237 foreach my $cmd (@{$ruleset->{$chain}}) {
3238 print "\t$cmd\n" if $verbose;
3242 foreach my $chain (sort keys %$active_chains) {
3243 if (!defined($ruleset->{$chain})) {
3244 my $sig = $active_chains->{$chain};
3245 $statushash->{$chain}->{action} = 'delete';
3246 $statushash->{$chain}->{sig} = $sig;
3247 print "delete $chain ($sig)\n" if $verbose;
3254 sub print_sig_rule {
3255 my ($chain, $sig) = @_;
3257 # We just use this to store a SHA1 checksum used to detect changes
3258 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3261 sub get_ruleset_cmdlist {
3262 my ($ruleset, $verbose, $iptablescmd) = @_;
3264 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3266 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3267 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3269 # create missing chains first
3270 foreach my $chain (sort keys %$ruleset) {
3271 my $stat = $statushash->{$chain};
3272 die "internal error" if !$stat;
3273 next if $stat->{action} ne 'create
';
3275 $cmdlist .= ":$chain - [0:0]\n";
3278 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3279 my $chain = "PVEFW-$h";
3280 if ($ruleset->{$chain} && !$hooks->{$h}) {
3281 $cmdlist .= "-A $h -j $chain\n";
3285 foreach my $chain (sort keys %$ruleset) {
3286 my $stat = $statushash->{$chain};
3287 die "internal error" if !$stat;
3289 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3290 $cmdlist .= "-F $chain\n";
3291 foreach my $cmd (@{$ruleset->{$chain}}) {
3292 $cmdlist .= "$cmd\n";
3294 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3295 } elsif ($stat->{action
} eq 'delete') {
3296 die "internal error"; # this should not happen
3297 } elsif ($stat->{action
} eq 'exists') {
3300 die "internal error - unknown status '$stat->{action}'";
3304 foreach my $chain (keys %$statushash) {
3305 next if $statushash->{$chain}->{action
} ne 'delete';
3306 $cmdlist .= "-F $chain\n";
3308 foreach my $chain (keys %$statushash) {
3309 next if $statushash->{$chain}->{action
} ne 'delete';
3310 next if $chain eq 'PVEFW-INPUT';
3311 next if $chain eq 'PVEFW-OUTPUT';
3312 next if $chain eq 'PVEFW-FORWARD';
3313 $cmdlist .= "-X $chain\n";
3316 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3318 $cmdlist .= "COMMIT\n";
3320 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3323 sub get_ipset_cmdlist
{
3324 my ($ruleset, $verbose) = @_;
3328 my $delete_cmdlist = "";
3330 my $active_chains = ipset_get_chains
();
3331 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3333 # remove stale _swap chains
3334 foreach my $chain (keys %$active_chains) {
3335 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3336 $cmdlist .= "destroy $chain\n";
3340 foreach my $chain (sort keys %$ruleset) {
3341 my $stat = $statushash->{$chain};
3342 die "internal error" if !$stat;
3344 if ($stat->{action
} eq 'create') {
3345 foreach my $cmd (@{$ruleset->{$chain}}) {
3346 $cmdlist .= "$cmd\n";
3351 foreach my $chain (sort keys %$ruleset) {
3352 my $stat = $statushash->{$chain};
3353 die "internal error" if !$stat;
3355 if ($stat->{action
} eq 'update') {
3356 my $chain_swap = $chain."_swap";
3358 foreach my $cmd (@{$ruleset->{$chain}}) {
3359 $cmd =~ s/$chain/$chain_swap/;
3360 $cmdlist .= "$cmd\n";
3362 $cmdlist .= "swap $chain_swap $chain\n";
3363 $cmdlist .= "flush $chain_swap\n";
3364 $cmdlist .= "destroy $chain_swap\n";
3368 foreach my $chain (sort keys %$statushash) {
3369 next if $statushash->{$chain}->{action
} ne 'delete';
3371 $delete_cmdlist .= "flush $chain\n";
3372 $delete_cmdlist .= "destroy $chain\n";
3375 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3377 return ($cmdlist, $delete_cmdlist, $changes);
3381 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3383 enable_bridge_firewall
();
3385 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3386 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3388 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3389 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3392 if ($ipset_changes) {
3393 print "ipset changes:\n";
3394 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3395 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3399 print "iptables changes:\n";
3404 print "ip6tables changes:\n";
3409 ipset_restore_cmdlist
($ipset_create_cmdlist);
3411 iptables_restore_cmdlist
($cmdlist);
3412 ip6tables_restore_cmdlist
($cmdlistv6);
3414 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3416 # test: re-read status and check if everything is up to date
3417 my $active_chains = iptables_get_chains
();
3418 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3421 foreach my $chain (sort keys %$ruleset) {
3422 my $stat = $statushash->{$chain};
3423 if ($stat->{action
} ne 'exists') {
3424 warn "unable to update chain '$chain'\n";
3429 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3430 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3432 foreach my $chain (sort keys %$rulesetv6) {
3433 my $stat = $statushashv6->{$chain};
3434 if ($stat->{action
} ne 'exists') {
3435 warn "unable to update chain '$chain'\n";
3440 die "unable to apply firewall changes\n" if $errors;
3442 update_nf_conntrack_max
($hostfw_conf);
3444 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3448 sub update_nf_conntrack_max
{
3449 my ($hostfw_conf) = @_;
3451 my $max = 65536; # reasonable default
3453 my $options = $hostfw_conf->{options
} || {};
3455 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3456 $max = $options->{nf_conntrack_max
};
3457 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3460 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3461 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3463 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3465 if ($current != $max) {
3466 my $hashsize = int($max/4);
3467 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3468 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3472 sub update_nf_conntrack_tcp_timeout_established
{
3473 my ($hostfw_conf) = @_;
3475 my $options = $hostfw_conf->{options
} || {};
3477 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3479 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3482 sub remove_pvefw_chains
{
3484 my ($chash, $hooks) = iptables_get_chains
();
3485 my $cmdlist = "*filter\n";
3487 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3489 $cmdlist .= "-D $h -j PVEFW-$h\n";
3493 foreach my $chain (keys %$chash) {
3494 $cmdlist .= "-F $chain\n";
3497 foreach my $chain (keys %$chash) {
3498 $cmdlist .= "-X $chain\n";
3500 $cmdlist .= "COMMIT\n";
3502 iptables_restore_cmdlist
($cmdlist);
3504 my $ipset_chains = ipset_get_chains
();
3508 foreach my $chain (keys %$ipset_chains) {
3509 $cmdlist .= "flush $chain\n";
3510 $cmdlist .= "destroy $chain\n";
3513 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3517 my $cluster_conf = load_clusterfw_conf
();
3518 my $cluster_options = $cluster_conf->{options
};
3519 my $enable = $cluster_options->{enable
};
3523 # load required modules here
3529 my $cluster_conf = load_clusterfw_conf
();
3530 my $cluster_options = $cluster_conf->{options
};
3532 if (!$cluster_options->{enable
}) {
3533 PVE
::Firewall
::remove_pvefw_chains
();
3537 my $hostfw_conf = load_hostfw_conf
();
3539 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3541 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);