9 use PVE
::Exception
qw(raise raise_param_exc);
10 use PVE
::JSONSchema
qw(get_standard_option);
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 my $feature_ipset_nomatch = 0;
40 my (undef, undef, $release) = POSIX
::uname
();
41 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
42 my ($major, $minor) = ($1, $2);
43 $feature_ipset_nomatch = 1 if ($major > 3) ||
44 ($major == 3 && $minor >= 7);
51 my $nodename = PVE
::INotify
::nodename
();
53 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
54 my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
56 my $default_log_level = 'info';
58 my $log_level_hash = {
69 # imported/converted from: /usr/share/shorewall/macro.*
73 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
74 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
77 "Auth (identd) traffic",
78 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
81 "Border Gateway Protocol traffic",
82 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
85 "BitTorrent traffic for BitTorrent 3.1 and earlier",
86 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
87 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
90 "BitTorrent traffic for BitTorrent 3.2 and later",
91 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
92 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
95 "Concurrent Versions System pserver traffic",
96 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
99 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
100 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
101 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
102 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
105 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
106 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
107 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
110 "Distributed Checksum Clearinghouse spam filtering mechanism",
111 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
114 "Forwarded DHCP traffic (bidirectional)",
115 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
116 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
119 "Domain Name System traffic (upd and tcp)",
120 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
121 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
124 "Distributed Compiler service",
125 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
128 "File Transfer Protocol",
129 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
132 "Finger protocol (RFC 742)",
133 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
136 "GNUnet secure peer-to-peer networking traffic",
137 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
138 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
139 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
140 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
143 "Generic Routing Encapsulation tunneling protocol (bidirectional)",
144 { action
=> 'PARAM', proto
=> '47' },
145 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
148 "Git distributed revision control traffic",
149 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
152 "OpenPGP HTTP keyserver protocol traffic",
153 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
156 "Hypertext Transfer Protocol (WWW)",
157 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
160 "Hypertext Transfer Protocol (WWW) over SSL",
161 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
164 "Internet Cache Protocol V2 (Squid) traffic",
165 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
168 "AOL Instant Messenger traffic",
169 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
172 "Internet Message Access Protocol",
173 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
176 "Internet Message Access Protocol over SSL",
177 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
180 "IPIP capsulation traffic (bidirectional)",
181 { action
=> 'PARAM', proto
=> '94' },
182 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '94' },
185 "IPsec traffic (bidirectional)",
186 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
187 { action
=> 'PARAM', proto
=> '50' },
188 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
189 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
192 "IPsec authentication (AH) traffic (bidirectional)",
193 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
194 { action
=> 'PARAM', proto
=> '51' },
195 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
196 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '51' },
199 "IPsec traffic and Nat-Traversal (bidirectional)",
200 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
201 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
202 { action
=> 'PARAM', proto
=> '50' },
203 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500' },
204 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '4500' },
205 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
208 "Internet Relay Chat traffic",
209 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
212 "HP Jetdirect printing",
213 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
216 "Layer 2 Tunneling Protocol traffic",
217 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
218 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1701' },
221 "Lightweight Directory Access Protocol traffic",
222 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
225 "Secure Lightweight Directory Access Protocol traffic",
226 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
229 "Microsoft Notification Protocol",
230 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
233 "Microsoft SQL Server",
234 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
237 "Mail traffic (SMTP, SMTPS, Submission)",
238 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
239 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
240 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
243 "Munin networked resource monitoring traffic",
244 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
248 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
251 "NNTP traffic (Usenet).",
252 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
255 "Encrypted NNTP traffic (Usenet)",
256 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
259 "Network Time Protocol (ntpd)",
260 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
263 "Bi-directional NTP (for NTP peers)",
264 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
265 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '123' },
268 "OSPF multicast traffic",
269 { action
=> 'PARAM', proto
=> '89' },
273 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
276 "Symantec PCAnywere (tm)",
277 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
278 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
282 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
285 "Encrypted POP3 traffic",
286 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
289 "Point-to-Point Tunneling Protocol",
290 { action
=> 'PARAM', proto
=> '47' },
291 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
292 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
296 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
300 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
303 "Line Printer protocol printing",
304 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
307 "Microsoft Remote Desktop Protocol traffic",
308 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
311 "Routing Information Protocol (bidirectional)",
312 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
313 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '520' },
316 "BIND remote management protocol",
317 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
320 "Razor Antispam System",
321 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
324 "Remote time retrieval (rdate)",
325 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
332 "SANE network scanning",
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
336 "Microsoft SMB traffic",
337 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
338 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
339 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
340 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
343 "Microsoft SMB traffic (bidirectional)",
344 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
345 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
346 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
347 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
348 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '135,445' },
349 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '137:139' },
350 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
351 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'tcp', dport
=> '135,139,445' },
354 "Samba Web Administration Tool",
355 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
358 "Simple Mail Transfer Protocol",
359 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
362 "Encrypted Simple Mail Transfer Protocol",
363 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
366 "Simple Network Management Protocol",
367 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
368 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
371 "Spam Assassin SPAMD traffic",
372 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
375 "Secure shell traffic",
376 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
379 "Subversion server (svnserve)",
380 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
383 "SixXS IPv6 Deployment and Tunnel Broker",
384 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
385 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
386 { action
=> 'PARAM', proto
=> '41' },
387 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
390 "Squid web proxy traffic",
391 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
394 "Mail message submission traffic",
395 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
398 "Syslog protocol (RFC 5424) traffic",
399 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
400 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
403 "Trivial File Transfer Protocol traffic",
404 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
408 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
412 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
415 "RFC 868 Time protocol",
416 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
419 "Traceroute (for up to 30 hops) traffic",
420 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
421 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
424 "VNC traffic for VNC display's 0 - 9",
425 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5909' },
428 "VNC traffic from Vncservers to Vncviewers in listen mode",
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
432 "WWW traffic (HTTP and HTTPS)",
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
434 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
437 "Web Cache/Proxy traffic (port 8080)",
438 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
442 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
445 "Whois (nicname, RFC 3912) traffic",
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
450 my $pve_fw_parsed_macros;
451 my $pve_fw_macro_descr;
452 my $pve_fw_preferred_macro_names = {};
454 my $pve_std_chains = {
455 'PVEFW-SET-ACCEPT-MARK' => [
456 "-j MARK --set-mark 1",
458 'PVEFW-DropBroadcast' => [
459 # same as shorewall 'Broadcast'
460 # simply DROP BROADCAST/MULTICAST/ANYCAST
461 # we can use this to reduce logging
462 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
463 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
464 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
465 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
468 # same as shorewall 'reject'
469 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
470 { action
=> 'DROP', source
=> '224.0.0.0/4' },
471 { action
=> 'DROP', proto
=> 'icmp' },
472 "-p tcp -j REJECT --reject-with tcp-reset",
473 "-p udp -j REJECT --reject-with icmp-port-unreachable",
474 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
475 "-j REJECT --reject-with icmp-host-prohibited",
478 # same as shorewall 'Drop', which is equal to DROP,
479 # but REJECT/DROP some packages to reduce logging,
480 # and ACCEPT critical ICMP types
481 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
482 # we are not interested in BROADCAST/MULTICAST/ANYCAST
483 { action
=> 'PVEFW-DropBroadcast' },
484 # ACCEPT critical ICMP types
485 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
486 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
487 # Drop packets with INVALID state
488 "-m conntrack --ctstate INVALID -j DROP",
489 # Drop Microsoft SMB noise
490 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
491 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
492 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
493 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
494 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
495 # Drop new/NotSyn traffic so that it doesn't get logged
496 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
498 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
501 # same as shorewall 'Reject', which is equal to Reject,
502 # but REJECT/DROP some packages to reduce logging,
503 # and ACCEPT critical ICMP types
504 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
505 # we are not interested in BROADCAST/MULTICAST/ANYCAST
506 { action
=> 'PVEFW-DropBroadcast' },
507 # ACCEPT critical ICMP types
508 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
509 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
510 # Drop packets with INVALID state
511 "-m conntrack --ctstate INVALID -j DROP",
512 # Drop Microsoft SMB noise
513 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
514 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
515 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
516 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
517 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
518 # Drop new/NotSyn traffic so that it doesn't get logged
519 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
521 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
523 'PVEFW-tcpflags' => [
524 # same as shorewall tcpflags action.
525 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
526 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
527 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
528 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
529 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
530 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
533 # same as shorewall smurfs action
534 # Filter packets for smurfs (packets with a broadcast address as the source).
535 "-s 0.0.0.0/32 -j RETURN",
536 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
537 "-s 224.0.0.0/4 -g PVEFW-smurflog",
541 # iptables -p icmp -h
542 my $icmp_type_names = {
545 'destination-unreachable' => 1,
546 'network-unreachable' => 1,
547 'host-unreachable' => 1,
548 'protocol-unreachable' => 1,
549 'port-unreachable' => 1,
550 'fragmentation-needed' => 1,
551 'source-route-failed' => 1,
552 'network-unknown' => 1,
554 'network-prohibited' => 1,
555 'host-prohibited' => 1,
556 'TOS-network-unreachable' => 1,
557 'TOS-host-unreachable' => 1,
558 'communication-prohibited' => 1,
559 'host-precedence-violation' => 1,
560 'precedence-cutoff' => 1,
561 'source-quench' => 1,
563 'network-redirect' => 1,
564 'host-redirect' => 1,
565 'TOS-network-redirect' => 1,
566 'TOS-host-redirect' => 1,
568 'router-advertisement' => 1,
569 'router-solicitation' => 1,
570 'time-exceeded' => 1,
571 'ttl-zero-during-transit' => 1,
572 'ttl-zero-during-reassembly' => 1,
573 'parameter-problem' => 1,
574 'ip-header-bad' => 1,
575 'required-option-missing' => 1,
576 'timestamp-request' => 1,
577 'timestamp-reply' => 1,
578 'address-mask-request' => 1,
579 'address-mask-reply' => 1,
582 sub init_firewall_macros
{
584 $pve_fw_parsed_macros = {};
586 foreach my $k (keys %$pve_fw_macros) {
587 my $lc_name = lc($k);
588 my $macro = $pve_fw_macros->{$k};
589 if (!ref($macro->[0])) {
590 $pve_fw_macro_descr->{$k} = shift @$macro;
592 $pve_fw_preferred_macro_names->{$lc_name} = $k;
593 $pve_fw_parsed_macros->{$k} = $macro;
597 init_firewall_macros
();
600 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
605 sub get_etc_services
{
607 return $etc_services if $etc_services;
609 my $filename = "/etc/services";
611 my $fh = IO
::File-
>new($filename, O_RDONLY
);
613 warn "unable to read '$filename' - $!\n";
619 while (my $line = <$fh>) {
621 next if $line =~m/^#/;
622 next if ($line =~m/^\s*$/);
624 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
625 $services->{byid
}->{$2}->{name
} = $1;
626 $services->{byid
}->{$2}->{port
} = $2;
627 $services->{byid
}->{$2}->{$3} = 1;
628 $services->{byname
}->{$1} = $services->{byid
}->{$2};
634 $etc_services = $services;
637 return $etc_services;
642 sub get_etc_protocols
{
643 return $etc_protocols if $etc_protocols;
645 my $filename = "/etc/protocols";
647 my $fh = IO
::File-
>new($filename, O_RDONLY
);
649 warn "unable to read '$filename' - $!\n";
655 while (my $line = <$fh>) {
657 next if $line =~m/^#/;
658 next if ($line =~m/^\s*$/);
660 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
661 $protocols->{byid
}->{$2}->{name
} = $1;
662 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
668 $etc_protocols = $protocols;
670 return $etc_protocols;
673 sub parse_address_list
{
676 return if $str !~ m/^(\+)(\S+)$/; # ipset ref
680 foreach my $elem (split(/,/, $str)) {
682 if (!Net
::IP-
>new($elem)) {
683 my $err = Net
::IP
::Error
();
684 die "invalid IP address: $err\n";
686 $iprange = 1 if $elem =~ m/-/;
689 die "you can use a range in a list\n" if $iprange && $count > 1;
692 sub parse_port_name_number_or_range
{
695 my $services = PVE
::Firewall
::get_etc_services
();
697 foreach my $item (split(/,/, $str)) {
699 if ($item =~ m/^(\d+):(\d+)$/) {
700 my ($port1, $port2) = ($1, $2);
701 die "invalid port '$port1'\n" if $port1 > 65535;
702 die "invalid port '$port2'\n" if $port2 > 65535;
703 } elsif ($item =~ m/^(\d+)$/) {
705 die "invalid port '$port'\n" if $port > 65535;
707 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
714 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
715 sub pve_fw_verify_port_spec
{
718 parse_port_name_number_or_range
($portstr);
723 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
724 sub pve_fw_verify_v4addr_spec
{
727 parse_address_list
($list);
732 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
733 sub pve_fw_verify_protocol_spec
{
736 my $protocols = get_etc_protocols
();
738 die "unknown protocol '$proto'\n" if $proto &&
739 !(defined($protocols->{byname
}->{$proto}) ||
740 defined($protocols->{byid
}->{$proto}));
746 # helper function for API
748 my $rule_properties = {
750 description
=> "Update rule at position <pos>.",
764 enum
=> ['in', 'out', 'group'],
769 enum
=> ['ACCEPT', 'DROP', 'REJECT'],
776 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
778 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
782 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
786 type
=> 'string', format
=> 'pve-fw-protocol-spec',
794 type
=> 'string', format
=> 'pve-fw-port-spec',
798 type
=> 'string', format
=> 'pve-fw-port-spec',
807 sub cleanup_fw_rule
{
808 my ($rule, $digest, $pos) = @_;
812 foreach my $k (keys %$rule) {
813 next if !$rule_properties->{$k};
815 next if !defined($v);
817 $r->{digest
} = $digest;
824 sub add_rule_properties
{
825 my ($properties) = @_;
827 foreach my $k (keys %$rule_properties) {
828 my $h = $rule_properties->{$k};
829 # copy data, so that we can modify later without side effects
830 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
836 sub delete_rule_properties
{
837 my ($rule, $delete_str) = @_;
839 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
840 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
841 if !defined($rule_properties->{$opt});
842 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
843 if $opt eq 'type' || $opt eq 'action';
844 delete $rule->{$opt};
850 my $apply_macro = sub {
851 my ($macro_name, $param, $verify) = @_;
853 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
854 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
858 foreach my $templ (@$macro_rules) {
861 foreach my $k (keys %$templ) {
862 my $v = $templ->{$k};
865 $param_used->{$k} = 1;
866 } elsif ($v eq 'DEST') {
868 $param_used->{dest
} = 1;
869 } elsif ($v eq 'SOURCE') {
870 $v = $param->{source
};
871 $param_used->{source
} = 1;
875 my $msg = "missing parameter '$k' in macro '$macro_name'";
876 raise_param_exc
({ macro => $msg }) if $verify;
881 foreach my $k (keys %$param) {
882 next if $k eq 'macro';
883 next if !defined($param->{$k});
884 next if $param_used->{$k};
885 if (defined($rule->{$k})) {
886 if ($rule->{$k} ne $param->{$k}) {
887 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
888 raise_param_exc
({ $k => $msg }) if $verify;
892 $rule->{$k} = $param->{$k};
902 my ($rule, $allow_groups) = @_;
904 my $type = $rule->{type
};
906 raise_param_exc
({ type
=> "missing property"}) if !$type;
907 raise_param_exc
({ action
=> "missing property"}) if !$rule->{action
};
909 if ($type eq 'in' || $type eq 'out') {
910 raise_param_exc
({ action
=> "unknown action '$rule->{action}'"})
911 if $rule->{action
} !~ m/^(ACCEPT|DROP|REJECT)$/;
912 } elsif ($type eq 'group') {
913 raise_param_exc
({ type
=> "security groups not allowed"})
915 raise_param_exc
({ action
=> "invalid characters in security group name"})
916 if $rule->{action
} !~ m/^[A-Za-z0-9_\-]+$/;
918 raise_param_exc
({ type
=> "unknown rule type '$type'"});
921 # fixme: verify $rule->{iface}?
923 if ($rule->{macro}) {
924 my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
925 raise_param_exc
({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
926 $rule->{macro} = $preferred_name;
929 if ($rule->{dport
}) {
930 eval { parse_port_name_number_or_range
($rule->{dport
}); };
931 raise_param_exc
({ dport
=> $@ }) if $@;
934 if ($rule->{sport
}) {
935 eval { parse_port_name_number_or_range
($rule->{sport
}); };
936 raise_param_exc
({ sport
=> $@ }) if $@;
939 if ($rule->{source
}) {
940 eval { parse_address_list
($rule->{source
}); };
941 raise_param_exc
({ source
=> $@ }) if $@;
945 eval { parse_address_list
($rule->{dest
}); };
946 raise_param_exc
({ dest
=> $@ }) if $@;
949 if ($rule->{macro}) {
950 &$apply_macro($rule->{macro}, $rule, 1);
957 my ($rule, $param) = @_;
959 foreach my $k (keys %$rule_properties) {
960 if (defined(my $v = $param->{$k})) {
961 if ($v eq '' || $v eq '-') {
977 my $bridge_firewall_enabled = 0;
979 sub enable_bridge_firewall
{
981 return if $bridge_firewall_enabled; # only once
983 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
984 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
986 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
987 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
989 $bridge_firewall_enabled = 1;
992 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
994 sub iptables_restore_cmdlist
{
997 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1000 sub ipset_restore_cmdlist
{
1003 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1006 sub iptables_get_chains
{
1010 # check what chains we want to track
1011 my $is_pvefw_chain = sub {
1014 return 1 if $name =~ m/^PVEFW-\S+$/;
1016 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1018 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1020 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1022 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
1023 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1035 return if $line =~ m/^#/;
1036 return if $line =~ m/^\s*$/;
1038 if ($line =~ m/^\*(\S+)$/) {
1043 return if $table ne 'filter';
1045 if ($line =~ m/^:(\S+)\s/) {
1047 return if !&$is_pvefw_chain($chain);
1048 $res->{$chain} = "unknown";
1049 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1050 my ($chain, $sig) = ($1, $2);
1051 return if !&$is_pvefw_chain($chain);
1052 $res->{$chain} = $sig;
1053 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1056 # simply ignore the rest
1061 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1063 return wantarray ?
($res, $hooks) : $res;
1066 sub iptables_chain_digest
{
1068 my $digest = Digest
::SHA-
>new('sha1');
1069 foreach my $rule (@$rules) { # order is important
1070 $digest->add($rule);
1072 return $digest->b64digest;
1075 sub ipset_chain_digest
{
1078 my $digest = Digest
::SHA-
>new('sha1');
1079 foreach my $rule (sort @$rules) { # note: sorted
1080 $digest->add($rule);
1082 return $digest->b64digest;
1085 sub ipset_get_chains
{
1093 return if $line =~ m/^#/;
1094 return if $line =~ m/^\s*$/;
1095 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1097 $line =~ s/\s+$//; # delete trailing white space
1098 push @{$chains->{$chain}}, $line;
1100 # simply ignore the rest
1105 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1107 # compute digest for each chain
1108 foreach my $chain (keys %$chains) {
1109 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1115 sub ruleset_generate_cmdstr
{
1116 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1118 return if defined($rule->{enable
}) && !$rule->{enable
};
1120 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1122 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1123 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1127 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1128 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1130 my $source = $rule->{source
};
1131 my $dest = $rule->{dest
};
1134 if ($source =~ m/^(\+)(\S+)$/) {
1135 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1136 push @cmd, "-m set --match-set PVEFW-$2 src";
1138 } elsif ($source =~ m/\-/){
1139 push @cmd, "-m iprange --src-range $source";
1142 push @cmd, "-s $source";
1147 if ($dest =~ m/^(\+)(\S+)$/) {
1148 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1149 push @cmd, "-m set --match-set PVEFW-$2 dst";
1151 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1152 push @cmd, "-m iprange --dst-range $dest";
1155 push @cmd, "-s $dest";
1159 if ($rule->{proto
}) {
1160 push @cmd, "-p $rule->{proto}";
1163 $multiport++ if $nbdport > 1;
1164 $multiport++ if $nbsport > 1;
1166 push @cmd, "--match multiport" if $multiport;
1168 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1169 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1171 if ($rule->{dport
}) {
1172 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1173 # Note: we use dport to store --icmp-type
1174 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1175 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1178 if ($multiport == 2) {
1179 push @cmd, "--ports $rule->{dport}";
1181 push @cmd, "--dports $rule->{dport}";
1184 push @cmd, "--dport $rule->{dport}";
1189 if ($rule->{sport
}) {
1191 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1193 push @cmd, "--sport $rule->{sport}";
1196 } elsif ($rule->{dport
} || $rule->{sport
}) {
1197 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport
};
1198 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport
};
1201 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1203 if (my $action = $rule->{action
}) {
1204 $action = $actions->{$action} if defined($actions->{$action});
1205 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1206 push @cmd, $goto ?
"-g $action" : "-j $action";
1209 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1212 sub ruleset_generate_rule
{
1213 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1217 if ($rule->{macro}) {
1218 $rules = &$apply_macro($rule->{macro}, $rule);
1223 foreach my $tmp (@$rules) {
1224 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1225 ruleset_addrule
($ruleset, $chain, $cmdstr);
1230 sub ruleset_generate_rule_insert
{
1231 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1233 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1235 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1236 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1240 sub ruleset_create_chain
{
1241 my ($ruleset, $chain) = @_;
1243 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1244 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1246 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1248 $ruleset->{$chain} = [];
1251 sub ruleset_chain_exist
{
1252 my ($ruleset, $chain) = @_;
1254 return $ruleset->{$chain} ?
1 : undef;
1257 sub ruleset_addrule
{
1258 my ($ruleset, $chain, $rule) = @_;
1260 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1262 push @{$ruleset->{$chain}}, "-A $chain $rule";
1265 sub ruleset_insertrule
{
1266 my ($ruleset, $chain, $rule) = @_;
1268 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1270 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1273 sub get_log_rule_base
{
1274 my ($chain, $vmid, $msg, $loglevel) = @_;
1276 die "internal error - no log level" if !defined($loglevel);
1278 $vmid = 0 if !defined($vmid);
1280 # Note: we use special format for prefix to pass further
1281 # info to log daemon (VMID, LOGVELEL and CHAIN)
1283 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1286 sub ruleset_addlog {
1287 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1289 return if !defined($loglevel);
1291 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1293 $logrule = "$rule $logrule" if defined($rule);
1295 ruleset_addrule($ruleset, $chain, $logrule)
1298 sub generate_bridge_chains {
1299 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
1301 my $options = $hostfw_conf->{options} || {};
1303 die "error
: detected direct route to bridge
'$bridge'\n"
1304 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
1306 if (!ruleset_chain_exist($ruleset, "$bridge-FW
")) {
1307 ruleset_create_chain($ruleset, "$bridge-FW
");
1308 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-FW
");
1309 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-FW
");
1312 if (!ruleset_chain_exist($ruleset, "$bridge-OUT
")) {
1313 ruleset_create_chain($ruleset, "$bridge-OUT
");
1314 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-in
-j
$bridge-OUT
");
1315 ruleset_insertrule($ruleset, "PVEFW-INPUT
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-OUT
");
1318 if (!ruleset_chain_exist($ruleset, "$bridge-IN
")) {
1319 ruleset_create_chain($ruleset, "$bridge-IN
");
1320 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j
$bridge-IN
");
1321 ruleset_addrule($ruleset, "$bridge-FW
", "-m mark
--mark
1 -j ACCEPT
");
1322 # accept traffic to unmanaged bridge ports
1323 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j ACCEPT
");
1327 sub ruleset_add_chain_policy {
1328 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1330 if ($policy eq 'ACCEPT') {
1332 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1333 { ACCEPT => $accept_action});
1335 } elsif ($policy eq 'DROP') {
1337 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1339 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1341 ruleset_addrule($ruleset, $chain, "-j DROP
");
1342 } elsif ($policy eq 'REJECT') {
1343 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1345 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1347 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1350 die "internal error
: unknown policy
'$policy'";
1354 sub ruleset_create_vm_chain {
1355 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1357 ruleset_create_chain($ruleset, $chain);
1358 my $accept = generate_nfqueue($options);
1360 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1361 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1364 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1365 if ($direction eq 'OUT') {
1366 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1367 proto => 'udp', sport => 68, dport => 67 });
1369 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1370 proto => 'udp', sport => 67, dport => 68 });
1374 if ($options->{tcpflags}) {
1375 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1378 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1379 if ($direction eq 'OUT') {
1380 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-g PVEFW-SET-ACCEPT-MARK
");
1382 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1385 if ($direction eq 'OUT') {
1386 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1387 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1389 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1393 sub ruleset_generate_vm_rules {
1394 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1396 my $lc_direction = lc($direction);
1398 foreach my $rule (@$rules) {
1399 next if $rule->{iface} && $rule->{iface} ne $netid;
1400 next if !$rule->{enable};
1401 if ($rule->{type} eq 'group') {
1402 my $group_chain = "GROUP-
$rule->{action
}-$direction";
1403 if(!ruleset_chain_exist($ruleset, $group_chain)){
1404 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
1406 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1407 if ($direction eq 'OUT'){
1408 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j RETURN
");
1410 my $accept = generate_nfqueue($options);
1411 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$accept");
1415 next if $rule->{type} ne $lc_direction;
1416 if ($direction eq 'OUT') {
1417 ruleset_generate_rule($ruleset, $chain, $rule,
1418 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1420 my $accept = generate_nfqueue($options);
1421 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1427 sub generate_nfqueue {
1431 if($options->{ips}){
1432 $action = "NFQUEUE
";
1433 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1434 if(defined($3) && defined($1)) {
1435 $action .= " --queue-balance
$1:$3";
1436 }elsif (defined($1)) {
1437 $action .= " --queue-num
$1";
1440 $action .= " --queue-bypass
";
1448 sub ruleset_generate_vm_ipsrules {
1449 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1451 if ($options->{ips} && $direction eq 'IN') {
1452 my $nfqueue = generate_nfqueue($options);
1454 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1455 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1458 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1459 ruleset_create_chain($ruleset, "$bridge-IPS
");
1460 ruleset_insertrule($ruleset, "PVEFW-IPS
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-IPS
");
1463 ruleset_addrule($ruleset, "$bridge-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1467 sub generate_venet_rules_direction {
1468 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1470 parse_address_list($ip); # make sure we have a valid $ip list
1472 my $lc_direction = lc($direction);
1474 my $rules = $vmfw_conf->{rules};
1476 my $options = $vmfw_conf->{options};
1477 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1479 my $chain = "venet0-
$vmid-$direction";
1481 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1483 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1488 if ($direction eq 'OUT') {
1489 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1491 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1494 my $accept = generate_nfqueue($options);
1495 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1496 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1498 # plug into FORWARD, INPUT and OUTPUT chain
1499 if ($direction eq 'OUT') {
1500 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD
", {
1503 iface_in => 'venet0'});
1505 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT
", {
1508 iface_in => 'venet0'});
1510 ruleset_generate_rule($ruleset, "PVEFW-FORWARD
", {
1513 iface_out => 'venet0'});
1515 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT
", {
1518 iface_out => 'venet0'});
1522 sub generate_tap_rules_direction {
1523 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1525 my $lc_direction = lc($direction);
1527 my $rules = $vmfw_conf->{rules};
1529 my $options = $vmfw_conf->{options};
1530 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1532 my $tapchain = "$iface-$direction";
1534 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1536 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1538 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1543 if ($direction eq 'OUT') {
1544 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1546 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1549 my $accept = generate_nfqueue($options);
1550 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1551 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1553 # plug the tap chain to bridge chain
1554 if ($direction eq 'IN') {
1555 ruleset_insertrule($ruleset, "$bridge-IN
",
1556 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1558 ruleset_insertrule($ruleset, "$bridge-OUT
",
1559 "-m physdev
--physdev-in
$iface -j
$tapchain");
1563 sub enable_host_firewall {
1564 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1566 # fixme: allow security groups
1568 my $options = $hostfw_conf->{options};
1569 my $rules = $hostfw_conf->{rules};
1571 # host inbound firewall
1572 my $chain = "PVEFW-HOST-IN
";
1573 ruleset_create_chain($ruleset, $chain);
1575 my $loglevel = get_option_log_level($options, "log_level_in
");
1577 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1578 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1581 if ($options->{tcpflags}) {
1582 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1585 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1586 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1587 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1588 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1589 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1590 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1592 # we use RETURN because we need to check also tap rules
1593 my $accept_action = 'RETURN';
1595 foreach my $rule (@$rules) {
1596 next if $rule->{type} ne 'in';
1597 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1600 # implement input policy
1601 my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1602 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1604 # host outbound firewall
1605 $chain = "PVEFW-HOST-OUT
";
1606 ruleset_create_chain($ruleset, $chain);
1608 $loglevel = get_option_log_level($options, "log_level_out
");
1610 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1611 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1612 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1613 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1614 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1615 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1617 # we use RETURN because we may want to check other thigs later
1618 $accept_action = 'RETURN';
1620 foreach my $rule (@$rules) {
1621 next if $rule->{type} ne 'out';
1622 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1625 # implement output policy
1626 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1627 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1629 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1630 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1633 sub generate_group_rules {
1634 my ($ruleset, $cluster_conf, $group) = @_;
1635 die "no such security group
'$group'\n" if !$cluster_conf->{groups}->{$group};
1637 my $rules = $cluster_conf->{groups}->{$group};
1639 my $chain = "GROUP-
${group
}-IN
";
1641 ruleset_create_chain($ruleset, $chain);
1642 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1644 foreach my $rule (@$rules) {
1645 next if $rule->{type} ne 'in';
1646 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1649 $chain = "GROUP-
${group
}-OUT
";
1651 ruleset_create_chain($ruleset, $chain);
1652 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1654 foreach my $rule (@$rules) {
1655 next if $rule->{type} ne 'out';
1656 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1657 # check also other tap rules later
1658 ruleset_generate_rule($ruleset, $chain, $rule,
1659 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1664 my $valid_netdev_names = {};
1665 for (my $i = 0; $i < $MAX_NETS; $i++) {
1666 $valid_netdev_names->{"net
$i"} = 1;
1670 my ($line, $need_iface, $allow_groups) = @_;
1672 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
1674 # we can add single line comments to the end of the rule
1675 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1677 # we can disable a rule when prefixed with '|'
1680 $enable = 0 if $line =~ s/^\|//;
1682 my @data = split(/\s+/, $line);
1683 my $expected_elements = $need_iface ? 8 : 7;
1685 die "wrong number of rule elements
\n" if scalar(@data) > $expected_elements;
1688 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1690 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1693 die "incomplete rule
\n" if ! ($type && $action);
1699 if ($type eq 'in' || $type eq 'out') {
1700 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1702 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1704 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1705 die "unknown
macro '$1'\n" if !$preferred_name;
1706 $macro = $preferred_name;
1708 die "unknown action
'$action'\n";
1710 } elsif ($type eq 'group') {
1711 die "wrong number of rule elements
\n" if scalar(@data) != 3;
1712 die "groups disabled
\n" if !$allow_groups;
1714 die "invalid characters
in group name
\n" if $action !~ m/^[A-Za-z0-9_\-]+$/;
1716 die "unknown rule type
'$type'\n";
1720 $iface = undef if $iface && $iface eq '-';
1723 $proto = undef if $proto && $proto eq '-';
1724 pve_fw_verify_protocol_spec($proto) if $proto;
1726 $source = undef if $source && $source eq '-';
1727 $dest = undef if $dest && $dest eq '-';
1729 $dport = undef if $dport && $dport eq '-';
1730 $sport = undef if $sport && $sport eq '-';
1732 parse_port_name_number_or_range($dport) if defined($dport);
1733 parse_port_name_number_or_range($sport) if defined($sport);
1735 parse_address_list($source) if $source;
1736 parse_address_list($dest) if $dest;
1741 comment => $comment,
1753 sub parse_vmfw_option {
1758 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
1760 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
1763 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1765 $value = $2 ? lc($3) : '';
1766 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1769 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1774 die "can
't parse option '$line'\n"
1777 return ($opt, $value);
1780 sub parse_hostfw_option {
1785 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1787 if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1790 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1792 $value = $2 ? lc($3) : '';
1793 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1796 } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
1801 die "can't parse option
'$line'\n"
1804 return ($opt, $value);
1807 sub parse_clusterfw_option {
1812 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1817 die "can
't parse option '$line'\n"
1820 return ($opt, $value);
1823 sub parse_vm_fw_rules {
1824 my ($filename, $fh) = @_;
1826 my $res = { rules => [], options => {}};
1830 my $digest = Digest::SHA->new('sha1
');
1832 while (defined(my $line = <$fh>)) {
1833 $digest->add($line);
1835 next if $line =~ m/^#/;
1836 next if $line =~ m/^\s*$/;
1838 my $linenr = $fh->input_line_number();
1839 my $prefix = "$filename (line $linenr)";
1841 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1843 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1847 warn "$prefix: skip line - no section";
1851 next if !$res->{$section}; # skip undefined section
1853 if ($section eq 'options
') {
1855 my ($opt, $value) = parse_vmfw_option($line);
1856 $res->{options}->{$opt} = $value;
1858 warn "$prefix: $@" if $@;
1863 eval { $rule = parse_fw_rule($line, 1, 1); };
1865 warn "$prefix: $err";
1869 push @{$res->{$section}}, $rule;
1872 $res->{digest} = $digest->b64digest;
1877 sub parse_host_fw_rules {
1878 my ($filename, $fh) = @_;
1880 my $res = { rules => [], options => {}};
1884 my $digest = Digest::SHA->new('sha1
');
1886 while (defined(my $line = <$fh>)) {
1887 $digest->add($line);
1889 next if $line =~ m/^#/;
1890 next if $line =~ m/^\s*$/;
1892 my $linenr = $fh->input_line_number();
1893 my $prefix = "$filename (line $linenr)";
1895 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1897 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1901 warn "$prefix: skip line - no section";
1905 next if !$res->{$section}; # skip undefined section
1907 if ($section eq 'options
') {
1909 my ($opt, $value) = parse_hostfw_option($line);
1910 $res->{options}->{$opt} = $value;
1912 warn "$prefix: $@" if $@;
1917 eval { $rule = parse_fw_rule($line, 1, 1); };
1919 warn "$prefix: $err";
1923 push @{$res->{$section}}, $rule;
1926 $res->{digest} = $digest->b64digest;
1931 sub parse_cluster_fw_rules {
1932 my ($filename, $fh) = @_;
1937 my $res = { rules => [], options => {}, groups => {}, ipset => {} };
1939 my $digest = Digest::SHA->new('sha1
');
1941 while (defined(my $line = <$fh>)) {
1942 $digest->add($line);
1944 next if $line =~ m/^#/;
1945 next if $line =~ m/^\s*$/;
1947 my $linenr = $fh->input_line_number();
1948 my $prefix = "$filename (line $linenr)";
1950 if ($line =~ m/^\[options\]$/i) {
1951 $section = 'options
';
1955 if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
1956 $section = 'groups
';
1961 if ($line =~ m/^\[rules\]$/i) {
1966 if ($line =~ m/^\[ipset\s+(\S+)\]\s*$/i) {
1973 warn "$prefix: skip line - no section\n";
1977 if ($section eq 'options
') {
1979 my ($opt, $value) = parse_clusterfw_option($line);
1980 $res->{options}->{$opt} = $value;
1982 warn "$prefix: $@" if $@;
1983 } elsif ($section eq 'rules
') {
1985 eval { $rule = parse_fw_rule($line, 1, 1); };
1987 warn "$prefix: $err";
1990 push @{$res->{$section}}, $rule;
1991 } elsif ($section eq 'groups
') {
1993 eval { $rule = parse_fw_rule($line, 0, 0); };
1995 warn "$prefix: $err";
1998 push @{$res->{$section}->{$group}}, $rule;
1999 } elsif ($section eq 'ipset
') {
2001 $line =~ m/^(\!)?\s*((\d+)\.(\d+)\.(\d+)\.(\d+)(\/(\d+))?)/;
2006 warn "$prefix: $line is not an valid ip address\n";
2009 if (!Net::IP->new($ip)) {
2010 warn "$prefix: $line is not an valid ip address\n";
2015 if ($feature_ipset_nomatch) {
2016 push @{$res->{$section}->{$group}}, "$ip nomatch";
2018 warn "$prefix: ignore $line - nomatch not supported by kernel\n";
2021 push @{$res->{$section}->{$group}}, $ip;
2026 $res->{digest} = $digest->b64digest;
2031 my ($code, @param) = @_;
2035 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2042 sub read_local_vm_config {
2047 my $vmdata = { openvz => $openvz, qemu => $qemu };
2049 my $vmlist = PVE::Cluster::get_vmlist();
2050 return $vmdata if !$vmlist || !$vmlist->{ids};
2051 my $ids = $vmlist->{ids};
2053 foreach my $vmid (keys %$ids) {
2054 next if !$vmid; # skip VE0
2055 my $d = $ids->{$vmid};
2056 next if !$d->{node} || $d->{node} ne $nodename;
2057 next if !$d->{type};
2058 if ($d->{type} eq 'openvz
') {
2059 if ($have_pve_manager) {
2060 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2061 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2062 $openvz->{$vmid} = $conf;
2065 } elsif ($d->{type} eq 'qemu
') {
2066 if ($have_qemu_server) {
2067 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2068 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2069 $qemu->{$vmid} = $conf;
2078 sub load_vmfw_conf {
2083 my $filename = "/etc/pve/firewall/$vmid.fw";
2084 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2085 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2091 my $format_rules = sub {
2092 my ($rules, $need_iface) = @_;
2096 foreach my $rule (@$rules) {
2097 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
') {
2098 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2099 $raw .= uc($rule->{type});
2100 if ($rule->{macro}) {
2101 $raw .= " $rule->{macro}($rule->{action})";
2103 $raw .= " " . $rule->{action};
2105 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
2106 $raw .= " " . ($rule->{source} || '-');
2107 $raw .= " " . ($rule->{dest} || '-');
2108 $raw .= " " . ($rule->{proto} || '-');
2109 $raw .= " " . ($rule->{dport} || '-');
2110 $raw .= " " . ($rule->{sport} || '-');
2111 $raw .= " # " . encode('utf8
', $rule->{comment})
2112 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2115 die "implement me '$rule->{type
}'";
2122 my $format_options = sub {
2127 $raw .= "[OPTIONS]\n\n";
2128 foreach my $opt (keys %$options) {
2129 $raw .= "$opt: $options->{$opt}\n";
2136 sub save_vmfw_conf {
2137 my ($vmid, $vmfw_conf) = @_;
2141 my $options = $vmfw_conf->{options};
2142 $raw .= &$format_options($options) if scalar(keys %$options);
2144 my $rules = $vmfw_conf->{rules};
2145 if (scalar(@$rules)) {
2146 $raw .= "[RULES]\n\n";
2147 $raw .= &$format_rules($rules, 1);
2151 my $filename = "/etc/pve/firewall/$vmid.fw";
2152 PVE::Tools::file_set_contents($filename, $raw);
2155 sub read_vm_firewall_configs {
2157 my $vmfw_configs = {};
2159 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2160 my $vmfw_conf = load_vmfw_conf($vmid);
2161 next if !$vmfw_conf->{options}; # skip if file does not exists
2162 $vmfw_configs->{$vmid} = $vmfw_conf;
2165 return $vmfw_configs;
2168 sub get_option_log_level {
2169 my ($options, $k) = @_;
2171 my $v = $options->{$k};
2172 $v = $default_log_level if !defined($v);
2174 return undef if $v eq '' || $v eq 'nolog
';
2176 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2178 return $v if ($v >= 0) && ($v <= 7);
2180 warn "unknown log level ($k = '$v')\n";
2185 sub generate_std_chains {
2186 my ($ruleset, $options) = @_;
2188 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2190 # same as shorewall smurflog.
2191 my $chain = 'PVEFW-smurflog
';
2193 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2194 push @{$pve_std_chains->{$chain}}, "-j DROP";
2196 # same as shorewall logflags action.
2197 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2198 $chain = 'PVEFW-logflags
';
2199 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2200 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2201 push @{$pve_std_chains->{$chain}}, "-j DROP";
2203 foreach my $chain (keys %$pve_std_chains) {
2204 ruleset_create_chain($ruleset, $chain);
2205 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2207 ruleset_generate_rule($ruleset, $chain, $rule);
2209 ruleset_addrule($ruleset, $chain, $rule);
2215 sub generate_ipset_chains {
2216 my ($ipset_ruleset, $fw_conf) = @_;
2218 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2219 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
2223 sub generate_ipset {
2224 my ($ipset_ruleset, $name, $options) = @_;
2226 my $hashsize = scalar(@$options);
2227 if ($hashsize <= 64) {
2230 $hashsize = round_powerof2($hashsize);
2233 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2235 foreach my $ip (@$options) {
2236 push @{$ipset_ruleset->{$name}}, "add $name $ip";
2240 sub round_powerof2 {
2244 $int |= $int >> $_ foreach (1,2,4,8,16);
2248 sub save_pvefw_status {
2251 die "unknown status '$status' - internal error"
2252 if $status !~ m/^(stopped|active)$/;
2254 mkdir dirname($pve_fw_status_filename);
2255 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2258 sub read_pvefw_status {
2260 my $status = 'unknown
';
2262 return 'stopped
' if ! -f $pve_fw_status_filename;
2265 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2272 # fixme: move to pve-common PVE::ProcFSTools
2273 sub read_proc_net_route {
2274 my $filename = "/proc/net/route";
2278 my $fh = IO::File->new ($filename, "r");
2279 return $res if !$fh;
2281 my $int_to_quad = sub {
2282 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2285 while (defined(my $line = <$fh>)) {
2286 next if $line =~/^Iface\s+Destination/; # skip head
2287 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2288 push @{$res->{$iface}}, {
2289 dest => &$int_to_quad(hex($dest)),
2290 gateway => &$int_to_quad(hex($gateway)),
2291 mask => &$int_to_quad(hex($mask)),
2300 sub load_clusterfw_conf {
2302 my $cluster_conf = {};
2303 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
2304 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
2307 return $cluster_conf;
2310 sub save_clusterfw_conf {
2311 my ($cluster_conf) = @_;
2315 my $options = $cluster_conf->{options};
2316 $raw .= &$format_options($options) if scalar(keys %$options);
2320 my $rules = $cluster_conf->{rules};
2321 if (scalar(@$rules)) {
2322 $raw .= "[RULES]\n\n";
2323 $raw .= &$format_rules($rules, 1);
2327 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2328 my $rules = $cluster_conf->{groups}->{$group};
2329 $raw .= "[group $group]\n\n";
2330 $raw .= &$format_rules($rules, 0);
2334 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2337 sub load_hostfw_conf {
2339 my $hostfw_conf = {};
2340 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2341 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
2343 return $hostfw_conf;
2346 sub save_hostfw_conf {
2347 my ($hostfw_conf) = @_;
2351 my $options = $hostfw_conf->{options};
2352 $raw .= &$format_options($options) if scalar(keys %$options);
2354 my $rules = $hostfw_conf->{rules};
2355 if (scalar(@$rules)) {
2356 $raw .= "[RULES]\n\n";
2357 $raw .= &$format_rules($rules, 1);
2361 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2365 my $vmdata = read_local_vm_config();
2366 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2368 my $routing_table = read_proc_net_route();
2370 my $cluster_conf = load_clusterfw_conf();
2372 my $ipset_ruleset = {};
2373 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2377 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2378 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2380 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2382 my $hostfw_conf = load_hostfw_conf();
2383 my $hostfw_options = $hostfw_conf->{options} || {};
2385 generate_std_chains($ruleset, $hostfw_options);
2387 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2389 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2391 # generate firewall rules for QEMU VMs
2392 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2393 my $conf = $vmdata->{qemu}->{$vmid};
2394 my $vmfw_conf = $vmfw_configs->{$vmid};
2395 next if !$vmfw_conf;
2396 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2398 foreach my $netid (keys %$conf) {
2399 next if $netid !~ m/^net(\d+)$/;
2400 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2402 my $iface = "tap${vmid}i$1";
2404 my $bridge = $net->{bridge};
2405 next if !$bridge; # fixme: ?
2407 $bridge .= "v$net->{tag}" if $net->{tag};
2409 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2411 my $macaddr = $net->{macaddr};
2412 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2413 $vmfw_conf, $vmid, $bridge, 'IN
');
2414 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2415 $vmfw_conf, $vmid, $bridge, 'OUT
');
2419 # generate firewall rules for OpenVZ containers
2420 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2421 my $conf = $vmdata->{openvz}->{$vmid};
2423 my $vmfw_conf = $vmfw_configs->{$vmid};
2424 next if !$vmfw_conf;
2425 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2427 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2428 my $ip = $conf->{ip_address}->{value};
2429 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2430 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2433 if ($conf->{netif} && $conf->{netif}->{value}) {
2434 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2435 foreach my $netid (keys %$netif) {
2436 my $d = $netif->{$netid};
2437 my $bridge = $d->{bridge};
2439 warn "no bridge device for CT $vmid iface '$netid'\n";
2443 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2445 my $macaddr = $d->{mac};
2446 my $iface = $d->{host_ifname};
2447 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2448 $vmfw_conf, $vmid, $bridge, 'IN
');
2449 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2450 $vmfw_conf, $vmid, $bridge, 'OUT
');
2455 if($hostfw_options->{optimize}){
2457 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
2458 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
2459 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2462 # fixme: what log level should we use here?
2463 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2465 # fixme: should we really block inter-bridge traffic?
2467 # always allow traffic from containers?
2468 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2470 # disable interbridge routing
2471 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
2472 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
2473 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2474 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2475 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
2476 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2478 return wantarray ? ($ruleset, $hostfw_conf, $ipset_ruleset) : $ruleset;
2481 sub get_ruleset_status {
2482 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2484 my $statushash = {};
2486 foreach my $chain (sort keys %$ruleset) {
2487 my $sig = &$digest_fn($ruleset->{$chain});
2489 $statushash->{$chain}->{sig} = $sig;
2491 my $oldsig = $active_chains->{$chain};
2492 if (!defined($oldsig)) {
2493 $statushash->{$chain}->{action} = 'create
';
2495 if ($oldsig eq $sig) {
2496 $statushash->{$chain}->{action} = 'exists';
2498 $statushash->{$chain}->{action} = 'update
';
2501 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2502 foreach my $cmd (@{$ruleset->{$chain}}) {
2503 print "\t$cmd\n" if $verbose;
2507 foreach my $chain (sort keys %$active_chains) {
2508 if (!defined($ruleset->{$chain})) {
2509 my $sig = $active_chains->{$chain};
2510 $statushash->{$chain}->{action} = 'delete';
2511 $statushash->{$chain}->{sig} = $sig;
2512 print "delete $chain ($sig)\n" if $verbose;
2519 sub print_sig_rule {
2520 my ($chain, $sig) = @_;
2522 # We just use this to store a SHA1 checksum used to detect changes
2523 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2526 sub get_ruleset_cmdlist {
2527 my ($ruleset, $verbose) = @_;
2529 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2531 my ($active_chains, $hooks) = iptables_get_chains();
2532 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2534 # create missing chains first
2535 foreach my $chain (sort keys %$ruleset) {
2536 my $stat = $statushash->{$chain};
2537 die "internal error" if !$stat;
2538 next if $stat->{action} ne 'create
';
2540 $cmdlist .= ":$chain - [0:0]\n";
2543 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2544 if (!$hooks->{$h}) {
2545 $cmdlist .= "-A $h -j PVEFW-$h\n";
2549 foreach my $chain (sort keys %$ruleset) {
2550 my $stat = $statushash->{$chain};
2551 die "internal error" if !$stat;
2553 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2554 $cmdlist .= "-F $chain\n";
2555 foreach my $cmd (@{$ruleset->{$chain}}) {
2556 $cmdlist .= "$cmd\n";
2558 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2559 } elsif ($stat->{action
} eq 'delete') {
2560 die "internal error"; # this should not happen
2561 } elsif ($stat->{action
} eq 'exists') {
2564 die "internal error - unknown status '$stat->{action}'";
2568 foreach my $chain (keys %$statushash) {
2569 next if $statushash->{$chain}->{action
} ne 'delete';
2570 $cmdlist .= "-F $chain\n";
2572 foreach my $chain (keys %$statushash) {
2573 next if $statushash->{$chain}->{action
} ne 'delete';
2574 next if $chain eq 'PVEFW-INPUT';
2575 next if $chain eq 'PVEFW-OUTPUT';
2576 next if $chain eq 'PVEFW-FORWARD';
2577 $cmdlist .= "-X $chain\n";
2580 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2582 $cmdlist .= "COMMIT\n";
2584 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2587 sub get_ipset_cmdlist
{
2588 my ($ruleset, $verbose) = @_;
2592 my $delete_cmdlist = "";
2594 my $active_chains = ipset_get_chains
();
2595 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2597 foreach my $chain (sort keys %$ruleset) {
2598 my $stat = $statushash->{$chain};
2599 die "internal error" if !$stat;
2601 if ($stat->{action
} eq 'create') {
2602 foreach my $cmd (@{$ruleset->{$chain}}) {
2603 $cmdlist .= "$cmd\n";
2607 if ($stat->{action
} eq 'update') {
2608 my $chain_swap = $chain."_swap";
2610 foreach my $cmd (@{$ruleset->{$chain}}) {
2611 $cmd =~ s/$chain/$chain_swap/;
2612 $cmdlist .= "$cmd\n";
2614 $cmdlist .= "swap $chain_swap $chain\n";
2615 $cmdlist .= "flush $chain_swap\n";
2616 $cmdlist .= "destroy $chain_swap\n";
2621 foreach my $chain (keys %$statushash) {
2622 next if $statushash->{$chain}->{action
} ne 'delete';
2624 $delete_cmdlist .= "flush $chain\n";
2625 $delete_cmdlist .= "destroy $chain\n";
2628 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
2630 return ($cmdlist, $delete_cmdlist, $changes);
2634 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2636 enable_bridge_firewall
();
2638 update_nf_conntrack_max
($hostfw_conf);
2640 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2641 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
2643 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
2646 if ($ipset_changes) {
2647 print "ipset changes:\n";
2648 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2649 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2653 print "iptables changes:\n";
2658 ipset_restore_cmdlist
($ipset_create_cmdlist);
2660 iptables_restore_cmdlist
($cmdlist);
2662 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2664 # test: re-read status and check if everything is up to date
2665 my $active_chains = iptables_get_chains
();
2666 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
2669 foreach my $chain (sort keys %$ruleset) {
2670 my $stat = $statushash->{$chain};
2671 if ($stat->{action
} ne 'exists') {
2672 warn "unable to update chain '$chain'\n";
2677 die "unable to apply firewall changes\n" if $errors;
2680 sub update_nf_conntrack_max
{
2681 my ($hostfw_conf) = @_;
2683 my $max = 65536; # reasonable default
2685 my $options = $hostfw_conf->{options
} || {};
2687 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
2688 $max = $options->{nf_conntrack_max
};
2689 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2692 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2693 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2695 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
2697 if ($current != $max) {
2698 my $hashsize = int($max/4);
2699 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
2700 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
2704 sub remove_pvefw_chains
{
2706 my ($chash, $hooks) = iptables_get_chains
();
2707 my $cmdlist = "*filter\n";
2709 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2711 $cmdlist .= "-D $h -j PVEFW-$h\n";
2715 foreach my $chain (keys %$chash) {
2716 $cmdlist .= "-F $chain\n";
2719 foreach my $chain (keys %$chash) {
2720 $cmdlist .= "-X $chain\n";
2722 $cmdlist .= "COMMIT\n";
2724 iptables_restore_cmdlist
($cmdlist);
2728 my ($start, $verbose) = @_;
2731 my $status = read_pvefw_status
();
2733 my ($ruleset, $hostfw_conf, $ipset_ruleset) = compile
();
2735 if ($start || $status eq 'active') {
2737 save_pvefw_status
('active') if ($status ne 'active');
2739 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
2741 print "Firewall not active (status = $status)\n" if $verbose;