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 $feature_ipset_nomatch = 0;
61 my (undef, undef, $release) = POSIX
::uname
();
62 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
63 my ($major, $minor) = ($1, $2);
64 $feature_ipset_nomatch = 1 if ($major > 3) ||
65 ($major == 3 && $minor >= 7);
72 my $nodename = PVE
::INotify
::nodename
();
74 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
75 my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
77 my $default_log_level = 'info';
79 my $log_level_hash = {
90 # imported/converted from: /usr/share/shorewall/macro.*
94 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
95 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
98 "Auth (identd) traffic",
99 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
102 "Border Gateway Protocol traffic",
103 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
106 "BitTorrent traffic for BitTorrent 3.1 and earlier",
107 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
108 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
111 "BitTorrent traffic for BitTorrent 3.2 and later",
112 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
113 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
116 "Concurrent Versions System pserver traffic",
117 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
120 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
121 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
122 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
123 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
126 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
127 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
128 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
131 "Distributed Checksum Clearinghouse spam filtering mechanism",
132 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
135 "Forwarded DHCP traffic (bidirectional)",
136 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
137 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
140 "Domain Name System traffic (upd and tcp)",
141 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
142 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
145 "Distributed Compiler service",
146 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
149 "File Transfer Protocol",
150 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
153 "Finger protocol (RFC 742)",
154 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
157 "GNUnet secure peer-to-peer networking traffic",
158 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
159 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
160 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
161 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
164 "Generic Routing Encapsulation tunneling protocol (bidirectional)",
165 { action
=> 'PARAM', proto
=> '47' },
166 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
169 "Git distributed revision control traffic",
170 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
173 "OpenPGP HTTP keyserver protocol traffic",
174 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
177 "Hypertext Transfer Protocol (WWW)",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
181 "Hypertext Transfer Protocol (WWW) over SSL",
182 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
185 "Internet Cache Protocol V2 (Squid) traffic",
186 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
189 "AOL Instant Messenger traffic",
190 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
193 "Internet Message Access Protocol",
194 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
197 "Internet Message Access Protocol over SSL",
198 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
201 "IPIP capsulation traffic (bidirectional)",
202 { action
=> 'PARAM', proto
=> '94' },
203 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '94' },
206 "IPsec traffic (bidirectional)",
207 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
208 { action
=> 'PARAM', proto
=> '50' },
209 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
210 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
213 "IPsec authentication (AH) traffic (bidirectional)",
214 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
215 { action
=> 'PARAM', proto
=> '51' },
216 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
217 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '51' },
220 "IPsec traffic and Nat-Traversal (bidirectional)",
221 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
222 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
223 { action
=> 'PARAM', proto
=> '50' },
224 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500' },
225 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '4500' },
226 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
229 "Internet Relay Chat traffic",
230 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
233 "HP Jetdirect printing",
234 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
237 "Layer 2 Tunneling Protocol traffic",
238 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
239 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1701' },
242 "Lightweight Directory Access Protocol traffic",
243 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
246 "Secure Lightweight Directory Access Protocol traffic",
247 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
250 "Microsoft Notification Protocol",
251 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
254 "Microsoft SQL Server",
255 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
258 "Mail traffic (SMTP, SMTPS, Submission)",
259 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
260 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
261 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
264 "Munin networked resource monitoring traffic",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
272 "NNTP traffic (Usenet).",
273 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
276 "Encrypted NNTP traffic (Usenet)",
277 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
280 "Network Time Protocol (ntpd)",
281 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
284 "Bi-directional NTP (for NTP peers)",
285 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
286 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '123' },
289 "OSPF multicast traffic",
290 { action
=> 'PARAM', proto
=> '89' },
294 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
297 "Symantec PCAnywere (tm)",
298 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
299 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
303 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
306 "Encrypted POP3 traffic",
307 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
310 "Point-to-Point Tunneling Protocol",
311 { action
=> 'PARAM', proto
=> '47' },
312 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
313 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
317 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
324 "Line Printer protocol printing",
325 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
328 "Microsoft Remote Desktop Protocol traffic",
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
332 "Routing Information Protocol (bidirectional)",
333 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
334 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '520' },
337 "BIND remote management protocol",
338 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
341 "Razor Antispam System",
342 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
345 "Remote time retrieval (rdate)",
346 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
350 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
353 "SANE network scanning",
354 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
357 "Microsoft SMB traffic",
358 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
359 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
360 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
361 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
364 "Microsoft SMB traffic (bidirectional)",
365 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
366 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
367 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
368 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
369 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '135,445' },
370 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '137:139' },
371 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
372 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'tcp', dport
=> '135,139,445' },
375 "Samba Web Administration Tool",
376 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
379 "Simple Mail Transfer Protocol",
380 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
383 "Encrypted Simple Mail Transfer Protocol",
384 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
387 "Simple Network Management Protocol",
388 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
389 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
392 "Spam Assassin SPAMD traffic",
393 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
396 "Secure shell traffic",
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
400 "Subversion server (svnserve)",
401 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
404 "SixXS IPv6 Deployment and Tunnel Broker",
405 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
406 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
407 { action
=> 'PARAM', proto
=> '41' },
408 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
411 "Squid web proxy traffic",
412 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
415 "Mail message submission traffic",
416 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
419 "Syslog protocol (RFC 5424) traffic",
420 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
421 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
424 "Trivial File Transfer Protocol traffic",
425 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
436 "RFC 868 Time protocol",
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
440 "Traceroute (for up to 30 hops) traffic",
441 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
442 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
445 "VNC traffic for VNC display's 0 - 9",
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5909' },
449 "VNC traffic from Vncservers to Vncviewers in listen mode",
450 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
453 "WWW traffic (HTTP and HTTPS)",
454 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
455 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
458 "Web Cache/Proxy traffic (port 8080)",
459 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
466 "Whois (nicname, RFC 3912) traffic",
467 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
471 my $pve_fw_parsed_macros;
472 my $pve_fw_macro_descr;
473 my $pve_fw_preferred_macro_names = {};
475 my $pve_std_chains = {
476 'PVEFW-SET-ACCEPT-MARK' => [
477 "-j MARK --set-mark 1",
479 'PVEFW-DropBroadcast' => [
480 # same as shorewall 'Broadcast'
481 # simply DROP BROADCAST/MULTICAST/ANYCAST
482 # we can use this to reduce logging
483 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
484 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
485 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
486 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
489 # same as shorewall 'reject'
490 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
491 { action
=> 'DROP', source
=> '224.0.0.0/4' },
492 { action
=> 'DROP', proto
=> 'icmp' },
493 "-p tcp -j REJECT --reject-with tcp-reset",
494 "-p udp -j REJECT --reject-with icmp-port-unreachable",
495 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
496 "-j REJECT --reject-with icmp-host-prohibited",
499 # same as shorewall 'Drop', which is equal to DROP,
500 # but REJECT/DROP some packages to reduce logging,
501 # and ACCEPT critical ICMP types
502 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
503 # we are not interested in BROADCAST/MULTICAST/ANYCAST
504 { action
=> 'PVEFW-DropBroadcast' },
505 # ACCEPT critical ICMP types
506 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
507 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
508 # Drop packets with INVALID state
509 "-m conntrack --ctstate INVALID -j DROP",
510 # Drop Microsoft SMB noise
511 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
512 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
513 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
514 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
515 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
516 # Drop new/NotSyn traffic so that it doesn't get logged
517 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
519 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
522 # same as shorewall 'Reject', which is equal to Reject,
523 # but REJECT/DROP some packages to reduce logging,
524 # and ACCEPT critical ICMP types
525 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
526 # we are not interested in BROADCAST/MULTICAST/ANYCAST
527 { action
=> 'PVEFW-DropBroadcast' },
528 # ACCEPT critical ICMP types
529 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
530 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
531 # Drop packets with INVALID state
532 "-m conntrack --ctstate INVALID -j DROP",
533 # Drop Microsoft SMB noise
534 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
535 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
536 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
537 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
538 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
539 # Drop new/NotSyn traffic so that it doesn't get logged
540 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
542 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
544 'PVEFW-tcpflags' => [
545 # same as shorewall tcpflags action.
546 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
547 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
548 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
549 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
550 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
551 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
554 # same as shorewall smurfs action
555 # Filter packets for smurfs (packets with a broadcast address as the source).
556 "-s 0.0.0.0/32 -j RETURN",
557 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
558 "-s 224.0.0.0/4 -g PVEFW-smurflog",
562 # iptables -p icmp -h
563 my $icmp_type_names = {
566 'destination-unreachable' => 1,
567 'network-unreachable' => 1,
568 'host-unreachable' => 1,
569 'protocol-unreachable' => 1,
570 'port-unreachable' => 1,
571 'fragmentation-needed' => 1,
572 'source-route-failed' => 1,
573 'network-unknown' => 1,
575 'network-prohibited' => 1,
576 'host-prohibited' => 1,
577 'TOS-network-unreachable' => 1,
578 'TOS-host-unreachable' => 1,
579 'communication-prohibited' => 1,
580 'host-precedence-violation' => 1,
581 'precedence-cutoff' => 1,
582 'source-quench' => 1,
584 'network-redirect' => 1,
585 'host-redirect' => 1,
586 'TOS-network-redirect' => 1,
587 'TOS-host-redirect' => 1,
589 'router-advertisement' => 1,
590 'router-solicitation' => 1,
591 'time-exceeded' => 1,
592 'ttl-zero-during-transit' => 1,
593 'ttl-zero-during-reassembly' => 1,
594 'parameter-problem' => 1,
595 'ip-header-bad' => 1,
596 'required-option-missing' => 1,
597 'timestamp-request' => 1,
598 'timestamp-reply' => 1,
599 'address-mask-request' => 1,
600 'address-mask-reply' => 1,
603 sub init_firewall_macros
{
605 $pve_fw_parsed_macros = {};
607 foreach my $k (keys %$pve_fw_macros) {
608 my $lc_name = lc($k);
609 my $macro = $pve_fw_macros->{$k};
610 if (!ref($macro->[0])) {
611 $pve_fw_macro_descr->{$k} = shift @$macro;
613 $pve_fw_preferred_macro_names->{$lc_name} = $k;
614 $pve_fw_parsed_macros->{$k} = $macro;
618 init_firewall_macros
();
621 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
626 sub get_etc_services
{
628 return $etc_services if $etc_services;
630 my $filename = "/etc/services";
632 my $fh = IO
::File-
>new($filename, O_RDONLY
);
634 warn "unable to read '$filename' - $!\n";
640 while (my $line = <$fh>) {
642 next if $line =~m/^#/;
643 next if ($line =~m/^\s*$/);
645 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
646 $services->{byid
}->{$2}->{name
} = $1;
647 $services->{byid
}->{$2}->{port
} = $2;
648 $services->{byid
}->{$2}->{$3} = 1;
649 $services->{byname
}->{$1} = $services->{byid
}->{$2};
655 $etc_services = $services;
658 return $etc_services;
663 sub get_etc_protocols
{
664 return $etc_protocols if $etc_protocols;
666 my $filename = "/etc/protocols";
668 my $fh = IO
::File-
>new($filename, O_RDONLY
);
670 warn "unable to read '$filename' - $!\n";
676 while (my $line = <$fh>) {
678 next if $line =~m/^#/;
679 next if ($line =~m/^\s*$/);
681 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
682 $protocols->{byid
}->{$2}->{name
} = $1;
683 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
689 $etc_protocols = $protocols;
691 return $etc_protocols;
694 sub parse_address_list
{
697 return if $str =~ m/^(\+)(\S+)$/; # ipset ref
701 foreach my $elem (split(/,/, $str)) {
703 if (!Net
::IP-
>new($elem)) {
704 my $err = Net
::IP
::Error
();
705 die "invalid IP address: $err\n";
707 $iprange = 1 if $elem =~ m/-/;
710 die "you can use a range in a list\n" if $iprange && $count > 1;
713 sub parse_port_name_number_or_range
{
716 my $services = PVE
::Firewall
::get_etc_services
();
720 foreach my $item (split(/,/, $str)) {
722 if ($item =~ m/^(\d+):(\d+)$/) {
723 my ($port1, $port2) = ($1, $2);
724 die "invalid port '$port1'\n" if $port1 > 65535;
725 die "invalid port '$port2'\n" if $port2 > 65535;
726 } elsif ($item =~ m/^(\d+)$/) {
728 die "invalid port '$port'\n" if $port > 65535;
730 if ($icmp_type_names->{$item}) {
733 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
738 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
743 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
744 sub pve_fw_verify_port_spec
{
747 parse_port_name_number_or_range
($portstr);
752 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
753 sub pve_fw_verify_v4addr_spec
{
756 parse_address_list
($list);
761 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
762 sub pve_fw_verify_protocol_spec
{
765 my $protocols = get_etc_protocols
();
767 die "unknown protocol '$proto'\n" if $proto &&
768 !(defined($protocols->{byname
}->{$proto}) ||
769 defined($protocols->{byid
}->{$proto}));
775 # helper function for API
777 my $rule_properties = {
779 description
=> "Update rule at position <pos>.",
793 enum
=> ['in', 'out', 'group'],
798 enum
=> ['ACCEPT', 'DROP', 'REJECT'],
805 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
807 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
811 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
815 type
=> 'string', format
=> 'pve-fw-protocol-spec',
823 type
=> 'string', format
=> 'pve-fw-port-spec',
827 type
=> 'string', format
=> 'pve-fw-port-spec',
836 sub cleanup_fw_rule
{
837 my ($rule, $digest, $pos) = @_;
841 foreach my $k (keys %$rule) {
842 next if !$rule_properties->{$k};
844 next if !defined($v);
846 $r->{digest
} = $digest;
853 sub add_rule_properties
{
854 my ($properties) = @_;
856 foreach my $k (keys %$rule_properties) {
857 my $h = $rule_properties->{$k};
858 # copy data, so that we can modify later without side effects
859 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
865 sub delete_rule_properties
{
866 my ($rule, $delete_str) = @_;
868 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
869 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
870 if !defined($rule_properties->{$opt});
871 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
872 if $opt eq 'type' || $opt eq 'action';
873 delete $rule->{$opt};
879 my $apply_macro = sub {
880 my ($macro_name, $param, $verify) = @_;
882 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
883 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
887 foreach my $templ (@$macro_rules) {
890 foreach my $k (keys %$templ) {
891 my $v = $templ->{$k};
894 $param_used->{$k} = 1;
895 } elsif ($v eq 'DEST') {
897 $param_used->{dest
} = 1;
898 } elsif ($v eq 'SOURCE') {
899 $v = $param->{source
};
900 $param_used->{source
} = 1;
904 my $msg = "missing parameter '$k' in macro '$macro_name'";
905 raise_param_exc
({ macro => $msg }) if $verify;
910 foreach my $k (keys %$param) {
911 next if $k eq 'macro';
912 next if !defined($param->{$k});
913 next if $param_used->{$k};
914 if (defined($rule->{$k})) {
915 if ($rule->{$k} ne $param->{$k}) {
916 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
917 raise_param_exc
({ $k => $msg }) if $verify;
921 $rule->{$k} = $param->{$k};
931 my ($rule, $allow_groups) = @_;
933 my $type = $rule->{type
};
935 raise_param_exc
({ type
=> "missing property"}) if !$type;
936 raise_param_exc
({ action
=> "missing property"}) if !$rule->{action
};
938 if ($type eq 'in' || $type eq 'out') {
939 raise_param_exc
({ action
=> "unknown action '$rule->{action}'"})
940 if $rule->{action
} !~ m/^(ACCEPT|DROP|REJECT)$/;
941 } elsif ($type eq 'group') {
942 raise_param_exc
({ type
=> "security groups not allowed"})
944 raise_param_exc
({ action
=> "invalid characters in security group name"})
945 if $rule->{action
} !~ m/^[A-Za-z0-9_\-]+$/;
947 raise_param_exc
({ type
=> "unknown rule type '$type'"});
950 # fixme: verify $rule->{iface}?
952 if ($rule->{macro}) {
953 my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
954 raise_param_exc
({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
955 $rule->{macro} = $preferred_name;
958 if ($rule->{dport
}) {
959 eval { parse_port_name_number_or_range
($rule->{dport
}); };
960 raise_param_exc
({ dport
=> $@ }) if $@;
963 if ($rule->{sport
}) {
964 eval { parse_port_name_number_or_range
($rule->{sport
}); };
965 raise_param_exc
({ sport
=> $@ }) if $@;
968 if ($rule->{source
}) {
969 eval { parse_address_list
($rule->{source
}); };
970 raise_param_exc
({ source
=> $@ }) if $@;
974 eval { parse_address_list
($rule->{dest
}); };
975 raise_param_exc
({ dest
=> $@ }) if $@;
978 if ($rule->{macro}) {
979 &$apply_macro($rule->{macro}, $rule, 1);
986 my ($rule, $param) = @_;
988 foreach my $k (keys %$rule_properties) {
989 if (defined(my $v = $param->{$k})) {
990 if ($v eq '' || $v eq '-') {
1006 my $bridge_firewall_enabled = 0;
1008 sub enable_bridge_firewall
{
1010 return if $bridge_firewall_enabled; # only once
1012 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1013 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1015 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1016 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1018 $bridge_firewall_enabled = 1;
1021 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1023 sub iptables_restore_cmdlist
{
1026 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1029 sub ipset_restore_cmdlist
{
1032 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1035 sub iptables_get_chains
{
1039 # check what chains we want to track
1040 my $is_pvefw_chain = sub {
1043 return 1 if $name =~ m/^PVEFW-\S+$/;
1045 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1047 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1049 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1051 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
1052 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1064 return if $line =~ m/^#/;
1065 return if $line =~ m/^\s*$/;
1067 if ($line =~ m/^\*(\S+)$/) {
1072 return if $table ne 'filter';
1074 if ($line =~ m/^:(\S+)\s/) {
1076 return if !&$is_pvefw_chain($chain);
1077 $res->{$chain} = "unknown";
1078 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1079 my ($chain, $sig) = ($1, $2);
1080 return if !&$is_pvefw_chain($chain);
1081 $res->{$chain} = $sig;
1082 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1085 # simply ignore the rest
1090 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1092 return wantarray ?
($res, $hooks) : $res;
1095 sub iptables_chain_digest
{
1097 my $digest = Digest
::SHA-
>new('sha1');
1098 foreach my $rule (@$rules) { # order is important
1099 $digest->add($rule);
1101 return $digest->b64digest;
1104 sub ipset_chain_digest
{
1107 my $digest = Digest
::SHA-
>new('sha1');
1108 foreach my $rule (sort @$rules) { # note: sorted
1109 $digest->add($rule);
1111 return $digest->b64digest;
1114 sub ipset_get_chains
{
1122 return if $line =~ m/^#/;
1123 return if $line =~ m/^\s*$/;
1124 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1126 $line =~ s/\s+$//; # delete trailing white space
1127 push @{$chains->{$chain}}, $line;
1129 # simply ignore the rest
1134 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1136 # compute digest for each chain
1137 foreach my $chain (keys %$chains) {
1138 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1144 sub ruleset_generate_cmdstr
{
1145 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1147 return if defined($rule->{enable
}) && !$rule->{enable
};
1149 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1151 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1152 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1156 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1157 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1159 my $source = $rule->{source
};
1160 my $dest = $rule->{dest
};
1163 if ($source =~ m/^(\+)(\S+)$/) {
1164 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1165 push @cmd, "-m set --match-set PVEFW-$2 src";
1167 } elsif ($source =~ m/\-/){
1168 push @cmd, "-m iprange --src-range $source";
1171 push @cmd, "-s $source";
1176 if ($dest =~ m/^(\+)(\S+)$/) {
1177 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1178 push @cmd, "-m set --match-set PVEFW-$2 dst";
1180 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1181 push @cmd, "-m iprange --dst-range $dest";
1184 push @cmd, "-s $dest";
1188 if ($rule->{proto
}) {
1189 push @cmd, "-p $rule->{proto}";
1192 $multiport++ if $nbdport > 1;
1193 $multiport++ if $nbsport > 1;
1195 push @cmd, "--match multiport" if $multiport;
1197 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1198 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1200 if ($rule->{dport
}) {
1201 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1202 # Note: we use dport to store --icmp-type
1203 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1204 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1207 if ($multiport == 2) {
1208 push @cmd, "--ports $rule->{dport}";
1210 push @cmd, "--dports $rule->{dport}";
1213 push @cmd, "--dport $rule->{dport}";
1218 if ($rule->{sport
}) {
1220 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1222 push @cmd, "--sport $rule->{sport}";
1225 } elsif ($rule->{dport
} || $rule->{sport
}) {
1226 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport
};
1227 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport
};
1230 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1232 if (my $action = $rule->{action
}) {
1233 $action = $actions->{$action} if defined($actions->{$action});
1234 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1235 push @cmd, $goto ?
"-g $action" : "-j $action";
1238 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1241 sub ruleset_generate_rule
{
1242 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1246 if ($rule->{macro}) {
1247 $rules = &$apply_macro($rule->{macro}, $rule);
1252 foreach my $tmp (@$rules) {
1253 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1254 ruleset_addrule
($ruleset, $chain, $cmdstr);
1259 sub ruleset_generate_rule_insert
{
1260 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1262 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1264 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1265 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1269 sub ruleset_create_chain
{
1270 my ($ruleset, $chain) = @_;
1272 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1273 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1275 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1277 $ruleset->{$chain} = [];
1280 sub ruleset_chain_exist
{
1281 my ($ruleset, $chain) = @_;
1283 return $ruleset->{$chain} ?
1 : undef;
1286 sub ruleset_addrule
{
1287 my ($ruleset, $chain, $rule) = @_;
1289 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1291 push @{$ruleset->{$chain}}, "-A $chain $rule";
1294 sub ruleset_insertrule
{
1295 my ($ruleset, $chain, $rule) = @_;
1297 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1299 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1302 sub get_log_rule_base
{
1303 my ($chain, $vmid, $msg, $loglevel) = @_;
1305 die "internal error - no log level" if !defined($loglevel);
1307 $vmid = 0 if !defined($vmid);
1309 # Note: we use special format for prefix to pass further
1310 # info to log daemon (VMID, LOGVELEL and CHAIN)
1312 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1315 sub ruleset_addlog {
1316 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1318 return if !defined($loglevel);
1320 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1322 $logrule = "$rule $logrule" if defined($rule);
1324 ruleset_addrule($ruleset, $chain, $logrule)
1327 sub generate_bridge_chains {
1328 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
1330 my $options = $hostfw_conf->{options} || {};
1332 die "error
: detected direct route to bridge
'$bridge'\n"
1333 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
1335 if (!ruleset_chain_exist($ruleset, "$bridge-FW
")) {
1336 ruleset_create_chain($ruleset, "$bridge-FW
");
1337 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-FW
");
1338 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-FW
");
1341 if (!ruleset_chain_exist($ruleset, "$bridge-OUT
")) {
1342 ruleset_create_chain($ruleset, "$bridge-OUT
");
1343 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-in
-j
$bridge-OUT
");
1344 ruleset_insertrule($ruleset, "PVEFW-INPUT
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-OUT
");
1347 if (!ruleset_chain_exist($ruleset, "$bridge-IN
")) {
1348 ruleset_create_chain($ruleset, "$bridge-IN
");
1349 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j
$bridge-IN
");
1350 ruleset_addrule($ruleset, "$bridge-FW
", "-m mark
--mark
1 -j ACCEPT
");
1351 # accept traffic to unmanaged bridge ports
1352 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j ACCEPT
");
1356 sub ruleset_add_chain_policy {
1357 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1359 if ($policy eq 'ACCEPT') {
1361 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1362 { ACCEPT => $accept_action});
1364 } elsif ($policy eq 'DROP') {
1366 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1368 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1370 ruleset_addrule($ruleset, $chain, "-j DROP
");
1371 } elsif ($policy eq 'REJECT') {
1372 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1374 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1376 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1379 die "internal error
: unknown policy
'$policy'";
1383 sub ruleset_create_vm_chain {
1384 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1386 ruleset_create_chain($ruleset, $chain);
1387 my $accept = generate_nfqueue($options);
1389 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1390 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1393 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1394 if ($direction eq 'OUT') {
1395 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1396 proto => 'udp', sport => 68, dport => 67 });
1398 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1399 proto => 'udp', sport => 67, dport => 68 });
1403 if ($options->{tcpflags}) {
1404 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1407 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1408 if ($direction eq 'OUT') {
1409 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-g PVEFW-SET-ACCEPT-MARK
");
1411 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1414 if ($direction eq 'OUT') {
1415 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1416 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1418 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1422 sub ruleset_generate_vm_rules {
1423 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1425 my $lc_direction = lc($direction);
1427 foreach my $rule (@$rules) {
1428 next if $rule->{iface} && $rule->{iface} ne $netid;
1429 next if !$rule->{enable};
1430 if ($rule->{type} eq 'group') {
1431 my $group_chain = "GROUP-
$rule->{action
}-$direction";
1432 if(!ruleset_chain_exist($ruleset, $group_chain)){
1433 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
1435 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1436 if ($direction eq 'OUT'){
1437 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j RETURN
");
1439 my $accept = generate_nfqueue($options);
1440 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$accept");
1444 next if $rule->{type} ne $lc_direction;
1445 if ($direction eq 'OUT') {
1446 ruleset_generate_rule($ruleset, $chain, $rule,
1447 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1449 my $accept = generate_nfqueue($options);
1450 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1456 sub generate_nfqueue {
1460 if($options->{ips}){
1461 $action = "NFQUEUE
";
1462 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1463 if(defined($3) && defined($1)) {
1464 $action .= " --queue-balance
$1:$3";
1465 }elsif (defined($1)) {
1466 $action .= " --queue-num
$1";
1469 $action .= " --queue-bypass
";
1477 sub ruleset_generate_vm_ipsrules {
1478 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1480 if ($options->{ips} && $direction eq 'IN') {
1481 my $nfqueue = generate_nfqueue($options);
1483 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1484 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1487 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1488 ruleset_create_chain($ruleset, "$bridge-IPS
");
1489 ruleset_insertrule($ruleset, "PVEFW-IPS
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-IPS
");
1492 ruleset_addrule($ruleset, "$bridge-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1496 sub generate_venet_rules_direction {
1497 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1499 parse_address_list($ip); # make sure we have a valid $ip list
1501 my $lc_direction = lc($direction);
1503 my $rules = $vmfw_conf->{rules};
1505 my $options = $vmfw_conf->{options};
1506 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1508 my $chain = "venet0-
$vmid-$direction";
1510 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1512 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1517 if ($direction eq 'OUT') {
1518 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1520 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1523 my $accept = generate_nfqueue($options);
1524 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1525 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1527 # plug into FORWARD, INPUT and OUTPUT chain
1528 if ($direction eq 'OUT') {
1529 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD
", {
1532 iface_in => 'venet0'});
1534 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT
", {
1537 iface_in => 'venet0'});
1539 ruleset_generate_rule($ruleset, "PVEFW-FORWARD
", {
1542 iface_out => 'venet0'});
1544 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT
", {
1547 iface_out => 'venet0'});
1551 sub generate_tap_rules_direction {
1552 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1554 my $lc_direction = lc($direction);
1556 my $rules = $vmfw_conf->{rules};
1558 my $options = $vmfw_conf->{options};
1559 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1561 my $tapchain = "$iface-$direction";
1563 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1565 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1567 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1572 if ($direction eq 'OUT') {
1573 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1575 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1578 my $accept = generate_nfqueue($options);
1579 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1580 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1582 # plug the tap chain to bridge chain
1583 if ($direction eq 'IN') {
1584 ruleset_insertrule($ruleset, "$bridge-IN
",
1585 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1587 ruleset_insertrule($ruleset, "$bridge-OUT
",
1588 "-m physdev
--physdev-in
$iface -j
$tapchain");
1592 sub enable_host_firewall {
1593 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1595 # fixme: allow security groups
1597 my $options = $hostfw_conf->{options};
1598 my $rules = $hostfw_conf->{rules};
1600 # host inbound firewall
1601 my $chain = "PVEFW-HOST-IN
";
1602 ruleset_create_chain($ruleset, $chain);
1604 my $loglevel = get_option_log_level($options, "log_level_in
");
1606 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1607 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1610 if ($options->{tcpflags}) {
1611 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1614 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1615 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1616 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1617 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1618 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1619 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1621 # we use RETURN because we need to check also tap rules
1622 my $accept_action = 'RETURN';
1624 foreach my $rule (@$rules) {
1625 next if $rule->{type} ne 'in';
1626 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1629 # implement input policy
1630 my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1631 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1633 # host outbound firewall
1634 $chain = "PVEFW-HOST-OUT
";
1635 ruleset_create_chain($ruleset, $chain);
1637 $loglevel = get_option_log_level($options, "log_level_out
");
1639 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1640 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1641 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1642 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1643 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1644 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1646 # we use RETURN because we may want to check other thigs later
1647 $accept_action = 'RETURN';
1649 foreach my $rule (@$rules) {
1650 next if $rule->{type} ne 'out';
1651 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1654 # implement output policy
1655 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1656 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1658 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1659 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1662 sub generate_group_rules {
1663 my ($ruleset, $cluster_conf, $group) = @_;
1664 die "no such security group
'$group'\n" if !$cluster_conf->{groups}->{$group};
1666 my $rules = $cluster_conf->{groups}->{$group};
1668 my $chain = "GROUP-
${group
}-IN
";
1670 ruleset_create_chain($ruleset, $chain);
1671 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1673 foreach my $rule (@$rules) {
1674 next if $rule->{type} ne 'in';
1675 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1678 $chain = "GROUP-
${group
}-OUT
";
1680 ruleset_create_chain($ruleset, $chain);
1681 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1683 foreach my $rule (@$rules) {
1684 next if $rule->{type} ne 'out';
1685 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1686 # check also other tap rules later
1687 ruleset_generate_rule($ruleset, $chain, $rule,
1688 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1693 my $valid_netdev_names = {};
1694 for (my $i = 0; $i < $MAX_NETS; $i++) {
1695 $valid_netdev_names->{"net
$i"} = 1;
1699 my ($line, $need_iface, $allow_groups) = @_;
1701 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
1703 # we can add single line comments to the end of the rule
1704 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1706 # we can disable a rule when prefixed with '|'
1709 $enable = 0 if $line =~ s/^\|//;
1711 my @data = split(/\s+/, $line);
1712 my $expected_elements = $need_iface ? 8 : 7;
1714 die "wrong number of rule elements
\n" if scalar(@data) > $expected_elements;
1717 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1719 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1722 die "incomplete rule
\n" if ! ($type && $action);
1728 if ($type eq 'in' || $type eq 'out') {
1729 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1731 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1733 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1734 die "unknown
macro '$1'\n" if !$preferred_name;
1735 $macro = $preferred_name;
1737 die "unknown action
'$action'\n";
1739 } elsif ($type eq 'group') {
1740 die "wrong number of rule elements
\n" if scalar(@data) != 3;
1741 die "groups disabled
\n" if !$allow_groups;
1743 die "invalid characters
in group name
\n" if $action !~ m/^[A-Za-z0-9_\-]+$/;
1745 die "unknown rule type
'$type'\n";
1749 $iface = undef if $iface && $iface eq '-';
1752 $proto = undef if $proto && $proto eq '-';
1753 pve_fw_verify_protocol_spec($proto) if $proto;
1755 $source = undef if $source && $source eq '-';
1756 $dest = undef if $dest && $dest eq '-';
1758 $dport = undef if $dport && $dport eq '-';
1759 $sport = undef if $sport && $sport eq '-';
1761 parse_port_name_number_or_range($dport) if defined($dport);
1762 parse_port_name_number_or_range($sport) if defined($sport);
1764 parse_address_list($source) if $source;
1765 parse_address_list($dest) if $dest;
1770 comment => $comment,
1782 sub parse_vmfw_option {
1787 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
1789 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
1792 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1794 $value = $2 ? lc($3) : '';
1795 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1798 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1803 die "can
't parse option '$line'\n"
1806 return ($opt, $value);
1809 sub parse_hostfw_option {
1814 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1816 if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1819 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1821 $value = $2 ? lc($3) : '';
1822 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1825 } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
1830 die "can't parse option
'$line'\n"
1833 return ($opt, $value);
1836 sub parse_clusterfw_option {
1841 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1846 die "can
't parse option '$line'\n"
1849 return ($opt, $value);
1852 sub parse_vm_fw_rules {
1853 my ($filename, $fh) = @_;
1855 my $res = { rules => [], options => {}};
1859 my $digest = Digest::SHA->new('sha1
');
1861 while (defined(my $line = <$fh>)) {
1862 $digest->add($line);
1864 next if $line =~ m/^#/;
1865 next if $line =~ m/^\s*$/;
1867 my $linenr = $fh->input_line_number();
1868 my $prefix = "$filename (line $linenr)";
1870 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1872 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1876 warn "$prefix: skip line - no section";
1880 next if !$res->{$section}; # skip undefined section
1882 if ($section eq 'options
') {
1884 my ($opt, $value) = parse_vmfw_option($line);
1885 $res->{options}->{$opt} = $value;
1887 warn "$prefix: $@" if $@;
1892 eval { $rule = parse_fw_rule($line, 1, 1); };
1894 warn "$prefix: $err";
1898 push @{$res->{$section}}, $rule;
1901 $res->{digest} = $digest->b64digest;
1906 sub parse_host_fw_rules {
1907 my ($filename, $fh) = @_;
1909 my $res = { rules => [], options => {}};
1913 my $digest = Digest::SHA->new('sha1
');
1915 while (defined(my $line = <$fh>)) {
1916 $digest->add($line);
1918 next if $line =~ m/^#/;
1919 next if $line =~ m/^\s*$/;
1921 my $linenr = $fh->input_line_number();
1922 my $prefix = "$filename (line $linenr)";
1924 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1926 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1930 warn "$prefix: skip line - no section";
1934 next if !$res->{$section}; # skip undefined section
1936 if ($section eq 'options
') {
1938 my ($opt, $value) = parse_hostfw_option($line);
1939 $res->{options}->{$opt} = $value;
1941 warn "$prefix: $@" if $@;
1946 eval { $rule = parse_fw_rule($line, 1, 1); };
1948 warn "$prefix: $err";
1952 push @{$res->{$section}}, $rule;
1955 $res->{digest} = $digest->b64digest;
1960 sub parse_cluster_fw_rules {
1961 my ($filename, $fh) = @_;
1966 my $res = { rules => [], options => {}, groups => {}, ipset => {} };
1968 my $digest = Digest::SHA->new('sha1
');
1970 while (defined(my $line = <$fh>)) {
1971 $digest->add($line);
1973 next if $line =~ m/^#/;
1974 next if $line =~ m/^\s*$/;
1976 my $linenr = $fh->input_line_number();
1977 my $prefix = "$filename (line $linenr)";
1979 if ($line =~ m/^\[options\]$/i) {
1980 $section = 'options
';
1984 if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
1985 $section = 'groups
';
1987 $res->{$section}->{$group} = [];
1991 if ($line =~ m/^\[rules\]$/i) {
1996 if ($line =~ m/^\[ipset\s+(\S+)\]\s*$/i) {
1999 $res->{$section}->{$group} = [];
2004 warn "$prefix: skip line - no section\n";
2008 if ($section eq 'options
') {
2010 my ($opt, $value) = parse_clusterfw_option($line);
2011 $res->{options}->{$opt} = $value;
2013 warn "$prefix: $@" if $@;
2014 } elsif ($section eq 'rules
') {
2016 eval { $rule = parse_fw_rule($line, 1, 1); };
2018 warn "$prefix: $err";
2021 push @{$res->{$section}}, $rule;
2022 } elsif ($section eq 'groups
') {
2024 eval { $rule = parse_fw_rule($line, 0, 0); };
2026 warn "$prefix: $err";
2029 push @{$res->{$section}->{$group}}, $rule;
2030 } elsif ($section eq 'ipset
') {
2031 # we can add single line comments to the end of the rule
2032 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2034 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2040 eval { pve_verify_ipv4_or_cidr($cidr); };
2042 warn "$prefix: $cidr - $err";
2046 my $entry = { cidr => $cidr };
2047 $entry->{nomatch} = 1 if $nomatch;
2048 $entry->{comment} = $comment if $comment;
2050 push @{$res->{$section}->{$group}}, $entry;
2054 $res->{digest} = $digest->b64digest;
2059 my ($code, @param) = @_;
2063 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2070 sub read_local_vm_config {
2075 my $vmdata = { openvz => $openvz, qemu => $qemu };
2077 my $vmlist = PVE::Cluster::get_vmlist();
2078 return $vmdata if !$vmlist || !$vmlist->{ids};
2079 my $ids = $vmlist->{ids};
2081 foreach my $vmid (keys %$ids) {
2082 next if !$vmid; # skip VE0
2083 my $d = $ids->{$vmid};
2084 next if !$d->{node} || $d->{node} ne $nodename;
2085 next if !$d->{type};
2086 if ($d->{type} eq 'openvz
') {
2087 if ($have_pve_manager) {
2088 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2089 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2090 $openvz->{$vmid} = $conf;
2093 } elsif ($d->{type} eq 'qemu
') {
2094 if ($have_qemu_server) {
2095 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2096 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2097 $qemu->{$vmid} = $conf;
2106 sub load_vmfw_conf {
2111 my $filename = "/etc/pve/firewall/$vmid.fw";
2112 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2113 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2119 my $format_rules = sub {
2120 my ($rules, $need_iface) = @_;
2124 foreach my $rule (@$rules) {
2125 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
') {
2126 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2127 $raw .= uc($rule->{type});
2128 if ($rule->{macro}) {
2129 $raw .= " $rule->{macro}($rule->{action})";
2131 $raw .= " " . $rule->{action};
2133 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
2134 $raw .= " " . ($rule->{source} || '-');
2135 $raw .= " " . ($rule->{dest} || '-');
2136 $raw .= " " . ($rule->{proto} || '-');
2137 $raw .= " " . ($rule->{dport} || '-');
2138 $raw .= " " . ($rule->{sport} || '-');
2139 $raw .= " # " . encode('utf8
', $rule->{comment})
2140 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2143 die "implement me '$rule->{type
}'";
2150 my $format_options = sub {
2155 $raw .= "[OPTIONS]\n\n";
2156 foreach my $opt (keys %$options) {
2157 $raw .= "$opt: $options->{$opt}\n";
2164 my $format_ipset = sub {
2170 foreach my $entry (@$options) {
2171 $nethash->{$entry->{cidr}} = $entry;
2174 foreach my $cidr (sort keys %$nethash) {
2175 my $entry = $nethash->{$cidr};
2176 my $line = $entry->{nomatch} ? '!' : '';
2177 $line .= $entry->{cidr};
2178 $line .= " # " . encode('utf8
', $entry->{comment})
2179 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2186 sub save_vmfw_conf {
2187 my ($vmid, $vmfw_conf) = @_;
2191 my $options = $vmfw_conf->{options};
2192 $raw .= &$format_options($options) if scalar(keys %$options);
2194 my $rules = $vmfw_conf->{rules};
2195 if (scalar(@$rules)) {
2196 $raw .= "[RULES]\n\n";
2197 $raw .= &$format_rules($rules, 1);
2201 my $filename = "/etc/pve/firewall/$vmid.fw";
2202 PVE::Tools::file_set_contents($filename, $raw);
2205 sub read_vm_firewall_configs {
2207 my $vmfw_configs = {};
2209 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2210 my $vmfw_conf = load_vmfw_conf($vmid);
2211 next if !$vmfw_conf->{options}; # skip if file does not exists
2212 $vmfw_configs->{$vmid} = $vmfw_conf;
2215 return $vmfw_configs;
2218 sub get_option_log_level {
2219 my ($options, $k) = @_;
2221 my $v = $options->{$k};
2222 $v = $default_log_level if !defined($v);
2224 return undef if $v eq '' || $v eq 'nolog
';
2226 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2228 return $v if ($v >= 0) && ($v <= 7);
2230 warn "unknown log level ($k = '$v')\n";
2235 sub generate_std_chains {
2236 my ($ruleset, $options) = @_;
2238 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2240 # same as shorewall smurflog.
2241 my $chain = 'PVEFW-smurflog
';
2243 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2244 push @{$pve_std_chains->{$chain}}, "-j DROP";
2246 # same as shorewall logflags action.
2247 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2248 $chain = 'PVEFW-logflags
';
2249 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2250 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2251 push @{$pve_std_chains->{$chain}}, "-j DROP";
2253 foreach my $chain (keys %$pve_std_chains) {
2254 ruleset_create_chain($ruleset, $chain);
2255 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2257 ruleset_generate_rule($ruleset, $chain, $rule);
2259 ruleset_addrule($ruleset, $chain, $rule);
2265 sub generate_ipset_chains {
2266 my ($ipset_ruleset, $fw_conf) = @_;
2268 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2269 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
2273 sub generate_ipset {
2274 my ($ipset_ruleset, $name, $options) = @_;
2276 my $hashsize = scalar(@$options);
2277 if ($hashsize <= 64) {
2280 $hashsize = round_powerof2($hashsize);
2283 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2287 foreach my $entry (@$options) {
2288 $nethash->{$entry->{cidr}} = $entry;
2291 foreach my $cidr (sort keys %$nethash) {
2292 my $entry = $nethash->{$cidr};
2294 my $cmd = "add $name $cidr";
2295 if ($entry->{nomatch}) {
2296 if ($feature_ipset_nomatch) {
2297 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2299 warn "ignore !$cidr - nomatch not supported by kernel\n";
2302 push @{$ipset_ruleset->{$name}}, $cmd;
2307 sub round_powerof2 {
2311 $int |= $int >> $_ foreach (1,2,4,8,16);
2315 sub save_pvefw_status {
2318 die "unknown status '$status' - internal error"
2319 if $status !~ m/^(stopped|active)$/;
2321 mkdir dirname($pve_fw_status_filename);
2322 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2325 sub read_pvefw_status {
2327 my $status = 'unknown
';
2329 return 'stopped
' if ! -f $pve_fw_status_filename;
2332 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2339 # fixme: move to pve-common PVE::ProcFSTools
2340 sub read_proc_net_route {
2341 my $filename = "/proc/net/route";
2345 my $fh = IO::File->new ($filename, "r");
2346 return $res if !$fh;
2348 my $int_to_quad = sub {
2349 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2352 while (defined(my $line = <$fh>)) {
2353 next if $line =~/^Iface\s+Destination/; # skip head
2354 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2355 push @{$res->{$iface}}, {
2356 dest => &$int_to_quad(hex($dest)),
2357 gateway => &$int_to_quad(hex($gateway)),
2358 mask => &$int_to_quad(hex($mask)),
2367 sub load_clusterfw_conf {
2369 my $cluster_conf = {};
2370 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
2371 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
2374 return $cluster_conf;
2377 sub save_clusterfw_conf {
2378 my ($cluster_conf) = @_;
2382 my $options = $cluster_conf->{options};
2383 $raw .= &$format_options($options) if scalar(keys %$options);
2385 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
2386 $raw .= "[IPSET $ipset]\n\n";
2387 my $options = $cluster_conf->{ipset}->{$ipset};
2388 $raw .= &$format_ipset($options);
2392 my $rules = $cluster_conf->{rules};
2393 if (scalar(@$rules)) {
2394 $raw .= "[RULES]\n\n";
2395 $raw .= &$format_rules($rules, 1);
2399 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2400 my $rules = $cluster_conf->{groups}->{$group};
2401 $raw .= "[group $group]\n\n";
2402 $raw .= &$format_rules($rules, 0);
2406 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2409 sub load_hostfw_conf {
2411 my $hostfw_conf = {};
2412 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2413 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
2415 return $hostfw_conf;
2418 sub save_hostfw_conf {
2419 my ($hostfw_conf) = @_;
2423 my $options = $hostfw_conf->{options};
2424 $raw .= &$format_options($options) if scalar(keys %$options);
2426 my $rules = $hostfw_conf->{rules};
2427 if (scalar(@$rules)) {
2428 $raw .= "[RULES]\n\n";
2429 $raw .= &$format_rules($rules, 1);
2433 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2437 my $vmdata = read_local_vm_config();
2438 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2440 my $routing_table = read_proc_net_route();
2442 my $cluster_conf = load_clusterfw_conf();
2444 my $ipset_ruleset = {};
2445 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2449 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2450 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2452 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2454 my $hostfw_conf = load_hostfw_conf();
2455 my $hostfw_options = $hostfw_conf->{options} || {};
2457 generate_std_chains($ruleset, $hostfw_options);
2459 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2461 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2463 # generate firewall rules for QEMU VMs
2464 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2465 my $conf = $vmdata->{qemu}->{$vmid};
2466 my $vmfw_conf = $vmfw_configs->{$vmid};
2467 next if !$vmfw_conf;
2468 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2470 foreach my $netid (keys %$conf) {
2471 next if $netid !~ m/^net(\d+)$/;
2472 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2474 my $iface = "tap${vmid}i$1";
2476 my $bridge = $net->{bridge};
2477 next if !$bridge; # fixme: ?
2479 $bridge .= "v$net->{tag}" if $net->{tag};
2481 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2483 my $macaddr = $net->{macaddr};
2484 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2485 $vmfw_conf, $vmid, $bridge, 'IN
');
2486 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2487 $vmfw_conf, $vmid, $bridge, 'OUT
');
2491 # generate firewall rules for OpenVZ containers
2492 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2493 my $conf = $vmdata->{openvz}->{$vmid};
2495 my $vmfw_conf = $vmfw_configs->{$vmid};
2496 next if !$vmfw_conf;
2497 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2499 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2500 my $ip = $conf->{ip_address}->{value};
2501 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2502 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2505 if ($conf->{netif} && $conf->{netif}->{value}) {
2506 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2507 foreach my $netid (keys %$netif) {
2508 my $d = $netif->{$netid};
2509 my $bridge = $d->{bridge};
2511 warn "no bridge device for CT $vmid iface '$netid'\n";
2515 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2517 my $macaddr = $d->{mac};
2518 my $iface = $d->{host_ifname};
2519 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2520 $vmfw_conf, $vmid, $bridge, 'IN
');
2521 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2522 $vmfw_conf, $vmid, $bridge, 'OUT
');
2527 if($hostfw_options->{optimize}){
2529 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
2530 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
2531 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2534 # fixme: what log level should we use here?
2535 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2537 # fixme: should we really block inter-bridge traffic?
2539 # always allow traffic from containers?
2540 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2542 # disable interbridge routing
2543 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
2544 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
2545 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2546 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2547 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
2548 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2550 return wantarray ? ($ruleset, $hostfw_conf, $ipset_ruleset) : $ruleset;
2553 sub get_ruleset_status {
2554 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2556 my $statushash = {};
2558 foreach my $chain (sort keys %$ruleset) {
2559 my $sig = &$digest_fn($ruleset->{$chain});
2561 $statushash->{$chain}->{sig} = $sig;
2563 my $oldsig = $active_chains->{$chain};
2564 if (!defined($oldsig)) {
2565 $statushash->{$chain}->{action} = 'create
';
2567 if ($oldsig eq $sig) {
2568 $statushash->{$chain}->{action} = 'exists';
2570 $statushash->{$chain}->{action} = 'update
';
2573 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2574 foreach my $cmd (@{$ruleset->{$chain}}) {
2575 print "\t$cmd\n" if $verbose;
2579 foreach my $chain (sort keys %$active_chains) {
2580 if (!defined($ruleset->{$chain})) {
2581 my $sig = $active_chains->{$chain};
2582 $statushash->{$chain}->{action} = 'delete';
2583 $statushash->{$chain}->{sig} = $sig;
2584 print "delete $chain ($sig)\n" if $verbose;
2591 sub print_sig_rule {
2592 my ($chain, $sig) = @_;
2594 # We just use this to store a SHA1 checksum used to detect changes
2595 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2598 sub get_ruleset_cmdlist {
2599 my ($ruleset, $verbose) = @_;
2601 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2603 my ($active_chains, $hooks) = iptables_get_chains();
2604 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2606 # create missing chains first
2607 foreach my $chain (sort keys %$ruleset) {
2608 my $stat = $statushash->{$chain};
2609 die "internal error" if !$stat;
2610 next if $stat->{action} ne 'create
';
2612 $cmdlist .= ":$chain - [0:0]\n";
2615 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2616 if (!$hooks->{$h}) {
2617 $cmdlist .= "-A $h -j PVEFW-$h\n";
2621 foreach my $chain (sort keys %$ruleset) {
2622 my $stat = $statushash->{$chain};
2623 die "internal error" if !$stat;
2625 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2626 $cmdlist .= "-F $chain\n";
2627 foreach my $cmd (@{$ruleset->{$chain}}) {
2628 $cmdlist .= "$cmd\n";
2630 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2631 } elsif ($stat->{action
} eq 'delete') {
2632 die "internal error"; # this should not happen
2633 } elsif ($stat->{action
} eq 'exists') {
2636 die "internal error - unknown status '$stat->{action}'";
2640 foreach my $chain (keys %$statushash) {
2641 next if $statushash->{$chain}->{action
} ne 'delete';
2642 $cmdlist .= "-F $chain\n";
2644 foreach my $chain (keys %$statushash) {
2645 next if $statushash->{$chain}->{action
} ne 'delete';
2646 next if $chain eq 'PVEFW-INPUT';
2647 next if $chain eq 'PVEFW-OUTPUT';
2648 next if $chain eq 'PVEFW-FORWARD';
2649 $cmdlist .= "-X $chain\n";
2652 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2654 $cmdlist .= "COMMIT\n";
2656 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2659 sub get_ipset_cmdlist
{
2660 my ($ruleset, $verbose) = @_;
2664 my $delete_cmdlist = "";
2666 my $active_chains = ipset_get_chains
();
2667 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2669 # remove stale _swap chains
2670 foreach my $chain (keys %$active_chains) {
2671 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2672 $cmdlist .= "destroy $chain\n";
2676 foreach my $chain (sort keys %$ruleset) {
2677 my $stat = $statushash->{$chain};
2678 die "internal error" if !$stat;
2680 if ($stat->{action
} eq 'create') {
2681 foreach my $cmd (@{$ruleset->{$chain}}) {
2682 $cmdlist .= "$cmd\n";
2686 if ($stat->{action
} eq 'update') {
2687 my $chain_swap = $chain."_swap";
2689 foreach my $cmd (@{$ruleset->{$chain}}) {
2690 $cmd =~ s/$chain/$chain_swap/;
2691 $cmdlist .= "$cmd\n";
2693 $cmdlist .= "swap $chain_swap $chain\n";
2694 $cmdlist .= "flush $chain_swap\n";
2695 $cmdlist .= "destroy $chain_swap\n";
2700 foreach my $chain (keys %$statushash) {
2701 next if $statushash->{$chain}->{action
} ne 'delete';
2703 $delete_cmdlist .= "flush $chain\n";
2704 $delete_cmdlist .= "destroy $chain\n";
2707 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
2709 return ($cmdlist, $delete_cmdlist, $changes);
2713 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2715 enable_bridge_firewall
();
2717 update_nf_conntrack_max
($hostfw_conf);
2719 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2720 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
2722 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
2725 if ($ipset_changes) {
2726 print "ipset changes:\n";
2727 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2728 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2732 print "iptables changes:\n";
2737 ipset_restore_cmdlist
($ipset_create_cmdlist);
2739 iptables_restore_cmdlist
($cmdlist);
2741 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2743 # test: re-read status and check if everything is up to date
2744 my $active_chains = iptables_get_chains
();
2745 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
2748 foreach my $chain (sort keys %$ruleset) {
2749 my $stat = $statushash->{$chain};
2750 if ($stat->{action
} ne 'exists') {
2751 warn "unable to update chain '$chain'\n";
2756 die "unable to apply firewall changes\n" if $errors;
2759 sub update_nf_conntrack_max
{
2760 my ($hostfw_conf) = @_;
2762 my $max = 65536; # reasonable default
2764 my $options = $hostfw_conf->{options
} || {};
2766 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
2767 $max = $options->{nf_conntrack_max
};
2768 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2771 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2772 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2774 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
2776 if ($current != $max) {
2777 my $hashsize = int($max/4);
2778 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
2779 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
2783 sub remove_pvefw_chains
{
2785 my ($chash, $hooks) = iptables_get_chains
();
2786 my $cmdlist = "*filter\n";
2788 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2790 $cmdlist .= "-D $h -j PVEFW-$h\n";
2794 foreach my $chain (keys %$chash) {
2795 $cmdlist .= "-F $chain\n";
2798 foreach my $chain (keys %$chash) {
2799 $cmdlist .= "-X $chain\n";
2801 $cmdlist .= "COMMIT\n";
2803 iptables_restore_cmdlist
($cmdlist);
2807 my ($start, $verbose) = @_;
2810 my $status = read_pvefw_status
();
2812 my ($ruleset, $hostfw_conf, $ipset_ruleset) = compile
();
2814 if ($start || $status eq 'active') {
2816 save_pvefw_status
('active') if ($status ne 'active');
2818 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
2820 print "Firewall not active (status = $status)\n" if $verbose;