9 use PVE
::Exception
qw(raise raise_param_exc);
10 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
13 use PVE
::Tools
qw($IPV4RE);
18 use PVE
::Tools
qw(run_command lock_file);
21 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
22 my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw";
24 # dynamically include PVE::QemuServer and PVE::OpenVZ
25 # to avoid dependency problems
28 require PVE
::QemuServer
;
29 $have_qemu_server = 1;
35 $have_pve_manager = 1;
38 PVE
::JSONSchema
::register_format
('IPv4orCIDR', \
&pve_verify_ipv4_or_cidr
);
39 sub pve_verify_ipv4_or_cidr
{
40 my ($cidr, $noerr) = @_;
42 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
43 return $cidr if Net
::IP-
>new($cidr);
44 return undef if $noerr;
45 die Net
::IP
::Error
() . "\n";
47 return undef if $noerr;
48 die "value does not look like a valid IP address or CIDR network\n";
51 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
52 description
=> "IP set name.",
54 pattern
=> '[A-Za-z][A-Za-z0-9\-\_]+',
59 my $security_group_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
61 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
62 description
=> "Security Group name.",
64 pattern
=> $security_group_pattern,
69 my $feature_ipset_nomatch = 0;
71 my (undef, undef, $release) = POSIX
::uname
();
72 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
73 my ($major, $minor) = ($1, $2);
74 $feature_ipset_nomatch = 1 if ($major > 3) ||
75 ($major == 3 && $minor >= 7);
82 my $nodename = PVE
::INotify
::nodename
();
84 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
85 my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
87 my $default_log_level = 'info';
89 my $log_level_hash = {
100 # imported/converted from: /usr/share/shorewall/macro.*
101 my $pve_fw_macros = {
104 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
105 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
108 "Auth (identd) traffic",
109 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
112 "Border Gateway Protocol traffic",
113 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
116 "BitTorrent traffic for BitTorrent 3.1 and earlier",
117 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
118 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
121 "BitTorrent traffic for BitTorrent 3.2 and later",
122 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
123 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
126 "Concurrent Versions System pserver traffic",
127 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
130 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
131 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
132 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
133 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
136 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
137 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
138 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
141 "Distributed Checksum Clearinghouse spam filtering mechanism",
142 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
145 "Forwarded DHCP traffic (bidirectional)",
146 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
147 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
150 "Domain Name System traffic (upd and tcp)",
151 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
152 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
155 "Distributed Compiler service",
156 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
159 "File Transfer Protocol",
160 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
163 "Finger protocol (RFC 742)",
164 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
167 "GNUnet secure peer-to-peer networking traffic",
168 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
169 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
170 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
171 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
174 "Generic Routing Encapsulation tunneling protocol (bidirectional)",
175 { action
=> 'PARAM', proto
=> '47' },
176 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
179 "Git distributed revision control traffic",
180 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
183 "OpenPGP HTTP keyserver protocol traffic",
184 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
187 "Hypertext Transfer Protocol (WWW)",
188 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
191 "Hypertext Transfer Protocol (WWW) over SSL",
192 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
195 "Internet Cache Protocol V2 (Squid) traffic",
196 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
199 "AOL Instant Messenger traffic",
200 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
203 "Internet Message Access Protocol",
204 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
207 "Internet Message Access Protocol over SSL",
208 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
211 "IPIP capsulation traffic (bidirectional)",
212 { action
=> 'PARAM', proto
=> '94' },
213 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '94' },
216 "IPsec traffic (bidirectional)",
217 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
218 { action
=> 'PARAM', proto
=> '50' },
219 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
220 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
223 "IPsec authentication (AH) traffic (bidirectional)",
224 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
225 { action
=> 'PARAM', proto
=> '51' },
226 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
227 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '51' },
230 "IPsec traffic and Nat-Traversal (bidirectional)",
231 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
232 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
233 { action
=> 'PARAM', proto
=> '50' },
234 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500' },
235 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '4500' },
236 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
239 "Internet Relay Chat traffic",
240 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
243 "HP Jetdirect printing",
244 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
247 "Layer 2 Tunneling Protocol traffic",
248 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
249 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1701' },
252 "Lightweight Directory Access Protocol traffic",
253 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
256 "Secure Lightweight Directory Access Protocol traffic",
257 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
260 "Microsoft Notification Protocol",
261 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
264 "Microsoft SQL Server",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
268 "Mail traffic (SMTP, SMTPS, Submission)",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
270 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
271 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
274 "Munin networked resource monitoring traffic",
275 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
279 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
282 "NNTP traffic (Usenet).",
283 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
286 "Encrypted NNTP traffic (Usenet)",
287 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
290 "Network Time Protocol (ntpd)",
291 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
294 "Bi-directional NTP (for NTP peers)",
295 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
296 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '123' },
299 "OSPF multicast traffic",
300 { action
=> 'PARAM', proto
=> '89' },
304 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
307 "Symantec PCAnywere (tm)",
308 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
309 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
313 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
316 "Encrypted POP3 traffic",
317 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
320 "Point-to-Point Tunneling Protocol",
321 { action
=> 'PARAM', proto
=> '47' },
322 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
323 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
327 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
331 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
334 "Line Printer protocol printing",
335 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
338 "Microsoft Remote Desktop Protocol traffic",
339 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
342 "Routing Information Protocol (bidirectional)",
343 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
344 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '520' },
347 "BIND remote management protocol",
348 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
351 "Razor Antispam System",
352 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
355 "Remote time retrieval (rdate)",
356 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
360 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
363 "SANE network scanning",
364 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
367 "Microsoft SMB traffic",
368 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
369 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
370 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
371 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
374 "Microsoft SMB traffic (bidirectional)",
375 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
376 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
377 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
378 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
379 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '135,445' },
380 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '137:139' },
381 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
382 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'tcp', dport
=> '135,139,445' },
385 "Samba Web Administration Tool",
386 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
389 "Simple Mail Transfer Protocol",
390 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
393 "Encrypted Simple Mail Transfer Protocol",
394 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
397 "Simple Network Management Protocol",
398 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
399 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
402 "Spam Assassin SPAMD traffic",
403 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
406 "Secure shell traffic",
407 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
410 "Subversion server (svnserve)",
411 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
414 "SixXS IPv6 Deployment and Tunnel Broker",
415 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
416 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
417 { action
=> 'PARAM', proto
=> '41' },
418 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
421 "Squid web proxy traffic",
422 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
425 "Mail message submission traffic",
426 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
429 "Syslog protocol (RFC 5424) traffic",
430 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
431 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
434 "Trivial File Transfer Protocol traffic",
435 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
439 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
443 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
446 "RFC 868 Time protocol",
447 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
450 "Traceroute (for up to 30 hops) traffic",
451 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
452 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
455 "VNC traffic for VNC display's 0 - 9",
456 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5909' },
459 "VNC traffic from Vncservers to Vncviewers in listen mode",
460 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
463 "WWW traffic (HTTP and HTTPS)",
464 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
465 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
468 "Web Cache/Proxy traffic (port 8080)",
469 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
473 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
476 "Whois (nicname, RFC 3912) traffic",
477 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
481 my $pve_fw_parsed_macros;
482 my $pve_fw_macro_descr;
483 my $pve_fw_preferred_macro_names = {};
485 my $pve_std_chains = {
486 'PVEFW-SET-ACCEPT-MARK' => [
487 "-j MARK --set-mark 1",
489 'PVEFW-DropBroadcast' => [
490 # same as shorewall 'Broadcast'
491 # simply DROP BROADCAST/MULTICAST/ANYCAST
492 # we can use this to reduce logging
493 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
494 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
495 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
496 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
499 # same as shorewall 'reject'
500 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
501 { action
=> 'DROP', source
=> '224.0.0.0/4' },
502 { action
=> 'DROP', proto
=> 'icmp' },
503 "-p tcp -j REJECT --reject-with tcp-reset",
504 "-p udp -j REJECT --reject-with icmp-port-unreachable",
505 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
506 "-j REJECT --reject-with icmp-host-prohibited",
509 # same as shorewall 'Drop', which is equal to DROP,
510 # but REJECT/DROP some packages to reduce logging,
511 # and ACCEPT critical ICMP types
512 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
513 # we are not interested in BROADCAST/MULTICAST/ANYCAST
514 { action
=> 'PVEFW-DropBroadcast' },
515 # ACCEPT critical ICMP types
516 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
517 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
518 # Drop packets with INVALID state
519 "-m conntrack --ctstate INVALID -j DROP",
520 # Drop Microsoft SMB noise
521 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
522 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
523 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
524 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
525 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
526 # Drop new/NotSyn traffic so that it doesn't get logged
527 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
529 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
532 # same as shorewall 'Reject', which is equal to Reject,
533 # but REJECT/DROP some packages to reduce logging,
534 # and ACCEPT critical ICMP types
535 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
536 # we are not interested in BROADCAST/MULTICAST/ANYCAST
537 { action
=> 'PVEFW-DropBroadcast' },
538 # ACCEPT critical ICMP types
539 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
540 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
541 # Drop packets with INVALID state
542 "-m conntrack --ctstate INVALID -j DROP",
543 # Drop Microsoft SMB noise
544 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
545 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
546 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
547 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
548 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
549 # Drop new/NotSyn traffic so that it doesn't get logged
550 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
552 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
554 'PVEFW-tcpflags' => [
555 # same as shorewall tcpflags action.
556 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
557 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
558 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
559 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
560 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
561 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
564 # same as shorewall smurfs action
565 # Filter packets for smurfs (packets with a broadcast address as the source).
566 "-s 0.0.0.0/32 -j RETURN",
567 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
568 "-s 224.0.0.0/4 -g PVEFW-smurflog",
572 # iptables -p icmp -h
573 my $icmp_type_names = {
576 'destination-unreachable' => 1,
577 'network-unreachable' => 1,
578 'host-unreachable' => 1,
579 'protocol-unreachable' => 1,
580 'port-unreachable' => 1,
581 'fragmentation-needed' => 1,
582 'source-route-failed' => 1,
583 'network-unknown' => 1,
585 'network-prohibited' => 1,
586 'host-prohibited' => 1,
587 'TOS-network-unreachable' => 1,
588 'TOS-host-unreachable' => 1,
589 'communication-prohibited' => 1,
590 'host-precedence-violation' => 1,
591 'precedence-cutoff' => 1,
592 'source-quench' => 1,
594 'network-redirect' => 1,
595 'host-redirect' => 1,
596 'TOS-network-redirect' => 1,
597 'TOS-host-redirect' => 1,
599 'router-advertisement' => 1,
600 'router-solicitation' => 1,
601 'time-exceeded' => 1,
602 'ttl-zero-during-transit' => 1,
603 'ttl-zero-during-reassembly' => 1,
604 'parameter-problem' => 1,
605 'ip-header-bad' => 1,
606 'required-option-missing' => 1,
607 'timestamp-request' => 1,
608 'timestamp-reply' => 1,
609 'address-mask-request' => 1,
610 'address-mask-reply' => 1,
613 sub init_firewall_macros
{
615 $pve_fw_parsed_macros = {};
617 foreach my $k (keys %$pve_fw_macros) {
618 my $lc_name = lc($k);
619 my $macro = $pve_fw_macros->{$k};
620 if (!ref($macro->[0])) {
621 $pve_fw_macro_descr->{$k} = shift @$macro;
623 $pve_fw_preferred_macro_names->{$lc_name} = $k;
624 $pve_fw_parsed_macros->{$k} = $macro;
628 init_firewall_macros
();
631 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
636 sub get_etc_services
{
638 return $etc_services if $etc_services;
640 my $filename = "/etc/services";
642 my $fh = IO
::File-
>new($filename, O_RDONLY
);
644 warn "unable to read '$filename' - $!\n";
650 while (my $line = <$fh>) {
652 next if $line =~m/^#/;
653 next if ($line =~m/^\s*$/);
655 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
656 $services->{byid
}->{$2}->{name
} = $1;
657 $services->{byid
}->{$2}->{port
} = $2;
658 $services->{byid
}->{$2}->{$3} = 1;
659 $services->{byname
}->{$1} = $services->{byid
}->{$2};
665 $etc_services = $services;
668 return $etc_services;
673 sub get_etc_protocols
{
674 return $etc_protocols if $etc_protocols;
676 my $filename = "/etc/protocols";
678 my $fh = IO
::File-
>new($filename, O_RDONLY
);
680 warn "unable to read '$filename' - $!\n";
686 while (my $line = <$fh>) {
688 next if $line =~m/^#/;
689 next if ($line =~m/^\s*$/);
691 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
692 $protocols->{byid
}->{$2}->{name
} = $1;
693 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
699 $etc_protocols = $protocols;
701 return $etc_protocols;
704 sub parse_address_list
{
707 return if $str =~ m/^(\+)(\S+)$/; # ipset ref
711 foreach my $elem (split(/,/, $str)) {
713 if (!Net
::IP-
>new($elem)) {
714 my $err = Net
::IP
::Error
();
715 die "invalid IP address: $err\n";
717 $iprange = 1 if $elem =~ m/-/;
720 die "you can use a range in a list\n" if $iprange && $count > 1;
723 sub parse_port_name_number_or_range
{
726 my $services = PVE
::Firewall
::get_etc_services
();
730 foreach my $item (split(/,/, $str)) {
732 if ($item =~ m/^(\d+):(\d+)$/) {
733 my ($port1, $port2) = ($1, $2);
734 die "invalid port '$port1'\n" if $port1 > 65535;
735 die "invalid port '$port2'\n" if $port2 > 65535;
736 } elsif ($item =~ m/^(\d+)$/) {
738 die "invalid port '$port'\n" if $port > 65535;
740 if ($icmp_type_names->{$item}) {
743 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
748 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
753 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
754 sub pve_fw_verify_port_spec
{
757 parse_port_name_number_or_range
($portstr);
762 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
763 sub pve_fw_verify_v4addr_spec
{
766 parse_address_list
($list);
771 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
772 sub pve_fw_verify_protocol_spec
{
775 my $protocols = get_etc_protocols
();
777 die "unknown protocol '$proto'\n" if $proto &&
778 !(defined($protocols->{byname
}->{$proto}) ||
779 defined($protocols->{byid
}->{$proto}));
785 # helper function for API
787 sub copy_opject_with_digest
{
790 my $sha = Digest
::SHA-
>new('sha1');
793 foreach my $k (sort keys %$object) {
794 my $v = $object->{$k};
795 next if !defined($v);
797 $sha->add($k, ':', $v, "\n");
800 my $digest = $sha->b64digest;
802 $res->{digest
} = $digest;
804 return wantarray ?
($res, $digest) : $res;
807 sub copy_list_with_digest
{
810 my $sha = Digest
::SHA-
>new('sha1');
813 foreach my $entry (@$list) {
815 foreach my $k (sort keys %$entry) {
816 my $v = $entry->{$k};
817 next if !defined($v);
819 $sha->add($k, ':', $v, "\n");
824 my $digest = $sha->b64digest;
826 foreach my $entry (@$res) {
827 $entry->{digest
} = $digest;
830 return wantarray ?
($res, $digest) : $res;
833 my $rule_properties = {
835 description
=> "Update rule at position <pos>.",
840 digest
=> get_standard_option
('pve-config-digest'),
844 enum
=> ['in', 'out', 'group'],
847 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
850 pattern
=> $security_group_pattern,
859 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
861 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
865 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
869 type
=> 'string', format
=> 'pve-fw-protocol-spec',
877 type
=> 'string', format
=> 'pve-fw-port-spec',
881 type
=> 'string', format
=> 'pve-fw-port-spec',
890 sub add_rule_properties
{
891 my ($properties) = @_;
893 foreach my $k (keys %$rule_properties) {
894 my $h = $rule_properties->{$k};
895 # copy data, so that we can modify later without side effects
896 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
902 sub delete_rule_properties
{
903 my ($rule, $delete_str) = @_;
905 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
906 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
907 if !defined($rule_properties->{$opt});
908 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
909 if $opt eq 'type' || $opt eq 'action';
910 delete $rule->{$opt};
916 my $apply_macro = sub {
917 my ($macro_name, $param, $verify) = @_;
919 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
920 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
924 foreach my $templ (@$macro_rules) {
927 foreach my $k (keys %$templ) {
928 my $v = $templ->{$k};
931 $param_used->{$k} = 1;
932 } elsif ($v eq 'DEST') {
934 $param_used->{dest
} = 1;
935 } elsif ($v eq 'SOURCE') {
936 $v = $param->{source
};
937 $param_used->{source
} = 1;
941 my $msg = "missing parameter '$k' in macro '$macro_name'";
942 raise_param_exc
({ macro => $msg }) if $verify;
947 foreach my $k (keys %$param) {
948 next if $k eq 'macro';
949 next if !defined($param->{$k});
950 next if $param_used->{$k};
951 if (defined($rule->{$k})) {
952 if ($rule->{$k} ne $param->{$k}) {
953 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
954 raise_param_exc
({ $k => $msg }) if $verify;
958 $rule->{$k} = $param->{$k};
968 my ($rule, $allow_groups) = @_;
970 my $type = $rule->{type
};
972 raise_param_exc
({ type
=> "missing property"}) if !$type;
973 raise_param_exc
({ action
=> "missing property"}) if !$rule->{action
};
975 if ($type eq 'in' || $type eq 'out') {
976 raise_param_exc
({ action
=> "unknown action '$rule->{action}'"})
977 if $rule->{action
} !~ m/^(ACCEPT|DROP|REJECT)$/;
978 } elsif ($type eq 'group') {
979 raise_param_exc
({ type
=> "security groups not allowed"})
981 raise_param_exc
({ action
=> "invalid characters in security group name"})
982 if $rule->{action
} !~ m/^${security_group_pattern}$/;
984 raise_param_exc
({ type
=> "unknown rule type '$type'"});
987 # fixme: verify $rule->{iface}?
989 if ($rule->{macro}) {
990 my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
991 raise_param_exc
({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
992 $rule->{macro} = $preferred_name;
995 if ($rule->{dport
}) {
996 eval { parse_port_name_number_or_range
($rule->{dport
}); };
997 raise_param_exc
({ dport
=> $@ }) if $@;
1000 if ($rule->{sport
}) {
1001 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1002 raise_param_exc
({ sport
=> $@ }) if $@;
1005 if ($rule->{source
}) {
1006 eval { parse_address_list
($rule->{source
}); };
1007 raise_param_exc
({ source
=> $@ }) if $@;
1010 if ($rule->{dest
}) {
1011 eval { parse_address_list
($rule->{dest
}); };
1012 raise_param_exc
({ dest
=> $@ }) if $@;
1015 if ($rule->{macro}) {
1016 &$apply_macro($rule->{macro}, $rule, 1);
1022 sub copy_rule_data
{
1023 my ($rule, $param) = @_;
1025 foreach my $k (keys %$rule_properties) {
1026 if (defined(my $v = $param->{$k})) {
1027 if ($v eq '' || $v eq '-') {
1043 my $bridge_firewall_enabled = 0;
1045 sub enable_bridge_firewall
{
1047 return if $bridge_firewall_enabled; # only once
1049 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1050 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1052 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1053 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1055 $bridge_firewall_enabled = 1;
1058 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1060 sub iptables_restore_cmdlist
{
1063 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1066 sub ipset_restore_cmdlist
{
1069 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1072 sub iptables_get_chains
{
1076 # check what chains we want to track
1077 my $is_pvefw_chain = sub {
1080 return 1 if $name =~ m/^PVEFW-\S+$/;
1082 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1084 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1086 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1088 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
1089 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1101 return if $line =~ m/^#/;
1102 return if $line =~ m/^\s*$/;
1104 if ($line =~ m/^\*(\S+)$/) {
1109 return if $table ne 'filter';
1111 if ($line =~ m/^:(\S+)\s/) {
1113 return if !&$is_pvefw_chain($chain);
1114 $res->{$chain} = "unknown";
1115 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1116 my ($chain, $sig) = ($1, $2);
1117 return if !&$is_pvefw_chain($chain);
1118 $res->{$chain} = $sig;
1119 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1122 # simply ignore the rest
1127 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1129 return wantarray ?
($res, $hooks) : $res;
1132 sub iptables_chain_digest
{
1134 my $digest = Digest
::SHA-
>new('sha1');
1135 foreach my $rule (@$rules) { # order is important
1136 $digest->add($rule);
1138 return $digest->b64digest;
1141 sub ipset_chain_digest
{
1144 my $digest = Digest
::SHA-
>new('sha1');
1145 foreach my $rule (sort @$rules) { # note: sorted
1146 $digest->add($rule);
1148 return $digest->b64digest;
1151 sub ipset_get_chains
{
1159 return if $line =~ m/^#/;
1160 return if $line =~ m/^\s*$/;
1161 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1163 $line =~ s/\s+$//; # delete trailing white space
1164 push @{$chains->{$chain}}, $line;
1166 # simply ignore the rest
1171 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1173 # compute digest for each chain
1174 foreach my $chain (keys %$chains) {
1175 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1181 sub ruleset_generate_cmdstr
{
1182 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1184 return if defined($rule->{enable
}) && !$rule->{enable
};
1186 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1188 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1189 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1193 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1194 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1196 my $source = $rule->{source
};
1197 my $dest = $rule->{dest
};
1200 if ($source =~ m/^(\+)(\S+)$/) {
1201 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1202 push @cmd, "-m set --match-set PVEFW-$2 src";
1204 } elsif ($source =~ m/\-/){
1205 push @cmd, "-m iprange --src-range $source";
1208 push @cmd, "-s $source";
1213 if ($dest =~ m/^(\+)(\S+)$/) {
1214 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1215 push @cmd, "-m set --match-set PVEFW-$2 dst";
1217 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1218 push @cmd, "-m iprange --dst-range $dest";
1221 push @cmd, "-s $dest";
1225 if ($rule->{proto
}) {
1226 push @cmd, "-p $rule->{proto}";
1229 $multiport++ if $nbdport > 1;
1230 $multiport++ if $nbsport > 1;
1232 push @cmd, "--match multiport" if $multiport;
1234 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1235 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1237 if ($rule->{dport
}) {
1238 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1239 # Note: we use dport to store --icmp-type
1240 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1241 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1244 if ($multiport == 2) {
1245 push @cmd, "--ports $rule->{dport}";
1247 push @cmd, "--dports $rule->{dport}";
1250 push @cmd, "--dport $rule->{dport}";
1255 if ($rule->{sport
}) {
1257 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1259 push @cmd, "--sport $rule->{sport}";
1262 } elsif ($rule->{dport
} || $rule->{sport
}) {
1263 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport
};
1264 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport
};
1267 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1269 if (my $action = $rule->{action
}) {
1270 $action = $actions->{$action} if defined($actions->{$action});
1271 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1272 push @cmd, $goto ?
"-g $action" : "-j $action";
1275 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1278 sub ruleset_generate_rule
{
1279 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1283 if ($rule->{macro}) {
1284 $rules = &$apply_macro($rule->{macro}, $rule);
1289 foreach my $tmp (@$rules) {
1290 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1291 ruleset_addrule
($ruleset, $chain, $cmdstr);
1296 sub ruleset_generate_rule_insert
{
1297 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1299 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1301 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1302 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1306 sub ruleset_create_chain
{
1307 my ($ruleset, $chain) = @_;
1309 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1310 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1312 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1314 $ruleset->{$chain} = [];
1317 sub ruleset_chain_exist
{
1318 my ($ruleset, $chain) = @_;
1320 return $ruleset->{$chain} ?
1 : undef;
1323 sub ruleset_addrule
{
1324 my ($ruleset, $chain, $rule) = @_;
1326 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1328 push @{$ruleset->{$chain}}, "-A $chain $rule";
1331 sub ruleset_insertrule
{
1332 my ($ruleset, $chain, $rule) = @_;
1334 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1336 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1339 sub get_log_rule_base
{
1340 my ($chain, $vmid, $msg, $loglevel) = @_;
1342 die "internal error - no log level" if !defined($loglevel);
1344 $vmid = 0 if !defined($vmid);
1346 # Note: we use special format for prefix to pass further
1347 # info to log daemon (VMID, LOGVELEL and CHAIN)
1349 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1352 sub ruleset_addlog {
1353 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1355 return if !defined($loglevel);
1357 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1359 $logrule = "$rule $logrule" if defined($rule);
1361 ruleset_addrule($ruleset, $chain, $logrule)
1364 sub generate_bridge_chains {
1365 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
1367 my $options = $hostfw_conf->{options} || {};
1369 die "error
: detected direct route to bridge
'$bridge'\n"
1370 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
1372 if (!ruleset_chain_exist($ruleset, "$bridge-FW
")) {
1373 ruleset_create_chain($ruleset, "$bridge-FW
");
1374 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-FW
");
1375 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-FW
");
1378 if (!ruleset_chain_exist($ruleset, "$bridge-OUT
")) {
1379 ruleset_create_chain($ruleset, "$bridge-OUT
");
1380 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-in
-j
$bridge-OUT
");
1381 ruleset_insertrule($ruleset, "PVEFW-INPUT
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-OUT
");
1384 if (!ruleset_chain_exist($ruleset, "$bridge-IN
")) {
1385 ruleset_create_chain($ruleset, "$bridge-IN
");
1386 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j
$bridge-IN
");
1387 ruleset_addrule($ruleset, "$bridge-FW
", "-m mark
--mark
1 -j ACCEPT
");
1388 # accept traffic to unmanaged bridge ports
1389 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j ACCEPT
");
1393 sub ruleset_add_chain_policy {
1394 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1396 if ($policy eq 'ACCEPT') {
1398 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1399 { ACCEPT => $accept_action});
1401 } elsif ($policy eq 'DROP') {
1403 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1405 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1407 ruleset_addrule($ruleset, $chain, "-j DROP
");
1408 } elsif ($policy eq 'REJECT') {
1409 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1411 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1413 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1416 die "internal error
: unknown policy
'$policy'";
1420 sub ruleset_create_vm_chain {
1421 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1423 ruleset_create_chain($ruleset, $chain);
1424 my $accept = generate_nfqueue($options);
1426 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1427 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1430 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1431 if ($direction eq 'OUT') {
1432 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1433 proto => 'udp', sport => 68, dport => 67 });
1435 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1436 proto => 'udp', sport => 67, dport => 68 });
1440 if ($options->{tcpflags}) {
1441 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1444 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1445 if ($direction eq 'OUT') {
1446 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-g PVEFW-SET-ACCEPT-MARK
");
1448 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1451 if ($direction eq 'OUT') {
1452 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1453 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1455 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1459 sub ruleset_generate_vm_rules {
1460 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1462 my $lc_direction = lc($direction);
1464 foreach my $rule (@$rules) {
1465 next if $rule->{iface} && $rule->{iface} ne $netid;
1466 next if !$rule->{enable};
1467 if ($rule->{type} eq 'group') {
1468 my $group_chain = "GROUP-
$rule->{action
}-$direction";
1469 if(!ruleset_chain_exist($ruleset, $group_chain)){
1470 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
1472 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1473 if ($direction eq 'OUT'){
1474 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j RETURN
");
1476 my $accept = generate_nfqueue($options);
1477 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$accept");
1481 next if $rule->{type} ne $lc_direction;
1482 if ($direction eq 'OUT') {
1483 ruleset_generate_rule($ruleset, $chain, $rule,
1484 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1486 my $accept = generate_nfqueue($options);
1487 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1493 sub generate_nfqueue {
1497 if($options->{ips}){
1498 $action = "NFQUEUE
";
1499 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1500 if(defined($3) && defined($1)) {
1501 $action .= " --queue-balance
$1:$3";
1502 }elsif (defined($1)) {
1503 $action .= " --queue-num
$1";
1506 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1514 sub ruleset_generate_vm_ipsrules {
1515 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1517 if ($options->{ips} && $direction eq 'IN') {
1518 my $nfqueue = generate_nfqueue($options);
1520 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1521 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1524 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1525 ruleset_create_chain($ruleset, "$bridge-IPS
");
1526 ruleset_insertrule($ruleset, "PVEFW-IPS
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-IPS
");
1529 ruleset_addrule($ruleset, "$bridge-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1533 sub generate_venet_rules_direction {
1534 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1536 parse_address_list($ip); # make sure we have a valid $ip list
1538 my $lc_direction = lc($direction);
1540 my $rules = $vmfw_conf->{rules};
1542 my $options = $vmfw_conf->{options};
1543 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1545 my $chain = "venet0-
$vmid-$direction";
1547 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1549 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1554 if ($direction eq 'OUT') {
1555 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1557 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1560 my $accept = generate_nfqueue($options);
1561 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1562 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1564 # plug into FORWARD, INPUT and OUTPUT chain
1565 if ($direction eq 'OUT') {
1566 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD
", {
1569 iface_in => 'venet0'});
1571 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT
", {
1574 iface_in => 'venet0'});
1576 ruleset_generate_rule($ruleset, "PVEFW-FORWARD
", {
1579 iface_out => 'venet0'});
1581 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT
", {
1584 iface_out => 'venet0'});
1588 sub generate_tap_rules_direction {
1589 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1591 my $lc_direction = lc($direction);
1593 my $rules = $vmfw_conf->{rules};
1595 my $options = $vmfw_conf->{options};
1596 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1598 my $tapchain = "$iface-$direction";
1600 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1602 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1604 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1609 if ($direction eq 'OUT') {
1610 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1612 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1615 my $accept = generate_nfqueue($options);
1616 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1617 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1619 # plug the tap chain to bridge chain
1620 if ($direction eq 'IN') {
1621 ruleset_insertrule($ruleset, "$bridge-IN
",
1622 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1624 ruleset_insertrule($ruleset, "$bridge-OUT
",
1625 "-m physdev
--physdev-in
$iface -j
$tapchain");
1629 sub enable_host_firewall {
1630 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1632 # fixme: allow security groups
1634 my $options = $hostfw_conf->{options};
1635 my $cluster_options = $cluster_conf->{options};
1636 my $rules = $hostfw_conf->{rules};
1638 # host inbound firewall
1639 my $chain = "PVEFW-HOST-IN
";
1640 ruleset_create_chain($ruleset, $chain);
1642 my $loglevel = get_option_log_level($options, "log_level_in
");
1644 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1645 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1648 if ($options->{tcpflags}) {
1649 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1652 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1653 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1654 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1655 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1656 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1657 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1659 # we use RETURN because we need to check also tap rules
1660 my $accept_action = 'RETURN';
1662 foreach my $rule (@$rules) {
1663 next if $rule->{type} ne 'in';
1664 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1667 # implement input policy
1668 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1669 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1671 # host outbound firewall
1672 $chain = "PVEFW-HOST-OUT
";
1673 ruleset_create_chain($ruleset, $chain);
1675 $loglevel = get_option_log_level($options, "log_level_out
");
1677 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1678 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1679 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1680 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1681 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1682 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1684 # we use RETURN because we may want to check other thigs later
1685 $accept_action = 'RETURN';
1687 foreach my $rule (@$rules) {
1688 next if $rule->{type} ne 'out';
1689 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1692 # implement output policy
1693 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1694 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1696 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1697 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1700 sub generate_group_rules {
1701 my ($ruleset, $cluster_conf, $group) = @_;
1702 die "no such security group
'$group'\n" if !$cluster_conf->{groups}->{$group};
1704 my $rules = $cluster_conf->{groups}->{$group};
1706 my $chain = "GROUP-
${group
}-IN
";
1708 ruleset_create_chain($ruleset, $chain);
1709 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1711 foreach my $rule (@$rules) {
1712 next if $rule->{type} ne 'in';
1713 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1716 $chain = "GROUP-
${group
}-OUT
";
1718 ruleset_create_chain($ruleset, $chain);
1719 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1721 foreach my $rule (@$rules) {
1722 next if $rule->{type} ne 'out';
1723 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1724 # check also other tap rules later
1725 ruleset_generate_rule($ruleset, $chain, $rule,
1726 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1731 my $valid_netdev_names = {};
1732 for (my $i = 0; $i < $MAX_NETS; $i++) {
1733 $valid_netdev_names->{"net
$i"} = 1;
1737 my ($line, $need_iface, $allow_groups) = @_;
1739 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
1741 # we can add single line comments to the end of the rule
1742 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1744 # we can disable a rule when prefixed with '|'
1747 $enable = 0 if $line =~ s/^\|//;
1749 my @data = split(/\s+/, $line);
1750 my $expected_elements = $need_iface ? 8 : 7;
1752 die "wrong number of rule elements
\n" if scalar(@data) > $expected_elements;
1755 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1757 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1760 die "incomplete rule
\n" if ! ($type && $action);
1766 if ($type eq 'in' || $type eq 'out') {
1767 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1769 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1771 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1772 die "unknown
macro '$1'\n" if !$preferred_name;
1773 $macro = $preferred_name;
1775 die "unknown action
'$action'\n";
1777 } elsif ($type eq 'group') {
1778 die "wrong number of rule elements
\n" if scalar(@data) != 3;
1779 die "groups disabled
\n" if !$allow_groups;
1781 die "invalid characters
in group name
\n" if $action !~ m/^${security_group_pattern}$/;
1783 die "unknown rule type
'$type'\n";
1787 $iface = undef if $iface && $iface eq '-';
1790 $proto = undef if $proto && $proto eq '-';
1791 pve_fw_verify_protocol_spec($proto) if $proto;
1793 $source = undef if $source && $source eq '-';
1794 $dest = undef if $dest && $dest eq '-';
1796 $dport = undef if $dport && $dport eq '-';
1797 $sport = undef if $sport && $sport eq '-';
1799 parse_port_name_number_or_range($dport) if defined($dport);
1800 parse_port_name_number_or_range($sport) if defined($sport);
1802 parse_address_list($source) if $source;
1803 parse_address_list($dest) if $dest;
1808 comment => $comment,
1820 sub parse_vmfw_option {
1825 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
1827 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
1830 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1832 $value = $2 ? lc($3) : '';
1833 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1836 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1841 die "can
't parse option '$line'\n"
1844 return ($opt, $value);
1847 sub parse_hostfw_option {
1852 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1854 if ($line =~ m/^(enable|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1857 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1859 $value = $2 ? lc($3) : '';
1860 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
1865 die "can't parse option
'$line'\n"
1868 return ($opt, $value);
1871 sub parse_clusterfw_option {
1876 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1879 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1884 die "can
't parse option '$line'\n"
1887 return ($opt, $value);
1890 sub parse_vm_fw_rules {
1891 my ($filename, $fh) = @_;
1893 my $res = { rules => [], options => {}};
1897 while (defined(my $line = <$fh>)) {
1898 next if $line =~ m/^#/;
1899 next if $line =~ m/^\s*$/;
1901 my $linenr = $fh->input_line_number();
1902 my $prefix = "$filename (line $linenr)";
1904 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1906 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1910 warn "$prefix: skip line - no section";
1914 next if !$res->{$section}; # skip undefined section
1916 if ($section eq 'options
') {
1918 my ($opt, $value) = parse_vmfw_option($line);
1919 $res->{options}->{$opt} = $value;
1921 warn "$prefix: $@" if $@;
1926 eval { $rule = parse_fw_rule($line, 1, 1); };
1928 warn "$prefix: $err";
1932 push @{$res->{$section}}, $rule;
1938 sub parse_host_fw_rules {
1939 my ($filename, $fh) = @_;
1941 my $res = { rules => [], options => {}};
1945 while (defined(my $line = <$fh>)) {
1946 next if $line =~ m/^#/;
1947 next if $line =~ m/^\s*$/;
1949 my $linenr = $fh->input_line_number();
1950 my $prefix = "$filename (line $linenr)";
1952 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1954 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1958 warn "$prefix: skip line - no section";
1962 next if !$res->{$section}; # skip undefined section
1964 if ($section eq 'options
') {
1966 my ($opt, $value) = parse_hostfw_option($line);
1967 $res->{options}->{$opt} = $value;
1969 warn "$prefix: $@" if $@;
1974 eval { $rule = parse_fw_rule($line, 1, 1); };
1976 warn "$prefix: $err";
1980 push @{$res->{$section}}, $rule;
1986 sub parse_cluster_fw_rules {
1987 my ($filename, $fh) = @_;
1996 group_comments => {},
1998 ipset_comments => {},
2001 while (defined(my $line = <$fh>)) {
2002 next if $line =~ m/^#/;
2003 next if $line =~ m/^\s*$/;
2005 my $linenr = $fh->input_line_number();
2006 my $prefix = "$filename (line $linenr)";
2008 if ($line =~ m/^\[options\]$/i) {
2009 $section = 'options
';
2013 if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2014 $section = 'groups
';
2017 $res->{$section}->{$group} = [];
2018 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2023 if ($line =~ m/^\[rules\]$/i) {
2028 if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2032 $res->{$section}->{$group} = [];
2033 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2039 warn "$prefix: skip line - no section\n";
2043 if ($section eq 'options
') {
2045 my ($opt, $value) = parse_clusterfw_option($line);
2046 $res->{options}->{$opt} = $value;
2048 warn "$prefix: $@" if $@;
2049 } elsif ($section eq 'rules
') {
2051 eval { $rule = parse_fw_rule($line, 1, 1); };
2053 warn "$prefix: $err";
2056 push @{$res->{$section}}, $rule;
2057 } elsif ($section eq 'groups
') {
2059 eval { $rule = parse_fw_rule($line, 0, 0); };
2061 warn "$prefix: $err";
2064 push @{$res->{$section}->{$group}}, $rule;
2065 } elsif ($section eq 'ipset
') {
2066 # we can add single line comments to the end of the rule
2067 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2069 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2075 eval { pve_verify_ipv4_or_cidr($cidr); };
2077 warn "$prefix: $cidr - $err";
2081 my $entry = { cidr => $cidr };
2082 $entry->{nomatch} = 1 if $nomatch;
2083 $entry->{comment} = $comment if $comment;
2085 push @{$res->{$section}->{$group}}, $entry;
2093 my ($code, @param) = @_;
2097 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2104 sub read_local_vm_config {
2109 my $vmdata = { openvz => $openvz, qemu => $qemu };
2111 my $vmlist = PVE::Cluster::get_vmlist();
2112 return $vmdata if !$vmlist || !$vmlist->{ids};
2113 my $ids = $vmlist->{ids};
2115 foreach my $vmid (keys %$ids) {
2116 next if !$vmid; # skip VE0
2117 my $d = $ids->{$vmid};
2118 next if !$d->{node} || $d->{node} ne $nodename;
2119 next if !$d->{type};
2120 if ($d->{type} eq 'openvz
') {
2121 if ($have_pve_manager) {
2122 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2123 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2124 $openvz->{$vmid} = $conf;
2127 } elsif ($d->{type} eq 'qemu
') {
2128 if ($have_qemu_server) {
2129 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2130 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2131 $qemu->{$vmid} = $conf;
2140 sub load_vmfw_conf {
2145 my $filename = "/etc/pve/firewall/$vmid.fw";
2146 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2147 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2153 my $format_rules = sub {
2154 my ($rules, $need_iface) = @_;
2158 foreach my $rule (@$rules) {
2159 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2160 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2161 $raw .= uc($rule->{type});
2162 if ($rule->{macro}) {
2163 $raw .= " $rule->{macro}($rule->{action})";
2165 $raw .= " " . $rule->{action};
2167 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
2169 if ($rule->{type} ne 'group
') {
2170 $raw .= " " . ($rule->{source} || '-');
2171 $raw .= " " . ($rule->{dest} || '-');
2172 $raw .= " " . ($rule->{proto} || '-');
2173 $raw .= " " . ($rule->{dport} || '-');
2174 $raw .= " " . ($rule->{sport} || '-');
2177 $raw .= " # " . encode('utf8
', $rule->{comment})
2178 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2181 die "unknown rule type '$rule->{type
}'";
2188 my $format_options = sub {
2193 $raw .= "[OPTIONS]\n\n";
2194 foreach my $opt (keys %$options) {
2195 $raw .= "$opt: $options->{$opt}\n";
2202 my $format_ipset = sub {
2208 foreach my $entry (@$options) {
2209 $nethash->{$entry->{cidr}} = $entry;
2212 foreach my $cidr (sort keys %$nethash) {
2213 my $entry = $nethash->{$cidr};
2214 my $line = $entry->{nomatch} ? '!' : '';
2215 $line .= $entry->{cidr};
2216 $line .= " # " . encode('utf8
', $entry->{comment})
2217 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2224 sub save_vmfw_conf {
2225 my ($vmid, $vmfw_conf) = @_;
2229 my $options = $vmfw_conf->{options};
2230 $raw .= &$format_options($options) if scalar(keys %$options);
2232 my $rules = $vmfw_conf->{rules};
2233 if (scalar(@$rules)) {
2234 $raw .= "[RULES]\n\n";
2235 $raw .= &$format_rules($rules, 1);
2239 my $filename = "/etc/pve/firewall/$vmid.fw";
2240 PVE::Tools::file_set_contents($filename, $raw);
2243 sub read_vm_firewall_configs {
2245 my $vmfw_configs = {};
2247 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2248 my $vmfw_conf = load_vmfw_conf($vmid);
2249 next if !$vmfw_conf->{options}; # skip if file does not exists
2250 $vmfw_configs->{$vmid} = $vmfw_conf;
2253 return $vmfw_configs;
2256 sub get_option_log_level {
2257 my ($options, $k) = @_;
2259 my $v = $options->{$k};
2260 $v = $default_log_level if !defined($v);
2262 return undef if $v eq '' || $v eq 'nolog
';
2264 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2266 return $v if ($v >= 0) && ($v <= 7);
2268 warn "unknown log level ($k = '$v')\n";
2273 sub generate_std_chains {
2274 my ($ruleset, $options) = @_;
2276 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2278 # same as shorewall smurflog.
2279 my $chain = 'PVEFW-smurflog
';
2281 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2282 push @{$pve_std_chains->{$chain}}, "-j DROP";
2284 # same as shorewall logflags action.
2285 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2286 $chain = 'PVEFW-logflags
';
2287 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2288 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2289 push @{$pve_std_chains->{$chain}}, "-j DROP";
2291 foreach my $chain (keys %$pve_std_chains) {
2292 ruleset_create_chain($ruleset, $chain);
2293 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2295 ruleset_generate_rule($ruleset, $chain, $rule);
2297 ruleset_addrule($ruleset, $chain, $rule);
2303 sub generate_ipset_chains {
2304 my ($ipset_ruleset, $fw_conf) = @_;
2306 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2307 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
2311 sub generate_ipset {
2312 my ($ipset_ruleset, $name, $options) = @_;
2314 my $hashsize = scalar(@$options);
2315 if ($hashsize <= 64) {
2318 $hashsize = round_powerof2($hashsize);
2321 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2325 foreach my $entry (@$options) {
2326 $nethash->{$entry->{cidr}} = $entry;
2329 foreach my $cidr (sort keys %$nethash) {
2330 my $entry = $nethash->{$cidr};
2332 my $cmd = "add $name $cidr";
2333 if ($entry->{nomatch}) {
2334 if ($feature_ipset_nomatch) {
2335 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2337 warn "ignore !$cidr - nomatch not supported by kernel\n";
2340 push @{$ipset_ruleset->{$name}}, $cmd;
2345 sub round_powerof2 {
2349 $int |= $int >> $_ foreach (1,2,4,8,16);
2353 sub save_pvefw_status {
2356 die "unknown status '$status' - internal error"
2357 if $status !~ m/^(stopped|active)$/;
2359 mkdir dirname($pve_fw_status_filename);
2360 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2363 sub read_pvefw_status {
2365 my $status = 'unknown
';
2367 return 'stopped
' if ! -f $pve_fw_status_filename;
2370 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2377 # fixme: move to pve-common PVE::ProcFSTools
2378 sub read_proc_net_route {
2379 my $filename = "/proc/net/route";
2383 my $fh = IO::File->new ($filename, "r");
2384 return $res if !$fh;
2386 my $int_to_quad = sub {
2387 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2390 while (defined(my $line = <$fh>)) {
2391 next if $line =~/^Iface\s+Destination/; # skip head
2392 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2393 push @{$res->{$iface}}, {
2394 dest => &$int_to_quad(hex($dest)),
2395 gateway => &$int_to_quad(hex($gateway)),
2396 mask => &$int_to_quad(hex($mask)),
2405 sub load_clusterfw_conf {
2407 my $cluster_conf = {};
2408 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
2409 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
2412 return $cluster_conf;
2415 sub save_clusterfw_conf {
2416 my ($cluster_conf) = @_;
2420 my $options = $cluster_conf->{options};
2421 $raw .= &$format_options($options) if scalar(keys %$options);
2423 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
2424 if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
2425 my $utf8comment = encode('utf8
', $comment);
2426 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2428 $raw .= "[IPSET $ipset]\n\n";
2430 my $options = $cluster_conf->{ipset}->{$ipset};
2431 $raw .= &$format_ipset($options);
2435 my $rules = $cluster_conf->{rules};
2436 if (scalar(@$rules)) {
2437 $raw .= "[RULES]\n\n";
2438 $raw .= &$format_rules($rules, 1);
2442 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2443 my $rules = $cluster_conf->{groups}->{$group};
2444 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2445 my $utf8comment = encode('utf8
', $comment);
2446 $raw .= "[group $group] # $utf8comment\n\n";
2448 $raw .= "[group $group]\n\n";
2451 $raw .= &$format_rules($rules, 0);
2455 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2458 sub load_hostfw_conf {
2460 my $hostfw_conf = {};
2461 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2462 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
2464 return $hostfw_conf;
2467 sub save_hostfw_conf {
2468 my ($hostfw_conf) = @_;
2472 my $options = $hostfw_conf->{options};
2473 $raw .= &$format_options($options) if scalar(keys %$options);
2475 my $rules = $hostfw_conf->{rules};
2476 if (scalar(@$rules)) {
2477 $raw .= "[RULES]\n\n";
2478 $raw .= &$format_rules($rules, 1);
2482 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2486 my ($cluster_conf, $hostfw_conf) = @_;
2488 $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
2489 $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
2491 my $vmdata = read_local_vm_config();
2492 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2494 my $routing_table = read_proc_net_route();
2497 my $ipset_ruleset = {};
2498 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2502 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2503 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2505 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2507 my $hostfw_options = $hostfw_conf->{options} || {};
2509 generate_std_chains($ruleset, $hostfw_options);
2511 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2513 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2515 # generate firewall rules for QEMU VMs
2516 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2517 my $conf = $vmdata->{qemu}->{$vmid};
2518 my $vmfw_conf = $vmfw_configs->{$vmid};
2519 next if !$vmfw_conf;
2520 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2522 foreach my $netid (keys %$conf) {
2523 next if $netid !~ m/^net(\d+)$/;
2524 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2526 my $iface = "tap${vmid}i$1";
2528 my $bridge = $net->{bridge};
2529 next if !$bridge; # fixme: ?
2531 $bridge .= "v$net->{tag}" if $net->{tag};
2533 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2535 my $macaddr = $net->{macaddr};
2536 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2537 $vmfw_conf, $vmid, $bridge, 'IN
');
2538 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2539 $vmfw_conf, $vmid, $bridge, 'OUT
');
2543 # generate firewall rules for OpenVZ containers
2544 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2545 my $conf = $vmdata->{openvz}->{$vmid};
2547 my $vmfw_conf = $vmfw_configs->{$vmid};
2548 next if !$vmfw_conf;
2549 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2551 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2552 my $ip = $conf->{ip_address}->{value};
2553 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2554 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2557 if ($conf->{netif} && $conf->{netif}->{value}) {
2558 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2559 foreach my $netid (keys %$netif) {
2560 my $d = $netif->{$netid};
2561 my $bridge = $d->{bridge};
2563 warn "no bridge device for CT $vmid iface '$netid'\n";
2567 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2569 my $macaddr = $d->{mac};
2570 my $iface = $d->{host_ifname};
2571 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2572 $vmfw_conf, $vmid, $bridge, 'IN
');
2573 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2574 $vmfw_conf, $vmid, $bridge, 'OUT
');
2579 if($hostfw_options->{optimize}){
2581 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
2582 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
2583 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2586 # fixme: what log level should we use here?
2587 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2589 # fixme: should we really block inter-bridge traffic?
2591 # always allow traffic from containers?
2592 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2594 # disable interbridge routing
2595 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
2596 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
2597 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2598 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2599 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
2600 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2602 return ($ruleset, $ipset_ruleset);
2605 sub get_ruleset_status {
2606 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2608 my $statushash = {};
2610 foreach my $chain (sort keys %$ruleset) {
2611 my $sig = &$digest_fn($ruleset->{$chain});
2613 $statushash->{$chain}->{sig} = $sig;
2615 my $oldsig = $active_chains->{$chain};
2616 if (!defined($oldsig)) {
2617 $statushash->{$chain}->{action} = 'create
';
2619 if ($oldsig eq $sig) {
2620 $statushash->{$chain}->{action} = 'exists';
2622 $statushash->{$chain}->{action} = 'update
';
2625 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2626 foreach my $cmd (@{$ruleset->{$chain}}) {
2627 print "\t$cmd\n" if $verbose;
2631 foreach my $chain (sort keys %$active_chains) {
2632 if (!defined($ruleset->{$chain})) {
2633 my $sig = $active_chains->{$chain};
2634 $statushash->{$chain}->{action} = 'delete';
2635 $statushash->{$chain}->{sig} = $sig;
2636 print "delete $chain ($sig)\n" if $verbose;
2643 sub print_sig_rule {
2644 my ($chain, $sig) = @_;
2646 # We just use this to store a SHA1 checksum used to detect changes
2647 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2650 sub get_ruleset_cmdlist {
2651 my ($ruleset, $verbose) = @_;
2653 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2655 my ($active_chains, $hooks) = iptables_get_chains();
2656 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2658 # create missing chains first
2659 foreach my $chain (sort keys %$ruleset) {
2660 my $stat = $statushash->{$chain};
2661 die "internal error" if !$stat;
2662 next if $stat->{action} ne 'create
';
2664 $cmdlist .= ":$chain - [0:0]\n";
2667 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2668 if (!$hooks->{$h}) {
2669 $cmdlist .= "-A $h -j PVEFW-$h\n";
2673 foreach my $chain (sort keys %$ruleset) {
2674 my $stat = $statushash->{$chain};
2675 die "internal error" if !$stat;
2677 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2678 $cmdlist .= "-F $chain\n";
2679 foreach my $cmd (@{$ruleset->{$chain}}) {
2680 $cmdlist .= "$cmd\n";
2682 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2683 } elsif ($stat->{action
} eq 'delete') {
2684 die "internal error"; # this should not happen
2685 } elsif ($stat->{action
} eq 'exists') {
2688 die "internal error - unknown status '$stat->{action}'";
2692 foreach my $chain (keys %$statushash) {
2693 next if $statushash->{$chain}->{action
} ne 'delete';
2694 $cmdlist .= "-F $chain\n";
2696 foreach my $chain (keys %$statushash) {
2697 next if $statushash->{$chain}->{action
} ne 'delete';
2698 next if $chain eq 'PVEFW-INPUT';
2699 next if $chain eq 'PVEFW-OUTPUT';
2700 next if $chain eq 'PVEFW-FORWARD';
2701 $cmdlist .= "-X $chain\n";
2704 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2706 $cmdlist .= "COMMIT\n";
2708 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2711 sub get_ipset_cmdlist
{
2712 my ($ruleset, $verbose) = @_;
2716 my $delete_cmdlist = "";
2718 my $active_chains = ipset_get_chains
();
2719 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2721 # remove stale _swap chains
2722 foreach my $chain (keys %$active_chains) {
2723 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2724 $cmdlist .= "destroy $chain\n";
2728 foreach my $chain (sort keys %$ruleset) {
2729 my $stat = $statushash->{$chain};
2730 die "internal error" if !$stat;
2732 if ($stat->{action
} eq 'create') {
2733 foreach my $cmd (@{$ruleset->{$chain}}) {
2734 $cmdlist .= "$cmd\n";
2738 if ($stat->{action
} eq 'update') {
2739 my $chain_swap = $chain."_swap";
2741 foreach my $cmd (@{$ruleset->{$chain}}) {
2742 $cmd =~ s/$chain/$chain_swap/;
2743 $cmdlist .= "$cmd\n";
2745 $cmdlist .= "swap $chain_swap $chain\n";
2746 $cmdlist .= "flush $chain_swap\n";
2747 $cmdlist .= "destroy $chain_swap\n";
2752 foreach my $chain (keys %$statushash) {
2753 next if $statushash->{$chain}->{action
} ne 'delete';
2755 $delete_cmdlist .= "flush $chain\n";
2756 $delete_cmdlist .= "destroy $chain\n";
2759 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
2761 return ($cmdlist, $delete_cmdlist, $changes);
2765 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2767 enable_bridge_firewall
();
2769 update_nf_conntrack_max
($hostfw_conf);
2771 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
2773 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2774 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
2776 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
2779 if ($ipset_changes) {
2780 print "ipset changes:\n";
2781 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2782 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2786 print "iptables changes:\n";
2791 ipset_restore_cmdlist
($ipset_create_cmdlist);
2793 iptables_restore_cmdlist
($cmdlist);
2795 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2797 # test: re-read status and check if everything is up to date
2798 my $active_chains = iptables_get_chains
();
2799 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
2802 foreach my $chain (sort keys %$ruleset) {
2803 my $stat = $statushash->{$chain};
2804 if ($stat->{action
} ne 'exists') {
2805 warn "unable to update chain '$chain'\n";
2810 die "unable to apply firewall changes\n" if $errors;
2813 sub update_nf_conntrack_max
{
2814 my ($hostfw_conf) = @_;
2816 my $max = 65536; # reasonable default
2818 my $options = $hostfw_conf->{options
} || {};
2820 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
2821 $max = $options->{nf_conntrack_max
};
2822 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2825 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2826 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2828 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
2830 if ($current != $max) {
2831 my $hashsize = int($max/4);
2832 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
2833 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
2837 sub update_nf_conntrack_tcp_timeout_established
{
2838 my ($hostfw_conf) = @_;
2840 my $options = $hostfw_conf->{options
} || {};
2842 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
2844 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
2847 sub remove_pvefw_chains
{
2849 my ($chash, $hooks) = iptables_get_chains
();
2850 my $cmdlist = "*filter\n";
2852 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2854 $cmdlist .= "-D $h -j PVEFW-$h\n";
2858 foreach my $chain (keys %$chash) {
2859 $cmdlist .= "-F $chain\n";
2862 foreach my $chain (keys %$chash) {
2863 $cmdlist .= "-X $chain\n";
2865 $cmdlist .= "COMMIT\n";
2867 iptables_restore_cmdlist
($cmdlist);
2871 my ($start, $verbose) = @_;
2875 my $cluster_conf = load_clusterfw_conf
();
2876 my $cluster_options = $cluster_conf->{options
};
2878 my $enable = $cluster_options->{enable
};
2880 my $status = read_pvefw_status
();
2882 die "Firewall is disabled - cannot start\n" if !$enable && $start;
2885 if ($status ne 'stopped') {
2886 print "trying to stop firewall (firewall is disabled)\n" if $verbose;
2887 PVE
::Firewall
::remove_pvefw_chains
();
2888 PVE
::Firewall
::save_pvefw_status
('stopped');
2890 print "Firewall disabled\n" if $verbose;
2894 my $hostfw_conf = load_hostfw_conf
();
2896 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
2898 if ($start || $status eq 'active') {
2900 save_pvefw_status
('active') if ($status ne 'active');
2902 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
2904 print "Firewall not active (status = $status)\n" if $verbose;