]> git.proxmox.com Git - pve-firewall.git/blob - src/PVE/Firewall.pm
parser: verify group and ipset names
[pve-firewall.git] / src / PVE / Firewall.pm
1 package PVE::Firewall;
2
3 use warnings;
4 use strict;
5 use POSIX;
6 use Data::Dumper;
7 use Digest::SHA;
8 use PVE::INotify;
9 use PVE::Exception qw(raise raise_param_exc);
10 use PVE::JSONSchema qw(register_standard_option get_standard_option);
11 use PVE::Cluster;
12 use PVE::ProcFSTools;
13 use PVE::Tools qw($IPV4RE);
14 use File::Basename;
15 use File::Path;
16 use IO::File;
17 use Net::IP;
18 use PVE::Tools qw(run_command lock_file dir_glob_foreach);
19 use Encode;
20
21 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
22 my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw";
23
24 # dynamically include PVE::QemuServer and PVE::OpenVZ
25 # to avoid dependency problems
26 my $have_qemu_server;
27 eval {
28 require PVE::QemuServer;
29 $have_qemu_server = 1;
30 };
31
32 my $have_pve_manager;
33 eval {
34 require PVE::OpenVZ;
35 $have_pve_manager = 1;
36 };
37
38 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
39 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
40 my $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
41
42 my $max_alias_name_length = 64;
43 my $max_ipset_name_length = 64;
44 my $max_group_name_length = 20;
45
46 PVE::JSONSchema::register_format('IPv4orCIDR', \&pve_verify_ipv4_or_cidr);
47 sub pve_verify_ipv4_or_cidr {
48 my ($cidr, $noerr) = @_;
49
50 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
51 return $cidr if Net::IP->new($cidr);
52 return undef if $noerr;
53 die Net::IP::Error() . "\n";
54 }
55 return undef if $noerr;
56 die "value does not look like a valid IP address or CIDR network\n";
57 }
58
59 PVE::JSONSchema::register_standard_option('ipset-name', {
60 description => "IP set name.",
61 type => 'string',
62 pattern => $ipset_name_pattern,
63 minLength => 2,
64 maxLength => $max_ipset_name_length,
65 });
66
67 PVE::JSONSchema::register_standard_option('pve-fw-alias', {
68 description => "Alias name.",
69 type => 'string',
70 pattern => $ip_alias_pattern,
71 minLength => 2,
72 maxLength => $max_alias_name_length,
73 });
74
75 PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => {
76 description => "Log level.",
77 type => 'string',
78 enum => ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
79 optional => 1,
80 });
81
82 PVE::JSONSchema::register_standard_option('pve-security-group-name', {
83 description => "Security Group name.",
84 type => 'string',
85 pattern => $security_group_name_pattern,
86 minLength => 2,
87 maxLength => $max_group_name_length,
88 });
89
90 my $feature_ipset_nomatch = 0;
91 eval {
92 my (undef, undef, $release) = POSIX::uname();
93 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
94 my ($major, $minor) = ($1, $2);
95 $feature_ipset_nomatch = 1 if ($major > 3) ||
96 ($major == 3 && $minor >= 7);
97 }
98
99 };
100
101 use Data::Dumper;
102
103 my $nodename = PVE::INotify::nodename();
104
105 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
106
107 my $default_log_level = 'nolog'; # avoid logs by default
108
109 my $log_level_hash = {
110 debug => 7,
111 info => 6,
112 notice => 5,
113 warning => 4,
114 err => 3,
115 crit => 2,
116 alert => 1,
117 emerg => 0,
118 };
119
120 # imported/converted from: /usr/share/shorewall/macro.*
121 my $pve_fw_macros = {
122 'Amanda' => [
123 "Amanda Backup",
124 { action => 'PARAM', proto => 'udp', dport => '10080' },
125 { action => 'PARAM', proto => 'tcp', dport => '10080' },
126 ],
127 'Auth' => [
128 "Auth (identd) traffic",
129 { action => 'PARAM', proto => 'tcp', dport => '113' },
130 ],
131 'BGP' => [
132 "Border Gateway Protocol traffic",
133 { action => 'PARAM', proto => 'tcp', dport => '179' },
134 ],
135 'BitTorrent' => [
136 "BitTorrent traffic for BitTorrent 3.1 and earlier",
137 { action => 'PARAM', proto => 'tcp', dport => '6881:6889' },
138 { action => 'PARAM', proto => 'udp', dport => '6881' },
139 ],
140 'BitTorrent32' => [
141 "BitTorrent traffic for BitTorrent 3.2 and later",
142 { action => 'PARAM', proto => 'tcp', dport => '6881:6999' },
143 { action => 'PARAM', proto => 'udp', dport => '6881' },
144 ],
145 'CVS' => [
146 "Concurrent Versions System pserver traffic",
147 { action => 'PARAM', proto => 'tcp', dport => '2401' },
148 ],
149 'Citrix' => [
150 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
151 { action => 'PARAM', proto => 'tcp', dport => '1494' },
152 { action => 'PARAM', proto => 'udp', dport => '1604' },
153 { action => 'PARAM', proto => 'tcp', dport => '2598' },
154 ],
155 'DAAP' => [
156 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
157 { action => 'PARAM', proto => 'tcp', dport => '3689' },
158 { action => 'PARAM', proto => 'udp', dport => '3689' },
159 ],
160 'DCC' => [
161 "Distributed Checksum Clearinghouse spam filtering mechanism",
162 { action => 'PARAM', proto => 'tcp', dport => '6277' },
163 ],
164 'DHCPfwd' => [
165 "Forwarded DHCP traffic",
166 { action => 'PARAM', proto => 'udp', dport => '67:68', sport => '67:68' },
167 ],
168 'DNS' => [
169 "Domain Name System traffic (upd and tcp)",
170 { action => 'PARAM', proto => 'udp', dport => '53' },
171 { action => 'PARAM', proto => 'tcp', dport => '53' },
172 ],
173 'Distcc' => [
174 "Distributed Compiler service",
175 { action => 'PARAM', proto => 'tcp', dport => '3632' },
176 ],
177 'FTP' => [
178 "File Transfer Protocol",
179 { action => 'PARAM', proto => 'tcp', dport => '21' },
180 ],
181 'Finger' => [
182 "Finger protocol (RFC 742)",
183 { action => 'PARAM', proto => 'tcp', dport => '79' },
184 ],
185 'GNUnet' => [
186 "GNUnet secure peer-to-peer networking traffic",
187 { action => 'PARAM', proto => 'tcp', dport => '2086' },
188 { action => 'PARAM', proto => 'udp', dport => '2086' },
189 { action => 'PARAM', proto => 'tcp', dport => '1080' },
190 { action => 'PARAM', proto => 'udp', dport => '1080' },
191 ],
192 'GRE' => [
193 "Generic Routing Encapsulation tunneling protocol",
194 { action => 'PARAM', proto => '47' },
195 ],
196 'Git' => [
197 "Git distributed revision control traffic",
198 { action => 'PARAM', proto => 'tcp', dport => '9418' },
199 ],
200 'HKP' => [
201 "OpenPGP HTTP keyserver protocol traffic",
202 { action => 'PARAM', proto => 'tcp', dport => '11371' },
203 ],
204 'HTTP' => [
205 "Hypertext Transfer Protocol (WWW)",
206 { action => 'PARAM', proto => 'tcp', dport => '80' },
207 ],
208 'HTTPS' => [
209 "Hypertext Transfer Protocol (WWW) over SSL",
210 { action => 'PARAM', proto => 'tcp', dport => '443' },
211 ],
212 'ICPV2' => [
213 "Internet Cache Protocol V2 (Squid) traffic",
214 { action => 'PARAM', proto => 'udp', dport => '3130' },
215 ],
216 'ICQ' => [
217 "AOL Instant Messenger traffic",
218 { action => 'PARAM', proto => 'tcp', dport => '5190' },
219 ],
220 'IMAP' => [
221 "Internet Message Access Protocol",
222 { action => 'PARAM', proto => 'tcp', dport => '143' },
223 ],
224 'IMAPS' => [
225 "Internet Message Access Protocol over SSL",
226 { action => 'PARAM', proto => 'tcp', dport => '993' },
227 ],
228 'IPIP' => [
229 "IPIP capsulation traffic",
230 { action => 'PARAM', proto => '94' },
231 ],
232 'IPsec' => [
233 "IPsec traffic",
234 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
235 { action => 'PARAM', proto => '50' },
236 ],
237 'IPsecah' => [
238 "IPsec authentication (AH) traffic",
239 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
240 { action => 'PARAM', proto => '51' },
241 ],
242 'IPsecnat' => [
243 "IPsec traffic and Nat-Traversal",
244 { action => 'PARAM', proto => 'udp', dport => '500' },
245 { action => 'PARAM', proto => 'udp', dport => '4500' },
246 { action => 'PARAM', proto => '50' },
247 ],
248 'IRC' => [
249 "Internet Relay Chat traffic",
250 { action => 'PARAM', proto => 'tcp', dport => '6667' },
251 ],
252 'Jetdirect' => [
253 "HP Jetdirect printing",
254 { action => 'PARAM', proto => 'tcp', dport => '9100' },
255 ],
256 'L2TP' => [
257 "Layer 2 Tunneling Protocol traffic",
258 { action => 'PARAM', proto => 'udp', dport => '1701' },
259 ],
260 'LDAP' => [
261 "Lightweight Directory Access Protocol traffic",
262 { action => 'PARAM', proto => 'tcp', dport => '389' },
263 ],
264 'LDAPS' => [
265 "Secure Lightweight Directory Access Protocol traffic",
266 { action => 'PARAM', proto => 'tcp', dport => '636' },
267 ],
268 'MSNP' => [
269 "Microsoft Notification Protocol",
270 { action => 'PARAM', proto => 'tcp', dport => '1863' },
271 ],
272 'MSSQL' => [
273 "Microsoft SQL Server",
274 { action => 'PARAM', proto => 'tcp', dport => '1433' },
275 ],
276 'Mail' => [
277 "Mail traffic (SMTP, SMTPS, Submission)",
278 { action => 'PARAM', proto => 'tcp', dport => '25' },
279 { action => 'PARAM', proto => 'tcp', dport => '465' },
280 { action => 'PARAM', proto => 'tcp', dport => '587' },
281 ],
282 'Munin' => [
283 "Munin networked resource monitoring traffic",
284 { action => 'PARAM', proto => 'tcp', dport => '4949' },
285 ],
286 'MySQL' => [
287 "MySQL server",
288 { action => 'PARAM', proto => 'tcp', dport => '3306' },
289 ],
290 'NNTP' => [
291 "NNTP traffic (Usenet).",
292 { action => 'PARAM', proto => 'tcp', dport => '119' },
293 ],
294 'NNTPS' => [
295 "Encrypted NNTP traffic (Usenet)",
296 { action => 'PARAM', proto => 'tcp', dport => '563' },
297 ],
298 'NTP' => [
299 "Network Time Protocol (ntpd)",
300 { action => 'PARAM', proto => 'udp', dport => '123' },
301 ],
302 'OSPF' => [
303 "OSPF multicast traffic",
304 { action => 'PARAM', proto => '89' },
305 ],
306 'OpenVPN' => [
307 "OpenVPN traffic",
308 { action => 'PARAM', proto => 'udp', dport => '1194' },
309 ],
310 'PCA' => [
311 "Symantec PCAnywere (tm)",
312 { action => 'PARAM', proto => 'udp', dport => '5632' },
313 { action => 'PARAM', proto => 'tcp', dport => '5631' },
314 ],
315 'POP3' => [
316 "POP3 traffic",
317 { action => 'PARAM', proto => 'tcp', dport => '110' },
318 ],
319 'POP3S' => [
320 "Encrypted POP3 traffic",
321 { action => 'PARAM', proto => 'tcp', dport => '995' },
322 ],
323 'PPtP' => [
324 "Point-to-Point Tunneling Protocol",
325 { action => 'PARAM', proto => '47' },
326 { action => 'PARAM', proto => 'tcp', dport => '1723' },
327 ],
328 'Ping' => [
329 "ICMP echo request",
330 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
331 ],
332 'PostgreSQL' => [
333 "PostgreSQL server",
334 { action => 'PARAM', proto => 'tcp', dport => '5432' },
335 ],
336 'Printer' => [
337 "Line Printer protocol printing",
338 { action => 'PARAM', proto => 'tcp', dport => '515' },
339 ],
340 'RDP' => [
341 "Microsoft Remote Desktop Protocol traffic",
342 { action => 'PARAM', proto => 'tcp', dport => '3389' },
343 ],
344 'RIP' => [
345 "Routing Information Protocol (bidirectional)",
346 { action => 'PARAM', proto => 'udp', dport => '520' },
347 ],
348 'RNDC' => [
349 "BIND remote management protocol",
350 { action => 'PARAM', proto => 'tcp', dport => '953' },
351 ],
352 'Razor' => [
353 "Razor Antispam System",
354 { action => 'ACCEPT', proto => 'tcp', dport => '2703' },
355 ],
356 'Rdate' => [
357 "Remote time retrieval (rdate)",
358 { action => 'PARAM', proto => 'tcp', dport => '37' },
359 ],
360 'Rsync' => [
361 "Rsync server",
362 { action => 'PARAM', proto => 'tcp', dport => '873' },
363 ],
364 'SANE' => [
365 "SANE network scanning",
366 { action => 'PARAM', proto => 'tcp', dport => '6566' },
367 ],
368 'SMB' => [
369 "Microsoft SMB traffic",
370 { action => 'PARAM', proto => 'udp', dport => '135,445' },
371 { action => 'PARAM', proto => 'udp', dport => '137:139' },
372 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
373 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
374 ],
375 'SMBswat' => [
376 "Samba Web Administration Tool",
377 { action => 'PARAM', proto => 'tcp', dport => '901' },
378 ],
379 'SMTP' => [
380 "Simple Mail Transfer Protocol",
381 { action => 'PARAM', proto => 'tcp', dport => '25' },
382 ],
383 'SMTPS' => [
384 "Encrypted Simple Mail Transfer Protocol",
385 { action => 'PARAM', proto => 'tcp', dport => '465' },
386 ],
387 'SNMP' => [
388 "Simple Network Management Protocol",
389 { action => 'PARAM', proto => 'udp', dport => '161:162' },
390 { action => 'PARAM', proto => 'tcp', dport => '161' },
391 ],
392 'SPAMD' => [
393 "Spam Assassin SPAMD traffic",
394 { action => 'PARAM', proto => 'tcp', dport => '783' },
395 ],
396 'SSH' => [
397 "Secure shell traffic",
398 { action => 'PARAM', proto => 'tcp', dport => '22' },
399 ],
400 'SVN' => [
401 "Subversion server (svnserve)",
402 { action => 'PARAM', proto => 'tcp', dport => '3690' },
403 ],
404 'SixXS' => [
405 "SixXS IPv6 Deployment and Tunnel Broker",
406 { action => 'PARAM', proto => 'tcp', dport => '3874' },
407 { action => 'PARAM', proto => 'udp', dport => '3740' },
408 { action => 'PARAM', proto => '41' },
409 { action => 'PARAM', proto => 'udp', dport => '5072,8374' },
410 ],
411 'Squid' => [
412 "Squid web proxy traffic",
413 { action => 'PARAM', proto => 'tcp', dport => '3128' },
414 ],
415 'Submission' => [
416 "Mail message submission traffic",
417 { action => 'PARAM', proto => 'tcp', dport => '587' },
418 ],
419 'Syslog' => [
420 "Syslog protocol (RFC 5424) traffic",
421 { action => 'PARAM', proto => 'udp', dport => '514' },
422 { action => 'PARAM', proto => 'tcp', dport => '514' },
423 ],
424 'TFTP' => [
425 "Trivial File Transfer Protocol traffic",
426 { action => 'PARAM', proto => 'udp', dport => '69' },
427 ],
428 'Telnet' => [
429 "Telnet traffic",
430 { action => 'PARAM', proto => 'tcp', dport => '23' },
431 ],
432 'Telnets' => [
433 "Telnet over SSL",
434 { action => 'PARAM', proto => 'tcp', dport => '992' },
435 ],
436 'Time' => [
437 "RFC 868 Time protocol",
438 { action => 'PARAM', proto => 'tcp', dport => '37' },
439 ],
440 'Trcrt' => [
441 "Traceroute (for up to 30 hops) traffic",
442 { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
443 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
444 ],
445 'VNC' => [
446 "VNC traffic for VNC display's 0 - 99",
447 { action => 'PARAM', proto => 'tcp', dport => '5900:5999' },
448 ],
449 'VNCL' => [
450 "VNC traffic from Vncservers to Vncviewers in listen mode",
451 { action => 'PARAM', proto => 'tcp', dport => '5500' },
452 ],
453 'Web' => [
454 "WWW traffic (HTTP and HTTPS)",
455 { action => 'PARAM', proto => 'tcp', dport => '80' },
456 { action => 'PARAM', proto => 'tcp', dport => '443' },
457 ],
458 'Webcache' => [
459 "Web Cache/Proxy traffic (port 8080)",
460 { action => 'PARAM', proto => 'tcp', dport => '8080' },
461 ],
462 'Webmin' => [
463 "Webmin traffic",
464 { action => 'PARAM', proto => 'tcp', dport => '10000' },
465 ],
466 'Whois' => [
467 "Whois (nicname, RFC 3912) traffic",
468 { action => 'PARAM', proto => 'tcp', dport => '43' },
469 ],
470 };
471
472 my $pve_fw_parsed_macros;
473 my $pve_fw_macro_descr;
474 my $pve_fw_preferred_macro_names = {};
475
476 my $pve_std_chains = {
477 'PVEFW-SET-ACCEPT-MARK' => [
478 "-j MARK --set-mark 1",
479 ],
480 'PVEFW-DropBroadcast' => [
481 # same as shorewall 'Broadcast'
482 # simply DROP BROADCAST/MULTICAST/ANYCAST
483 # we can use this to reduce logging
484 { action => 'DROP', dsttype => 'BROADCAST' },
485 { action => 'DROP', dsttype => 'MULTICAST' },
486 { action => 'DROP', dsttype => 'ANYCAST' },
487 { action => 'DROP', dest => '224.0.0.0/4' },
488 ],
489 'PVEFW-reject' => [
490 # same as shorewall 'reject'
491 { action => 'DROP', dsttype => 'BROADCAST' },
492 { action => 'DROP', source => '224.0.0.0/4' },
493 { action => 'DROP', proto => 'icmp' },
494 "-p tcp -j REJECT --reject-with tcp-reset",
495 "-p udp -j REJECT --reject-with icmp-port-unreachable",
496 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
497 "-j REJECT --reject-with icmp-host-prohibited",
498 ],
499 'PVEFW-Drop' => [
500 # same as shorewall 'Drop', which is equal to DROP,
501 # but REJECT/DROP some packages to reduce logging,
502 # and ACCEPT critical ICMP types
503 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
504 # we are not interested in BROADCAST/MULTICAST/ANYCAST
505 { action => 'PVEFW-DropBroadcast' },
506 # ACCEPT critical ICMP types
507 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
508 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
509 # Drop packets with INVALID state
510 "-m conntrack --ctstate INVALID -j DROP",
511 # Drop Microsoft SMB noise
512 { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 },
513 { action => 'DROP', proto => 'udp', dport => '137:139'},
514 { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
515 { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
516 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
517 # Drop new/NotSyn traffic so that it doesn't get logged
518 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
519 # Drop DNS replies
520 { action => 'DROP', proto => 'udp', sport => 53 },
521 ],
522 'PVEFW-Reject' => [
523 # same as shorewall 'Reject', which is equal to Reject,
524 # but REJECT/DROP some packages to reduce logging,
525 # and ACCEPT critical ICMP types
526 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
527 # we are not interested in BROADCAST/MULTICAST/ANYCAST
528 { action => 'PVEFW-DropBroadcast' },
529 # ACCEPT critical ICMP types
530 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
531 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
532 # Drop packets with INVALID state
533 "-m conntrack --ctstate INVALID -j DROP",
534 # Drop Microsoft SMB noise
535 { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
536 { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'},
537 { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 },
538 { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
539 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
540 # Drop new/NotSyn traffic so that it doesn't get logged
541 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
542 # Drop DNS replies
543 { action => 'DROP', proto => 'udp', sport => 53 },
544 ],
545 'PVEFW-tcpflags' => [
546 # same as shorewall tcpflags action.
547 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
548 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
549 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
550 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
551 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
552 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
553 ],
554 'PVEFW-smurfs' => [
555 # same as shorewall smurfs action
556 # Filter packets for smurfs (packets with a broadcast address as the source).
557 "-s 0.0.0.0/32 -j RETURN",
558 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
559 "-s 224.0.0.0/4 -g PVEFW-smurflog",
560 ],
561 };
562
563 # iptables -p icmp -h
564 my $icmp_type_names = {
565 any => 1,
566 'echo-reply' => 1,
567 'destination-unreachable' => 1,
568 'network-unreachable' => 1,
569 'host-unreachable' => 1,
570 'protocol-unreachable' => 1,
571 'port-unreachable' => 1,
572 'fragmentation-needed' => 1,
573 'source-route-failed' => 1,
574 'network-unknown' => 1,
575 'host-unknown' => 1,
576 'network-prohibited' => 1,
577 'host-prohibited' => 1,
578 'TOS-network-unreachable' => 1,
579 'TOS-host-unreachable' => 1,
580 'communication-prohibited' => 1,
581 'host-precedence-violation' => 1,
582 'precedence-cutoff' => 1,
583 'source-quench' => 1,
584 'redirect' => 1,
585 'network-redirect' => 1,
586 'host-redirect' => 1,
587 'TOS-network-redirect' => 1,
588 'TOS-host-redirect' => 1,
589 'echo-request' => 1,
590 'router-advertisement' => 1,
591 'router-solicitation' => 1,
592 'time-exceeded' => 1,
593 'ttl-zero-during-transit' => 1,
594 'ttl-zero-during-reassembly' => 1,
595 'parameter-problem' => 1,
596 'ip-header-bad' => 1,
597 'required-option-missing' => 1,
598 'timestamp-request' => 1,
599 'timestamp-reply' => 1,
600 'address-mask-request' => 1,
601 'address-mask-reply' => 1,
602 };
603
604 sub init_firewall_macros {
605
606 $pve_fw_parsed_macros = {};
607
608 foreach my $k (keys %$pve_fw_macros) {
609 my $lc_name = lc($k);
610 my $macro = $pve_fw_macros->{$k};
611 if (!ref($macro->[0])) {
612 $pve_fw_macro_descr->{$k} = shift @$macro;
613 }
614 $pve_fw_preferred_macro_names->{$lc_name} = $k;
615 $pve_fw_parsed_macros->{$k} = $macro;
616 }
617 }
618
619 init_firewall_macros();
620
621 sub get_macros {
622 return wantarray ? ($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
623 }
624
625 my $etc_services;
626
627 sub get_etc_services {
628
629 return $etc_services if $etc_services;
630
631 my $filename = "/etc/services";
632
633 my $fh = IO::File->new($filename, O_RDONLY);
634 if (!$fh) {
635 warn "unable to read '$filename' - $!\n";
636 return {};
637 }
638
639 my $services = {};
640
641 while (my $line = <$fh>) {
642 chomp ($line);
643 next if $line =~m/^#/;
644 next if ($line =~m/^\s*$/);
645
646 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
647 $services->{byid}->{$2}->{name} = $1;
648 $services->{byid}->{$2}->{port} = $2;
649 $services->{byid}->{$2}->{$3} = 1;
650 $services->{byname}->{$1} = $services->{byid}->{$2};
651 }
652 }
653
654 close($fh);
655
656 $etc_services = $services;
657
658
659 return $etc_services;
660 }
661
662 my $etc_protocols;
663
664 sub get_etc_protocols {
665 return $etc_protocols if $etc_protocols;
666
667 my $filename = "/etc/protocols";
668
669 my $fh = IO::File->new($filename, O_RDONLY);
670 if (!$fh) {
671 warn "unable to read '$filename' - $!\n";
672 return {};
673 }
674
675 my $protocols = {};
676
677 while (my $line = <$fh>) {
678 chomp ($line);
679 next if $line =~m/^#/;
680 next if ($line =~m/^\s*$/);
681
682 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
683 $protocols->{byid}->{$2}->{name} = $1;
684 $protocols->{byname}->{$1} = $protocols->{byid}->{$2};
685 }
686 }
687
688 close($fh);
689
690 $etc_protocols = $protocols;
691
692 return $etc_protocols;
693 }
694
695 my $ipv4_mask_hash_localnet = {
696 '255.255.0.0' => 16,
697 '255.255.128.0' => 17,
698 '255.255.192.0' => 18,
699 '255.255.224.0' => 19,
700 '255.255.240.0' => 20,
701 '255.255.248.0' => 21,
702 '255.255.252.0' => 22,
703 '255.255.254.0' => 23,
704 '255.255.255.0' => 24,
705 '255.255.255.128' => 25,
706 '255.255.255.192' => 26,
707 '255.255.255.224' => 27,
708 '255.255.255.240' => 28,
709 '255.255.255.248' => 29,
710 '255.255.255.252' => 30,
711 };
712
713 my $__local_network;
714
715 sub local_network {
716 my ($new_value) = @_;
717
718 $__local_network = $new_value if defined($new_value);
719
720 return $__local_network if defined($__local_network);
721
722 eval {
723 my $nodename = PVE::INotify::nodename();
724
725 my $ip = PVE::Cluster::remote_node_ip($nodename);
726
727 my $testip = Net::IP->new($ip);
728
729 my $routes = PVE::ProcFSTools::read_proc_net_route();
730 foreach my $entry (@$routes) {
731 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask}};
732 next if !defined($mask);
733 return if $mask eq '0.0.0.0';
734 my $cidr = "$entry->{dest}/$mask";
735 my $testnet = Net::IP->new($cidr);
736 if ($testnet->overlaps($testip)) {
737 $__local_network = $cidr;
738 return;
739 }
740 }
741 };
742 warn $@ if $@;
743
744 return $__local_network;
745 }
746
747 my $max_iptables_ipset_name_length = 27;
748
749 sub compute_ipset_chain_name {
750 my ($vmid, $ipset_name) = @_;
751
752 $vmid = 0 if !defined($vmid);
753
754 my $id = "$vmid-${ipset_name}";
755
756
757 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
758 $id = PVE::Tools::fnv31a_hex($id);
759 }
760
761 return "PVEFW-$id";
762 }
763
764 sub parse_address_list {
765 my ($str) = @_;
766
767 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
768 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
769 return;
770 }
771
772 if ($str =~ m/^${ip_alias_pattern}$/) {
773 die "alias name too long\n" if length($str) > $max_alias_name_length;
774 return;
775 }
776
777 my $count = 0;
778 my $iprange = 0;
779 foreach my $elem (split(/,/, $str)) {
780 $count++;
781 if (!Net::IP->new($elem)) {
782 my $err = Net::IP::Error();
783 die "invalid IP address: $err\n";
784 }
785 $iprange = 1 if $elem =~ m/-/;
786 }
787
788 die "you can use a range in a list\n" if $iprange && $count > 1;
789 }
790
791 sub parse_port_name_number_or_range {
792 my ($str) = @_;
793
794 my $services = PVE::Firewall::get_etc_services();
795 my $count = 0;
796 my $icmp_port = 0;
797
798 foreach my $item (split(/,/, $str)) {
799 $count++;
800 if ($item =~ m/^(\d+):(\d+)$/) {
801 my ($port1, $port2) = ($1, $2);
802 die "invalid port '$port1'\n" if $port1 > 65535;
803 die "invalid port '$port2'\n" if $port2 > 65535;
804 } elsif ($item =~ m/^(\d+)$/) {
805 my $port = $1;
806 die "invalid port '$port'\n" if $port > 65535;
807 } else {
808 if ($icmp_type_names->{$item}) {
809 $icmp_port = 1;
810 } else {
811 die "invalid port '$item'\n" if !$services->{byname}->{$item};
812 }
813 }
814 }
815
816 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
817
818 return $count;
819 }
820
821 PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
822 sub pve_fw_verify_port_spec {
823 my ($portstr) = @_;
824
825 parse_port_name_number_or_range($portstr);
826
827 return $portstr;
828 }
829
830 PVE::JSONSchema::register_format('pve-fw-v4addr-spec', \&pve_fw_verify_v4addr_spec);
831 sub pve_fw_verify_v4addr_spec {
832 my ($list) = @_;
833
834 parse_address_list($list);
835
836 return $list;
837 }
838
839 PVE::JSONSchema::register_format('pve-fw-protocol-spec', \&pve_fw_verify_protocol_spec);
840 sub pve_fw_verify_protocol_spec {
841 my ($proto) = @_;
842
843 my $protocols = get_etc_protocols();
844
845 die "unknown protocol '$proto'\n" if $proto &&
846 !(defined($protocols->{byname}->{$proto}) ||
847 defined($protocols->{byid}->{$proto}));
848
849 return $proto;
850 }
851
852
853 # helper function for API
854
855 sub copy_opject_with_digest {
856 my ($object) = @_;
857
858 my $sha = Digest::SHA->new('sha1');
859
860 my $res = {};
861 foreach my $k (sort keys %$object) {
862 my $v = $object->{$k};
863 next if !defined($v);
864 $res->{$k} = $v;
865 $sha->add($k, ':', $v, "\n");
866 }
867
868 my $digest = $sha->hexdigest;
869
870 $res->{digest} = $digest;
871
872 return wantarray ? ($res, $digest) : $res;
873 }
874
875 sub copy_list_with_digest {
876 my ($list) = @_;
877
878 my $sha = Digest::SHA->new('sha1');
879
880 my $res = [];
881 foreach my $entry (@$list) {
882 my $data = {};
883 foreach my $k (sort keys %$entry) {
884 my $v = $entry->{$k};
885 next if !defined($v);
886 $data->{$k} = $v;
887 # Note: digest ignores refs ($rule->{errors})
888 $sha->add($k, ':', $v, "\n") if !ref($v); ;
889 }
890 push @$res, $data;
891 }
892
893 my $digest = $sha->hexdigest;
894
895 foreach my $entry (@$res) {
896 $entry->{digest} = $digest;
897 }
898
899 return wantarray ? ($res, $digest) : $res;
900 }
901
902 my $rule_properties = {
903 pos => {
904 description => "Update rule at position <pos>.",
905 type => 'integer',
906 minimum => 0,
907 optional => 1,
908 },
909 digest => get_standard_option('pve-config-digest'),
910 type => {
911 type => 'string',
912 optional => 1,
913 enum => ['in', 'out', 'group'],
914 },
915 action => {
916 description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
917 type => 'string',
918 optional => 1,
919 pattern => $security_group_name_pattern,
920 maxLength => 20,
921 minLength => 2,
922 },
923 macro => {
924 type => 'string',
925 optional => 1,
926 maxLength => 128,
927 },
928 iface => get_standard_option('pve-iface', { optional => 1 }),
929 source => {
930 type => 'string', format => 'pve-fw-v4addr-spec',
931 optional => 1,
932 },
933 dest => {
934 type => 'string', format => 'pve-fw-v4addr-spec',
935 optional => 1,
936 },
937 proto => {
938 type => 'string', format => 'pve-fw-protocol-spec',
939 optional => 1,
940 },
941 enable => {
942 type => 'boolean',
943 optional => 1,
944 },
945 sport => {
946 type => 'string', format => 'pve-fw-port-spec',
947 optional => 1,
948 },
949 dport => {
950 type => 'string', format => 'pve-fw-port-spec',
951 optional => 1,
952 },
953 comment => {
954 type => 'string',
955 optional => 1,
956 },
957 };
958
959 sub add_rule_properties {
960 my ($properties) = @_;
961
962 foreach my $k (keys %$rule_properties) {
963 my $h = $rule_properties->{$k};
964 # copy data, so that we can modify later without side effects
965 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
966 }
967
968 return $properties;
969 }
970
971 sub delete_rule_properties {
972 my ($rule, $delete_str) = @_;
973
974 foreach my $opt (PVE::Tools::split_list($delete_str)) {
975 raise_param_exc({ 'delete' => "no such property ('$opt')"})
976 if !defined($rule_properties->{$opt});
977 raise_param_exc({ 'delete' => "unable to delete required property '$opt'"})
978 if $opt eq 'type' || $opt eq 'action';
979 delete $rule->{$opt};
980 }
981
982 return $rule;
983 }
984
985 my $apply_macro = sub {
986 my ($macro_name, $param, $verify) = @_;
987
988 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
989 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
990
991 my $rules = [];
992
993 foreach my $templ (@$macro_rules) {
994 my $rule = {};
995 my $param_used = {};
996 foreach my $k (keys %$templ) {
997 my $v = $templ->{$k};
998 if ($v eq 'PARAM') {
999 $v = $param->{$k};
1000 $param_used->{$k} = 1;
1001 } elsif ($v eq 'DEST') {
1002 $v = $param->{dest};
1003 $param_used->{dest} = 1;
1004 } elsif ($v eq 'SOURCE') {
1005 $v = $param->{source};
1006 $param_used->{source} = 1;
1007 }
1008
1009 if (!defined($v)) {
1010 my $msg = "missing parameter '$k' in macro '$macro_name'";
1011 raise_param_exc({ macro => $msg }) if $verify;
1012 die "$msg\n";
1013 }
1014 $rule->{$k} = $v;
1015 }
1016 foreach my $k (keys %$param) {
1017 next if $k eq 'macro';
1018 next if !defined($param->{$k});
1019 next if $param_used->{$k};
1020 if (defined($rule->{$k})) {
1021 if ($rule->{$k} ne $param->{$k}) {
1022 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1023 raise_param_exc({ $k => $msg }) if $verify;
1024 die "$msg\n";
1025 }
1026 } else {
1027 $rule->{$k} = $param->{$k};
1028 }
1029 }
1030 push @$rules, $rule;
1031 }
1032
1033 return $rules;
1034 };
1035
1036 my $rule_env_iface_lookup = {
1037 'ct' => 1,
1038 'vm' => 1,
1039 'group' => 0,
1040 'cluster' => 1,
1041 'host' => 1,
1042 };
1043
1044 sub verify_rule {
1045 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1046
1047 my $allow_groups = $rule_env eq 'group' ? 0 : 1;
1048
1049 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1050 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1051
1052 my $errors = $rule->{errors} || {};
1053
1054 my $error_count = 0;
1055
1056 my $add_error = sub {
1057 my ($param, $msg) = @_;
1058 chomp $msg;
1059 raise_param_exc({ $param => $msg }) if !$noerr;
1060 $error_count++;
1061 $errors->{$param} = $msg if !$errors->{$param};
1062 };
1063
1064 my $check_ipset_or_alias_property = sub {
1065 my ($name) = @_;
1066
1067 if (my $value = $rule->{$name}) {
1068 if ($value =~ m/^\+/) {
1069 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1070 &$add_error($name, "no such ipset '$1'")
1071 if !($cluster_conf->{ipset}->{$1} || ($fw_conf && $fw_conf->{ipset}->{$1}));
1072
1073 } else {
1074 &$add_error($name, "invalid ipset name '$value'");
1075 }
1076 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1077 my $alias = lc($value);
1078 &$add_error($name, "no such alias '$value'")
1079 if !($cluster_conf->{aliases}->{$alias} || ($fw_conf && $fw_conf->{aliases}->{$alias}))
1080 }
1081 }
1082 };
1083
1084 my $type = $rule->{type};
1085 my $action = $rule->{action};
1086
1087 &$add_error('type', "missing property") if !$type;
1088 &$add_error('action', "missing property") if !$action;
1089
1090 if ($type) {
1091 if ($type eq 'in' || $type eq 'out') {
1092 &$add_error('action', "unknown action '$action'")
1093 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1094 } elsif ($type eq 'group') {
1095 &$add_error('type', "security groups not allowed")
1096 if !$allow_groups;
1097 &$add_error('action', "invalid characters in security group name")
1098 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1099 } else {
1100 &$add_error('type', "unknown rule type '$type'");
1101 }
1102 }
1103
1104 if ($rule->{iface}) {
1105 &$add_error('type', "parameter -i not allowed for this rule type")
1106 if !$allow_iface;
1107 eval { PVE::JSONSchema::pve_verify_iface($rule->{iface}); };
1108 &$add_error('iface', $@) if $@;
1109 if ($rule_env eq 'vm') {
1110 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1111 if $rule->{iface} !~ m/^net(\d+)$/;
1112 } elsif ($rule_env eq 'ct') {
1113 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1114 if $rule->{iface} !~ m/^(venet|eth(\d+))$/;
1115 }
1116 }
1117
1118 if ($rule->{macro}) {
1119 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1120 $rule->{macro} = $preferred_name;
1121 } else {
1122 &$add_error('macro', "unknown macro '$rule->{macro}'");
1123 }
1124 }
1125
1126 if ($rule->{proto}) {
1127 eval { pve_fw_verify_protocol_spec($rule->{proto}); };
1128 &$add_error('proto', $@) if $@;
1129 }
1130
1131 if ($rule->{dport}) {
1132 eval { parse_port_name_number_or_range($rule->{dport}); };
1133 &$add_error('dport', $@) if $@;
1134 &$add_error('proto', "missing property - 'dport' requires this property")
1135 if !$rule->{proto};
1136 }
1137
1138 if ($rule->{sport}) {
1139 eval { parse_port_name_number_or_range($rule->{sport}); };
1140 &$add_error('sport', $@) if $@;
1141 &$add_error('proto', "missing property - 'sport' requires this property")
1142 if !$rule->{proto};
1143 }
1144
1145 if ($rule->{source}) {
1146 eval { parse_address_list($rule->{source}); };
1147 &$add_error('source', $@) if $@;
1148 &$check_ipset_or_alias_property('source');
1149 }
1150
1151 if ($rule->{dest}) {
1152 eval { parse_address_list($rule->{dest}); };
1153 &$add_error('dest', $@) if $@;
1154 &$check_ipset_or_alias_property('dest');
1155 }
1156
1157 if ($rule->{macro} && !$error_count) {
1158 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1159 if (my $err = $@) {
1160 if (ref($err) eq "PVE::Exception" && $err->{errors}) {
1161 my $eh = $err->{errors};
1162 foreach my $p (keys %$eh) {
1163 &$add_error($p, $eh->{$p});
1164 }
1165 } else {
1166 &$add_error('macro', "$err");
1167 }
1168 }
1169 }
1170
1171 $rule->{errors} = $errors if $error_count;
1172
1173 return $rule;
1174 }
1175
1176 sub copy_rule_data {
1177 my ($rule, $param) = @_;
1178
1179 foreach my $k (keys %$rule_properties) {
1180 if (defined(my $v = $param->{$k})) {
1181 if ($v eq '' || $v eq '-') {
1182 delete $rule->{$k};
1183 } else {
1184 $rule->{$k} = $v;
1185 }
1186 }
1187 }
1188
1189 return $rule;
1190 }
1191
1192 # core functions
1193 my $bridge_firewall_enabled = 0;
1194
1195 sub enable_bridge_firewall {
1196
1197 return if $bridge_firewall_enabled; # only once
1198
1199 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1200 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1201
1202 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1203 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
1204
1205 $bridge_firewall_enabled = 1;
1206 }
1207
1208 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1209
1210 sub iptables_restore_cmdlist {
1211 my ($cmdlist) = @_;
1212
1213 run_command("/sbin/iptables-restore -n", input => $cmdlist);
1214 }
1215
1216 sub ipset_restore_cmdlist {
1217 my ($cmdlist) = @_;
1218
1219 run_command("/usr/sbin/ipset restore", input => $cmdlist);
1220 }
1221
1222 sub iptables_get_chains {
1223
1224 my $res = {};
1225
1226 # check what chains we want to track
1227 my $is_pvefw_chain = sub {
1228 my $name = shift;
1229
1230 return 1 if $name =~ m/^PVEFW-\S+$/;
1231
1232 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1233
1234 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1235
1236 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1237
1238 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1239 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1240
1241 return undef;
1242 };
1243
1244 my $table = '';
1245
1246 my $hooks = {};
1247
1248 my $parser = sub {
1249 my $line = shift;
1250
1251 return if $line =~ m/^#/;
1252 return if $line =~ m/^\s*$/;
1253
1254 if ($line =~ m/^\*(\S+)$/) {
1255 $table = $1;
1256 return;
1257 }
1258
1259 return if $table ne 'filter';
1260
1261 if ($line =~ m/^:(\S+)\s/) {
1262 my $chain = $1;
1263 return if !&$is_pvefw_chain($chain);
1264 $res->{$chain} = "unknown";
1265 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1266 my ($chain, $sig) = ($1, $2);
1267 return if !&$is_pvefw_chain($chain);
1268 $res->{$chain} = $sig;
1269 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1270 $hooks->{$1} = 1;
1271 } else {
1272 # simply ignore the rest
1273 return;
1274 }
1275 };
1276
1277 run_command("/sbin/iptables-save", outfunc => $parser);
1278
1279 return wantarray ? ($res, $hooks) : $res;
1280 }
1281
1282 sub iptables_chain_digest {
1283 my ($rules) = @_;
1284 my $digest = Digest::SHA->new('sha1');
1285 foreach my $rule (@$rules) { # order is important
1286 $digest->add($rule);
1287 }
1288 return $digest->b64digest;
1289 }
1290
1291 sub ipset_chain_digest {
1292 my ($rules) = @_;
1293
1294 my $digest = Digest::SHA->new('sha1');
1295 foreach my $rule (sort @$rules) { # note: sorted
1296 $digest->add($rule);
1297 }
1298 return $digest->b64digest;
1299 }
1300
1301 sub ipset_get_chains {
1302
1303 my $res = {};
1304 my $chains = {};
1305
1306 my $parser = sub {
1307 my $line = shift;
1308
1309 return if $line =~ m/^#/;
1310 return if $line =~ m/^\s*$/;
1311 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1312 my $chain = $1;
1313 $line =~ s/\s+$//; # delete trailing white space
1314 push @{$chains->{$chain}}, $line;
1315 } else {
1316 # simply ignore the rest
1317 return;
1318 }
1319 };
1320
1321 run_command("/usr/sbin/ipset save", outfunc => $parser);
1322
1323 # compute digest for each chain
1324 foreach my $chain (keys %$chains) {
1325 $res->{$chain} = ipset_chain_digest($chains->{$chain});
1326 }
1327
1328 return $res;
1329 }
1330
1331 sub ruleset_generate_cmdstr {
1332 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1333
1334 return if defined($rule->{enable}) && !$rule->{enable};
1335 return if $rule->{errors};
1336
1337 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1338
1339 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
1340 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
1341
1342 my @cmd = ();
1343
1344 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1345 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1346
1347 my $source = $rule->{source};
1348 my $dest = $rule->{dest};
1349
1350 if ($source) {
1351 if ($source =~ m/^\+/) {
1352 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1353 my $name = $1;
1354 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
1355 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name);
1356 push @cmd, "-m set --match-set ${ipset_chain} src";
1357 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
1358 my $ipset_chain = compute_ipset_chain_name(0, $name);
1359 push @cmd, "-m set --match-set ${ipset_chain} src";
1360 } else {
1361 die "no such ipset '$name'\n";
1362 }
1363 } else {
1364 die "invalid security group name '$source'\n";
1365 }
1366 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1367 my $alias = lc($source);
1368 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
1369 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1370 die "no such alias '$source'\n" if !$e;
1371 push @cmd, "-s $e->{cidr}";
1372 } elsif ($source =~ m/\-/){
1373 push @cmd, "-m iprange --src-range $source";
1374 } else {
1375 push @cmd, "-s $source";
1376 }
1377 }
1378
1379 if ($dest) {
1380 if ($dest =~ m/^\+/) {
1381 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1382 my $name = $1;
1383 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
1384 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name);
1385 push @cmd, "-m set --match-set ${ipset_chain} dst";
1386 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
1387 my $ipset_chain = compute_ipset_chain_name(0, $name);
1388 push @cmd, "-m set --match-set ${ipset_chain} dst";
1389 } else {
1390 die "no such ipset '$name'\n";
1391 }
1392 } else {
1393 die "invalid security group name '$dest'\n";
1394 }
1395 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1396 my $alias = lc($dest);
1397 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
1398 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1399 die "no such alias '$dest'\n" if !$e;
1400 push @cmd, "-d $e->{cidr}";
1401 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1402 push @cmd, "-m iprange --dst-range $dest";
1403 } else {
1404 push @cmd, "-d $dest";
1405 }
1406 }
1407
1408 if ($rule->{proto}) {
1409 push @cmd, "-p $rule->{proto}";
1410
1411 my $multiport = 0;
1412 $multiport++ if $nbdport > 1;
1413 $multiport++ if $nbsport > 1;
1414
1415 push @cmd, "--match multiport" if $multiport;
1416
1417 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1418 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1419
1420 if ($rule->{dport}) {
1421 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
1422 # Note: we use dport to store --icmp-type
1423 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
1424 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1425 } else {
1426 if ($nbdport > 1) {
1427 if ($multiport == 2) {
1428 push @cmd, "--ports $rule->{dport}";
1429 } else {
1430 push @cmd, "--dports $rule->{dport}";
1431 }
1432 } else {
1433 push @cmd, "--dport $rule->{dport}";
1434 }
1435 }
1436 }
1437
1438 if ($rule->{sport}) {
1439 if ($nbsport > 1) {
1440 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1441 } else {
1442 push @cmd, "--sport $rule->{sport}";
1443 }
1444 }
1445 } elsif ($rule->{dport} || $rule->{sport}) {
1446 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1447 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
1448 }
1449
1450 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
1451
1452 if (my $action = $rule->{action}) {
1453 $action = $actions->{$action} if defined($actions->{$action});
1454 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1455 push @cmd, $goto ? "-g $action" : "-j $action";
1456 }
1457
1458 return scalar(@cmd) ? join(' ', @cmd) : undef;
1459 }
1460
1461 sub ruleset_generate_rule {
1462 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1463
1464 my $rules;
1465
1466 if ($rule->{macro}) {
1467 $rules = &$apply_macro($rule->{macro}, $rule);
1468 } else {
1469 $rules = [ $rule ];
1470 }
1471
1472 # update all or nothing
1473
1474 my @cmds = ();
1475 foreach my $tmp (@$rules) {
1476 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1477 push @cmds, $cmdstr;
1478 }
1479 }
1480
1481 foreach my $cmdstr (@cmds) {
1482 ruleset_addrule($ruleset, $chain, $cmdstr);
1483 }
1484 }
1485
1486 sub ruleset_generate_rule_insert {
1487 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1488
1489 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1490
1491 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
1492 ruleset_insertrule($ruleset, $chain, $cmdstr);
1493 }
1494 }
1495
1496 sub ruleset_create_chain {
1497 my ($ruleset, $chain) = @_;
1498
1499 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1500 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1501
1502 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1503
1504 $ruleset->{$chain} = [];
1505 }
1506
1507 sub ruleset_chain_exist {
1508 my ($ruleset, $chain) = @_;
1509
1510 return $ruleset->{$chain} ? 1 : undef;
1511 }
1512
1513 sub ruleset_addrule {
1514 my ($ruleset, $chain, $rule) = @_;
1515
1516 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1517
1518 push @{$ruleset->{$chain}}, "-A $chain $rule";
1519 }
1520
1521 sub ruleset_insertrule {
1522 my ($ruleset, $chain, $rule) = @_;
1523
1524 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1525
1526 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1527 }
1528
1529 sub get_log_rule_base {
1530 my ($chain, $vmid, $msg, $loglevel) = @_;
1531
1532 die "internal error - no log level" if !defined($loglevel);
1533
1534 $vmid = 0 if !defined($vmid);
1535
1536 # Note: we use special format for prefix to pass further
1537 # info to log daemon (VMID, LOGVELEL and CHAIN)
1538
1539 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1540 }
1541
1542 sub ruleset_addlog {
1543 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1544
1545 return if !defined($loglevel);
1546
1547 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1548
1549 $logrule = "$rule $logrule" if defined($rule);
1550
1551 ruleset_addrule($ruleset, $chain, $logrule);
1552 }
1553
1554 sub ruleset_add_chain_policy {
1555 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1556
1557 if ($policy eq 'ACCEPT') {
1558
1559 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1560 { ACCEPT => $accept_action});
1561
1562 } elsif ($policy eq 'DROP') {
1563
1564 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1565
1566 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1567
1568 ruleset_addrule($ruleset, $chain, "-j DROP");
1569 } elsif ($policy eq 'REJECT') {
1570 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1571
1572 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1573
1574 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1575 } else {
1576 # should not happen
1577 die "internal error: unknown policy '$policy'";
1578 }
1579 }
1580
1581 sub ruleset_chain_add_conn_filters {
1582 my ($ruleset, $chain, $accept) = @_;
1583
1584 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1585 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1586 }
1587
1588 sub ruleset_chain_add_input_filters {
1589 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1590
1591 if ($cluster_conf->{ipset}->{blacklist}){
1592 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
1593 ruleset_create_chain($ruleset, "PVEFW-blacklist");
1594 ruleset_addlog($ruleset, "PVEFW-blacklist", 0, "DROP: ", $loglevel) if $loglevel;
1595 ruleset_addrule($ruleset, "PVEFW-blacklist", "-j DROP");
1596 }
1597 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1598 ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src -j PVEFW-blacklist");
1599 }
1600
1601 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1602 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1603 }
1604
1605 if ($options->{tcpflags}) {
1606 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1607 }
1608 }
1609
1610 sub ruleset_create_vm_chain {
1611 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1612
1613 ruleset_create_chain($ruleset, $chain);
1614 my $accept = generate_nfqueue($options);
1615
1616 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1617 if ($direction eq 'OUT') {
1618 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1619 proto => 'udp', sport => 68, dport => 67 });
1620 } else {
1621 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1622 proto => 'udp', sport => 67, dport => 68 });
1623 }
1624 }
1625
1626 if ($direction eq 'OUT') {
1627 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1628 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
1629 }
1630 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1631 }
1632 }
1633
1634 sub ruleset_add_group_rule {
1635 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1636
1637 my $group = $rule->{action};
1638 my $group_chain = "GROUP-$group-$direction";
1639 if(!ruleset_chain_exist($ruleset, $group_chain)){
1640 generate_group_rules($ruleset, $cluster_conf, $group);
1641 }
1642
1643 if ($direction eq 'OUT' && $rule->{iface_out}) {
1644 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain");
1645 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1646 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in} -j $group_chain");
1647 } else {
1648 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1649 }
1650
1651 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $action");
1652 }
1653
1654 sub ruleset_generate_vm_rules {
1655 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options) = @_;
1656
1657 my $lc_direction = lc($direction);
1658
1659 my $in_accept = generate_nfqueue($options);
1660
1661 foreach my $rule (@$rules) {
1662 next if $rule->{iface} && $rule->{iface} ne $netid;
1663 next if !$rule->{enable} || $rule->{errors};
1664 if ($rule->{type} eq 'group') {
1665 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1666 $direction eq 'OUT' ? 'RETURN' : $in_accept);
1667 } else {
1668 next if $rule->{type} ne $lc_direction;
1669 eval {
1670 if ($direction eq 'OUT') {
1671 ruleset_generate_rule($ruleset, $chain, $rule,
1672 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
1673 undef, $cluster_conf, $vmfw_conf);
1674 } else {
1675 ruleset_generate_rule($ruleset, $chain, $rule,
1676 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
1677 undef, $cluster_conf, $vmfw_conf);
1678 }
1679 };
1680 warn $@ if $@;
1681 }
1682 }
1683 }
1684
1685 sub generate_nfqueue {
1686 my ($options) = @_;
1687
1688 if ($options->{ips}) {
1689 my $action = "NFQUEUE";
1690 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1691 if (defined($3) && defined($1)) {
1692 $action .= " --queue-balance $1:$3";
1693 } elsif (defined($1)) {
1694 $action .= " --queue-num $1";
1695 }
1696 }
1697 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
1698 return $action;
1699 } else {
1700 return "ACCEPT";
1701 }
1702 }
1703
1704 sub ruleset_generate_vm_ipsrules {
1705 my ($ruleset, $options, $direction, $iface) = @_;
1706
1707 if ($options->{ips} && $direction eq 'IN') {
1708 my $nfqueue = generate_nfqueue($options);
1709
1710 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
1711 ruleset_create_chain($ruleset, "PVEFW-IPS");
1712 }
1713
1714 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
1715 }
1716 }
1717
1718 sub generate_venet_rules_direction {
1719 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1720
1721 my $lc_direction = lc($direction);
1722
1723 my $rules = $vmfw_conf->{rules};
1724
1725 my $options = $vmfw_conf->{options};
1726 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1727
1728 my $chain = "venet0-$vmid-$direction";
1729
1730 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1731
1732 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction);
1733
1734 # implement policy
1735 my $policy;
1736
1737 if ($direction eq 'OUT') {
1738 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1739 } else {
1740 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1741 }
1742
1743 my $accept = generate_nfqueue($options);
1744 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1745 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1746
1747 if ($direction eq 'OUT') {
1748 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT", {
1749 action => $chain,
1750 source => $ip,
1751 iface_in => 'venet0'});
1752 } else {
1753 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN", {
1754 action => $chain,
1755 dest => $ip,
1756 iface_out => 'venet0'});
1757 }
1758 }
1759
1760 sub generate_tap_rules_direction {
1761 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
1762
1763 my $lc_direction = lc($direction);
1764
1765 my $rules = $vmfw_conf->{rules};
1766
1767 my $options = $vmfw_conf->{options};
1768 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1769
1770 my $tapchain = "$iface-$direction";
1771
1772 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1773
1774 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options);
1775
1776 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1777
1778 # implement policy
1779 my $policy;
1780
1781 if ($direction eq 'OUT') {
1782 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1783 } else {
1784 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1785 }
1786
1787 my $accept = generate_nfqueue($options);
1788 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1789 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1790
1791 # plug the tap chain to bridge chain
1792 if ($direction eq 'IN') {
1793 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
1794 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
1795 } else {
1796 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
1797 "-m physdev --physdev-is-bridged --physdev-in $iface -j $tapchain");
1798 }
1799 }
1800
1801 sub enable_host_firewall {
1802 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1803
1804 my $options = $hostfw_conf->{options};
1805 my $cluster_options = $cluster_conf->{options};
1806 my $rules = $hostfw_conf->{rules};
1807 my $cluster_rules = $cluster_conf->{rules};
1808
1809 # host inbound firewall
1810 my $chain = "PVEFW-HOST-IN";
1811 ruleset_create_chain($ruleset, $chain);
1812
1813 my $loglevel = get_option_log_level($options, "log_level_in");
1814
1815 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
1816
1817 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1818 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1819
1820 # we use RETURN because we need to check also tap rules
1821 my $accept_action = 'RETURN';
1822
1823 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
1824
1825 # add host rules first, so that cluster wide rules can be overwritten
1826 foreach my $rule (@$rules, @$cluster_rules) {
1827 next if !$rule->{enable} || $rule->{errors};
1828
1829 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1830
1831 eval {
1832 if ($rule->{type} eq 'group') {
1833 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1834 } elsif ($rule->{type} eq 'in') {
1835 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
1836 undef, $cluster_conf, $hostfw_conf);
1837 }
1838 };
1839 warn $@ if $@;
1840 delete $rule->{iface_in};
1841 }
1842
1843 # allow standard traffic for management ipset (includes cluster network)
1844 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management");
1845 my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src";
1846 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006 -j $accept_action"); # PVE API
1847 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
1848 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
1849 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22 -j $accept_action"); # SSH
1850
1851 my $localnet = local_network();
1852
1853 # corosync
1854 if ($localnet) {
1855 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
1856 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule");
1857 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule");
1858 }
1859
1860 # implement input policy
1861 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1862 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1863
1864 # host outbound firewall
1865 $chain = "PVEFW-HOST-OUT";
1866 ruleset_create_chain($ruleset, $chain);
1867
1868 $loglevel = get_option_log_level($options, "log_level_out");
1869
1870 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
1871
1872 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1873
1874 # we use RETURN because we may want to check other thigs later
1875 $accept_action = 'RETURN';
1876
1877 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
1878
1879 # add host rules first, so that cluster wide rules can be overwritten
1880 foreach my $rule (@$rules, @$cluster_rules) {
1881 next if !$rule->{enable} || $rule->{errors};
1882
1883 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1884 eval {
1885 if ($rule->{type} eq 'group') {
1886 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1887 } elsif ($rule->{type} eq 'out') {
1888 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
1889 undef, $cluster_conf, $hostfw_conf);
1890 }
1891 };
1892 warn $@ if $@;
1893 delete $rule->{iface_out};
1894 }
1895
1896 # allow standard traffic on cluster network
1897 if ($localnet) {
1898 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006 -j $accept_action"); # PVE API
1899 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22 -j $accept_action"); # SSH
1900 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
1901 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
1902
1903 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
1904 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule");
1905 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule");
1906 }
1907
1908 # implement output policy
1909 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1910 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1911
1912 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1913 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
1914 }
1915
1916 sub generate_group_rules {
1917 my ($ruleset, $cluster_conf, $group) = @_;
1918
1919 my $rules = $cluster_conf->{groups}->{$group};
1920
1921 if (!$rules) {
1922 warn "no such security group '$group'\n";
1923 $rules = []; # create empty chain
1924 }
1925
1926 my $chain = "GROUP-${group}-IN";
1927
1928 ruleset_create_chain($ruleset, $chain);
1929 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1930
1931 foreach my $rule (@$rules) {
1932 next if $rule->{type} ne 'in';
1933 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1934 }
1935
1936 $chain = "GROUP-${group}-OUT";
1937
1938 ruleset_create_chain($ruleset, $chain);
1939 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1940
1941 foreach my $rule (@$rules) {
1942 next if $rule->{type} ne 'out';
1943 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1944 # check also other tap rules later
1945 ruleset_generate_rule($ruleset, $chain, $rule,
1946 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1947 }
1948 }
1949
1950 my $MAX_NETS = 32;
1951 my $valid_netdev_names = {};
1952 for (my $i = 0; $i < $MAX_NETS; $i++) {
1953 $valid_netdev_names->{"net$i"} = 1;
1954 }
1955
1956 sub parse_fw_rule {
1957 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
1958
1959 chomp $line;
1960
1961 my $orig_line = $line;
1962
1963 my $rule = {};
1964
1965 # we can add single line comments to the end of the rule
1966 if ($line =~ s/#\s*(.*?)\s*$//) {
1967 $rule->{comment} = decode('utf8', $1);
1968 }
1969
1970 # we can disable a rule when prefixed with '|'
1971
1972 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
1973
1974 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1975 die "unable to parse rule: $line\n";
1976
1977 $rule->{type} = lc($1);
1978 $rule->{action} = $2;
1979
1980 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1981 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1982 $rule->{macro} = $1;
1983 $rule->{action} = $2;
1984 }
1985 }
1986
1987 while (length($line)) {
1988 if ($line =~ s/^-i (\S+)\s*//) {
1989 $rule->{iface} = $1;
1990 next;
1991 }
1992
1993 last if $rule->{type} eq 'group';
1994
1995 if ($line =~ s/^-p (\S+)\s*//) {
1996 $rule->{proto} = $1;
1997 next;
1998 }
1999
2000 if ($line =~ s/^-dport (\S+)\s*//) {
2001 $rule->{dport} = $1;
2002 next;
2003 }
2004
2005 if ($line =~ s/^-sport (\S+)\s*//) {
2006 $rule->{sport} = $1;
2007 next;
2008 }
2009 if ($line =~ s/^-source (\S+)\s*//) {
2010 $rule->{source} = $1;
2011 next;
2012 }
2013 if ($line =~ s/^-dest (\S+)\s*//) {
2014 $rule->{dest} = $1;
2015 next;
2016 }
2017
2018 last;
2019 }
2020
2021 die "unable to parse rule parameters: $line\n" if length($line);
2022
2023 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2024 if ($verbose && $rule->{errors}) {
2025 warn "$prefix - errors in rule parameters: $orig_line\n";
2026 foreach my $p (keys %{$rule->{errors}}) {
2027 warn " $p: $rule->{errors}->{$p}\n";
2028 }
2029 }
2030
2031 return $rule;
2032 }
2033
2034 sub parse_vmfw_option {
2035 my ($line) = @_;
2036
2037 my ($opt, $value);
2038
2039 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2040
2041 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2042 $opt = lc($1);
2043 $value = int($2);
2044 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2045 $opt = lc($1);
2046 $value = $2 ? lc($3) : '';
2047 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2048 $opt = lc($1);
2049 $value = uc($3);
2050 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2051 $opt = lc($1);
2052 $value = $2;
2053 } else {
2054 chomp $line;
2055 die "can't parse option '$line'\n"
2056 }
2057
2058 return ($opt, $value);
2059 }
2060
2061 sub parse_hostfw_option {
2062 my ($line) = @_;
2063
2064 my ($opt, $value);
2065
2066 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2067
2068 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2069 $opt = lc($1);
2070 $value = int($2);
2071 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2072 $opt = lc($1);
2073 $value = $2 ? lc($3) : '';
2074 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2075 $opt = lc($1);
2076 $value = int($2);
2077 } else {
2078 chomp $line;
2079 die "can't parse option '$line'\n"
2080 }
2081
2082 return ($opt, $value);
2083 }
2084
2085 sub parse_clusterfw_option {
2086 my ($line) = @_;
2087
2088 my ($opt, $value);
2089
2090 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2091 $opt = lc($1);
2092 $value = int($2);
2093 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2094 $opt = lc($1);
2095 $value = uc($3);
2096 } else {
2097 chomp $line;
2098 die "can't parse option '$line'\n"
2099 }
2100
2101 return ($opt, $value);
2102 }
2103
2104 sub parse_alias {
2105 my ($line) = @_;
2106
2107 # we can add single line comments to the end of the line
2108 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2109
2110 if ($line =~ m/^(\S+)\s(\S+)$/) {
2111 my ($name, $cidr) = ($1, $2);
2112 $cidr =~ s|/32$||;
2113 pve_verify_ipv4_or_cidr($cidr);
2114 my $data = {
2115 name => $name,
2116 cidr => $cidr,
2117 };
2118 $data->{comment} = $comment if $comment;
2119 return $data;
2120 }
2121
2122 return undef;
2123 }
2124
2125 sub generic_fw_rules_parser {
2126 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2127
2128 my $section;
2129 my $group;
2130
2131 my $res = $empty_conf;
2132
2133 my $ipset_option = get_standard_option('ipset-name');
2134
2135 while (defined(my $line = <$fh>)) {
2136 next if $line =~ m/^#/;
2137 next if $line =~ m/^\s*$/;
2138
2139 my $linenr = $fh->input_line_number();
2140 my $prefix = "$filename (line $linenr)";
2141
2142 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2143 $section = 'options';
2144 next;
2145 }
2146
2147 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2148 $section = 'aliases';
2149 next;
2150 }
2151
2152 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2153 $section = 'groups';
2154 $group = lc($1);
2155 my $comment = $2;
2156 eval {
2157 die "security group name too long\n" if length($group) > $max_group_name_length;
2158 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2159 };
2160 if (my $err = $@) {
2161 ($section, $group, $comment) = undef;
2162 warn "$prefix: $err";
2163 next;
2164 }
2165
2166 $res->{$section}->{$group} = [];
2167 $res->{group_comments}->{$group} = decode('utf8', $comment)
2168 if $comment;
2169 next;
2170 }
2171
2172 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2173 $section = 'rules';
2174 next;
2175 }
2176
2177 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2178 $section = 'ipset';
2179 $group = lc($1);
2180 my $comment = $2;
2181 eval {
2182 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2183 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2184 };
2185 if (my $err = $@) {
2186 ($section, $group, $comment) = undef;
2187 warn "$prefix: $err";
2188 next;
2189 }
2190
2191 $res->{$section}->{$group} = [];
2192 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
2193 if $comment;
2194 next;
2195 }
2196
2197 if (!$section) {
2198 warn "$prefix: skip line - no section\n";
2199 next;
2200 }
2201
2202 if ($section eq 'options') {
2203 eval {
2204 my ($opt, $value);
2205 if ($rule_env eq 'cluster') {
2206 ($opt, $value) = parse_clusterfw_option($line);
2207 } elsif ($rule_env eq 'host') {
2208 ($opt, $value) = parse_hostfw_option($line);
2209 } else {
2210 ($opt, $value) = parse_vmfw_option($line);
2211 }
2212 $res->{options}->{$opt} = $value;
2213 };
2214 warn "$prefix: $@" if $@;
2215 } elsif ($section eq 'aliases') {
2216 eval {
2217 my $data = parse_alias($line);
2218 $res->{aliases}->{lc($data->{name})} = $data;
2219 };
2220 warn "$prefix: $@" if $@;
2221 } elsif ($section eq 'rules') {
2222 my $rule;
2223 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2224 if (my $err = $@) {
2225 warn "$prefix: $err";
2226 next;
2227 }
2228 push @{$res->{$section}}, $rule;
2229 } elsif ($section eq 'groups') {
2230 my $rule;
2231 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); };
2232 if (my $err = $@) {
2233 warn "$prefix: $err";
2234 next;
2235 }
2236 push @{$res->{$section}->{$group}}, $rule;
2237 } elsif ($section eq 'ipset') {
2238 # we can add single line comments to the end of the rule
2239 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2240
2241 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2242 my $nomatch = $1;
2243 my $cidr = $2;
2244
2245 if($cidr !~ m/^${ip_alias_pattern}$/) {
2246 $cidr =~ s|/32$||;
2247
2248 eval { pve_verify_ipv4_or_cidr($cidr); };
2249 if (my $err = $@) {
2250 warn "$prefix: $cidr - $err";
2251 next;
2252 }
2253 }
2254
2255 my $entry = { cidr => $cidr };
2256 $entry->{nomatch} = 1 if $nomatch;
2257 $entry->{comment} = $comment if $comment;
2258
2259 push @{$res->{$section}->{$group}}, $entry;
2260 } else {
2261 warn "$prefix: skip line - unknown section\n";
2262 next;
2263 }
2264 }
2265
2266 return $res;
2267 }
2268
2269 sub parse_host_fw_rules {
2270 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2271
2272 my $empty_conf = { rules => [], options => {}};
2273
2274 return generic_fw_rules_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host');
2275 }
2276
2277 sub parse_vm_fw_rules {
2278 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2279
2280 my $empty_conf = {
2281 rules => [],
2282 options => {},
2283 aliases => {},
2284 ipset => {} ,
2285 ipset_comments => {},
2286 };
2287
2288 return generic_fw_rules_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2289 }
2290
2291 sub parse_cluster_fw_rules {
2292 my ($filename, $fh, $verbose) = @_;
2293
2294 my $section;
2295 my $group;
2296
2297 my $empty_conf = {
2298 rules => [],
2299 options => {},
2300 aliases => {},
2301 groups => {},
2302 group_comments => {},
2303 ipset => {} ,
2304 ipset_comments => {},
2305 };
2306
2307 return generic_fw_rules_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster');
2308 }
2309
2310 sub run_locked {
2311 my ($code, @param) = @_;
2312
2313 my $timeout = 10;
2314
2315 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2316
2317 die $@ if $@;
2318
2319 return $res;
2320 }
2321
2322 sub read_local_vm_config {
2323
2324 my $openvz = {};
2325 my $qemu = {};
2326
2327 my $vmdata = { openvz => $openvz, qemu => $qemu };
2328
2329 my $vmlist = PVE::Cluster::get_vmlist();
2330 return $vmdata if !$vmlist || !$vmlist->{ids};
2331 my $ids = $vmlist->{ids};
2332
2333 foreach my $vmid (keys %$ids) {
2334 next if !$vmid; # skip VE0
2335 my $d = $ids->{$vmid};
2336 next if !$d->{node} || $d->{node} ne $nodename;
2337 next if !$d->{type};
2338 if ($d->{type} eq 'openvz') {
2339 if ($have_pve_manager) {
2340 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2341 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2342 $openvz->{$vmid} = $conf;
2343 }
2344 }
2345 } elsif ($d->{type} eq 'qemu') {
2346 if ($have_qemu_server) {
2347 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2348 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2349 $qemu->{$vmid} = $conf;
2350 }
2351 }
2352 }
2353 }
2354
2355 return $vmdata;
2356 };
2357
2358 sub load_vmfw_conf {
2359 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2360
2361 my $vmfw_conf = {};
2362
2363 $dir = "/etc/pve/firewall" if !defined($dir);
2364
2365 my $filename = "$dir/$vmid.fw";
2366 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2367 $vmfw_conf = parse_vm_fw_rules($filename, $fh, $cluster_conf, $rule_env, $verbose);
2368 $vmfw_conf->{vmid} = $vmid;
2369 }
2370
2371 return $vmfw_conf;
2372 }
2373
2374 my $format_rules = sub {
2375 my ($rules, $allow_iface) = @_;
2376
2377 my $raw = '';
2378
2379 foreach my $rule (@$rules) {
2380 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
2381 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2382 $raw .= uc($rule->{type});
2383 if ($rule->{macro}) {
2384 $raw .= " $rule->{macro}($rule->{action})";
2385 } else {
2386 $raw .= " " . $rule->{action};
2387 }
2388 if ($allow_iface && $rule->{iface}) {
2389 $raw .= " -i $rule->{iface}";
2390 }
2391
2392 if ($rule->{type} ne 'group') {
2393 $raw .= " -source $rule->{source}" if $rule->{source};
2394 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2395 $raw .= " -p $rule->{proto}" if $rule->{proto};
2396 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2397 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2398 }
2399
2400 $raw .= " # " . encode('utf8', $rule->{comment})
2401 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2402 $raw .= "\n";
2403 } else {
2404 die "unknown rule type '$rule->{type}'";
2405 }
2406 }
2407
2408 return $raw;
2409 };
2410
2411 my $format_options = sub {
2412 my ($options) = @_;
2413
2414 my $raw = '';
2415
2416 $raw .= "[OPTIONS]\n\n";
2417 foreach my $opt (keys %$options) {
2418 $raw .= "$opt: $options->{$opt}\n";
2419 }
2420 $raw .= "\n";
2421
2422 return $raw;
2423 };
2424
2425 my $format_aliases = sub {
2426 my ($aliases) = @_;
2427
2428 my $raw = '';
2429
2430 $raw .= "[ALIASES]\n\n";
2431 foreach my $k (keys %$aliases) {
2432 my $e = $aliases->{$k};
2433 $raw .= "$e->{name} $e->{cidr}";
2434 $raw .= " # " . encode('utf8', $e->{comment})
2435 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2436 $raw .= "\n";
2437 }
2438 $raw .= "\n";
2439
2440 return $raw;
2441 };
2442
2443 my $format_ipsets = sub {
2444 my ($fw_conf) = @_;
2445
2446 my $raw = '';
2447
2448 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2449 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2450 my $utf8comment = encode('utf8', $comment);
2451 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2452 } else {
2453 $raw .= "[IPSET $ipset]\n\n";
2454 }
2455 my $options = $fw_conf->{ipset}->{$ipset};
2456
2457 my $nethash = {};
2458 foreach my $entry (@$options) {
2459 $nethash->{$entry->{cidr}} = $entry;
2460 }
2461
2462 foreach my $cidr (sort keys %$nethash) {
2463 my $entry = $nethash->{$cidr};
2464 my $line = $entry->{nomatch} ? '!' : '';
2465 $line .= $entry->{cidr};
2466 $line .= " # " . encode('utf8', $entry->{comment})
2467 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2468 $raw .= "$line\n";
2469 }
2470
2471 $raw .= "\n";
2472 }
2473
2474 return $raw;
2475 };
2476
2477 sub save_vmfw_conf {
2478 my ($vmid, $vmfw_conf) = @_;
2479
2480 my $raw = '';
2481
2482 my $options = $vmfw_conf->{options};
2483 $raw .= &$format_options($options) if scalar(keys %$options);
2484
2485 my $aliases = $vmfw_conf->{aliases};
2486 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2487
2488 $raw .= &$format_ipsets($vmfw_conf);
2489
2490 my $rules = $vmfw_conf->{rules} || [];
2491 if (scalar(@$rules)) {
2492 $raw .= "[RULES]\n\n";
2493 $raw .= &$format_rules($rules, 1);
2494 $raw .= "\n";
2495 }
2496
2497 my $filename = "/etc/pve/firewall/$vmid.fw";
2498 PVE::Tools::file_set_contents($filename, $raw);
2499 }
2500
2501 sub read_vm_firewall_configs {
2502 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2503
2504 my $vmfw_configs = {};
2505
2506 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2507 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose);
2508 next if !$vmfw_conf->{options}; # skip if file does not exists
2509 $vmfw_configs->{$vmid} = $vmfw_conf;
2510 }
2511 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2512 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose);
2513 next if !$vmfw_conf->{options}; # skip if file does not exists
2514 $vmfw_configs->{$vmid} = $vmfw_conf;
2515 }
2516
2517 return $vmfw_configs;
2518 }
2519
2520 sub get_option_log_level {
2521 my ($options, $k) = @_;
2522
2523 my $v = $options->{$k};
2524 $v = $default_log_level if !defined($v);
2525
2526 return undef if $v eq '' || $v eq 'nolog';
2527
2528 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2529
2530 return $v if ($v >= 0) && ($v <= 7);
2531
2532 warn "unknown log level ($k = '$v')\n";
2533
2534 return undef;
2535 }
2536
2537 sub generate_std_chains {
2538 my ($ruleset, $options) = @_;
2539
2540 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2541
2542 # same as shorewall smurflog.
2543 my $chain = 'PVEFW-smurflog';
2544 $pve_std_chains->{$chain} = [];
2545
2546 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2547 push @{$pve_std_chains->{$chain}}, "-j DROP";
2548
2549 # same as shorewall logflags action.
2550 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
2551 $chain = 'PVEFW-logflags';
2552 $pve_std_chains->{$chain} = [];
2553
2554 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2555 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2556 push @{$pve_std_chains->{$chain}}, "-j DROP";
2557
2558 foreach my $chain (keys %$pve_std_chains) {
2559 ruleset_create_chain($ruleset, $chain);
2560 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2561 if (ref($rule)) {
2562 ruleset_generate_rule($ruleset, $chain, $rule);
2563 } else {
2564 ruleset_addrule($ruleset, $chain, $rule);
2565 }
2566 }
2567 }
2568 }
2569
2570 sub generate_ipset_chains {
2571 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2572
2573 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2574 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2575 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2576 }
2577 }
2578
2579 sub generate_ipset {
2580 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2581
2582 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2583
2584 my $hashsize = scalar(@$options);
2585 if ($hashsize <= 64) {
2586 $hashsize = 64;
2587 } else {
2588 $hashsize = round_powerof2($hashsize);
2589 }
2590
2591 $ipset_ruleset->{$name} = ["create $name hash:net family inet hashsize $hashsize maxelem $hashsize"];
2592
2593 # remove duplicates
2594 my $nethash = {};
2595 foreach my $entry (@$options) {
2596 my $cidr = $entry->{cidr};
2597 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2598 my $alias = lc($cidr);
2599 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2600 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2601 if ($e) {
2602 $entry->{cidr} = $e->{cidr};
2603 $nethash->{$entry->{cidr}} = $entry;
2604 } else {
2605 warn "no such alias '$cidr'\n";
2606 }
2607 } else {
2608 $nethash->{$entry->{cidr}} = $entry;
2609 }
2610 }
2611
2612 foreach my $cidr (sort keys %$nethash) {
2613 my $entry = $nethash->{$cidr};
2614
2615 my $cmd = "add $name $cidr";
2616 if ($entry->{nomatch}) {
2617 if ($feature_ipset_nomatch) {
2618 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2619 } else {
2620 warn "ignore !$cidr - nomatch not supported by kernel\n";
2621 }
2622 } else {
2623 push @{$ipset_ruleset->{$name}}, $cmd;
2624 }
2625 }
2626 }
2627
2628 sub round_powerof2 {
2629 my ($int) = @_;
2630
2631 $int--;
2632 $int |= $int >> $_ foreach (1,2,4,8,16);
2633 return ++$int;
2634 }
2635
2636 sub load_clusterfw_conf {
2637 my ($filename, $verbose) = @_;
2638
2639 $filename = $clusterfw_conf_filename if !defined($filename);
2640
2641 my $cluster_conf = {};
2642 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2643 $cluster_conf = parse_cluster_fw_rules($filename, $fh, $verbose);
2644 }
2645
2646 return $cluster_conf;
2647 }
2648
2649 sub save_clusterfw_conf {
2650 my ($cluster_conf) = @_;
2651
2652 my $raw = '';
2653
2654 my $options = $cluster_conf->{options};
2655 $raw .= &$format_options($options) if scalar(keys %$options);
2656
2657 my $aliases = $cluster_conf->{aliases};
2658 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2659
2660 $raw .= &$format_ipsets($cluster_conf);
2661
2662 my $rules = $cluster_conf->{rules};
2663 if (scalar(@$rules)) {
2664 $raw .= "[RULES]\n\n";
2665 $raw .= &$format_rules($rules, 1);
2666 $raw .= "\n";
2667 }
2668
2669 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2670 my $rules = $cluster_conf->{groups}->{$group};
2671 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2672 my $utf8comment = encode('utf8', $comment);
2673 $raw .= "[group $group] # $utf8comment\n\n";
2674 } else {
2675 $raw .= "[group $group]\n\n";
2676 }
2677
2678 $raw .= &$format_rules($rules, 0);
2679 $raw .= "\n";
2680 }
2681
2682 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2683 }
2684
2685 sub load_hostfw_conf {
2686 my ($cluster_conf, $filename, $verbose) = @_;
2687
2688 $filename = $hostfw_conf_filename if !defined($filename);
2689
2690 my $hostfw_conf = {};
2691 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2692 $hostfw_conf = parse_host_fw_rules($filename, $fh, $cluster_conf, $verbose);
2693 }
2694 return $hostfw_conf;
2695 }
2696
2697 sub save_hostfw_conf {
2698 my ($hostfw_conf) = @_;
2699
2700 my $raw = '';
2701
2702 my $options = $hostfw_conf->{options};
2703 $raw .= &$format_options($options) if scalar(keys %$options);
2704
2705 my $rules = $hostfw_conf->{rules};
2706 if (scalar(@$rules)) {
2707 $raw .= "[RULES]\n\n";
2708 $raw .= &$format_rules($rules, 1);
2709 $raw .= "\n";
2710 }
2711
2712 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2713 }
2714
2715 sub compile {
2716 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
2717
2718 my $vmfw_configs;
2719
2720 if ($vmdata) { # test mode
2721 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2722 my $filename = "$testdir/cluster.fw";
2723 $cluster_conf = load_clusterfw_conf($filename, $verbose);
2724
2725 $filename = "$testdir/host.fw";
2726 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
2727
2728 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
2729 } else { # normal operation
2730 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
2731
2732 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
2733
2734 $vmdata = read_local_vm_config();
2735 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
2736 }
2737
2738 $cluster_conf->{ipset}->{venet0} = [];
2739 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0');
2740
2741 my $localnet;
2742 if ($cluster_conf->{aliases}->{local_network}) {
2743 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2744 } else {
2745 $localnet = local_network() || '127.0.0.0/8';
2746 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2747 }
2748
2749 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
2750
2751 my $ruleset = {};
2752
2753 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2754 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2755
2756 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2757
2758 my $hostfw_options = $hostfw_conf->{options} || {};
2759
2760 # fixme: what log level should we use here?
2761 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2762
2763 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2764
2765
2766 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2767 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2768 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2769
2770 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2771 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2772
2773 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2774
2775 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2776 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2777
2778 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2779 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2780
2781 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2782
2783 generate_std_chains($ruleset, $hostfw_options);
2784
2785 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2786
2787 my $ipset_ruleset = {};
2788
2789 if ($hostfw_enable) {
2790 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2791 warn $@ if $@; # just to be sure - should not happen
2792 }
2793
2794 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2795
2796 # generate firewall rules for QEMU VMs
2797 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2798 eval {
2799 my $conf = $vmdata->{qemu}->{$vmid};
2800 my $vmfw_conf = $vmfw_configs->{$vmid};
2801 return if !$vmfw_conf;
2802 return if !$vmfw_conf->{options}->{enable};
2803
2804 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2805
2806 foreach my $netid (keys %$conf) {
2807 next if $netid !~ m/^net(\d+)$/;
2808 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2809 next if !$net->{firewall};
2810 my $iface = "tap${vmid}i$1";
2811
2812 my $macaddr = $net->{macaddr};
2813 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2814 $vmfw_conf, $vmid, 'IN');
2815 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2816 $vmfw_conf, $vmid, 'OUT');
2817 }
2818 };
2819 warn $@ if $@; # just to be sure - should not happen
2820 }
2821
2822 # generate firewall rules for OpenVZ containers
2823 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2824 eval {
2825 my $conf = $vmdata->{openvz}->{$vmid};
2826
2827 my $vmfw_conf = $vmfw_configs->{$vmid};
2828 return if !$vmfw_conf;
2829 return if !$vmfw_conf->{options}->{enable};
2830
2831 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2832
2833 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2834 my $ip = $conf->{ip_address}->{value};
2835 $ip =~ s/\s+/,/g;
2836 parse_address_list($ip); # make sure we have a valid $ip list
2837
2838 my @ips = split(',', $ip);
2839
2840 foreach my $singleip (@ips) {
2841 my $venet0ipset = {};
2842 $venet0ipset->{cidr} = $singleip;
2843 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2844 }
2845
2846 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN');
2847 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT');
2848 }
2849
2850 if ($conf->{netif} && $conf->{netif}->{value}) {
2851 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2852 foreach my $netid (keys %$netif) {
2853 my $d = $netif->{$netid};
2854
2855 my $macaddr = $d->{mac};
2856 my $iface = $d->{host_ifname};
2857 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2858 $vmfw_conf, $vmid, 'IN');
2859 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2860 $vmfw_conf, $vmid, 'OUT');
2861 }
2862 }
2863 };
2864 warn $@ if $@; # just to be sure - should not happen
2865 }
2866
2867 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2868 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2869 }
2870
2871 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
2872
2873 return ($ruleset, $ipset_ruleset);
2874 }
2875
2876 sub get_ruleset_status {
2877 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2878
2879 my $statushash = {};
2880
2881 foreach my $chain (sort keys %$ruleset) {
2882 my $sig = &$digest_fn($ruleset->{$chain});
2883
2884 $statushash->{$chain}->{sig} = $sig;
2885
2886 my $oldsig = $active_chains->{$chain};
2887 if (!defined($oldsig)) {
2888 $statushash->{$chain}->{action} = 'create';
2889 } else {
2890 if ($oldsig eq $sig) {
2891 $statushash->{$chain}->{action} = 'exists';
2892 } else {
2893 $statushash->{$chain}->{action} = 'update';
2894 }
2895 }
2896 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2897 foreach my $cmd (@{$ruleset->{$chain}}) {
2898 print "\t$cmd\n" if $verbose;
2899 }
2900 }
2901
2902 foreach my $chain (sort keys %$active_chains) {
2903 if (!defined($ruleset->{$chain})) {
2904 my $sig = $active_chains->{$chain};
2905 $statushash->{$chain}->{action} = 'delete';
2906 $statushash->{$chain}->{sig} = $sig;
2907 print "delete $chain ($sig)\n" if $verbose;
2908 }
2909 }
2910
2911 return $statushash;
2912 }
2913
2914 sub print_sig_rule {
2915 my ($chain, $sig) = @_;
2916
2917 # We just use this to store a SHA1 checksum used to detect changes
2918 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2919 }
2920
2921 sub get_ruleset_cmdlist {
2922 my ($ruleset, $verbose) = @_;
2923
2924 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2925
2926 my ($active_chains, $hooks) = iptables_get_chains();
2927 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2928
2929 # create missing chains first
2930 foreach my $chain (sort keys %$ruleset) {
2931 my $stat = $statushash->{$chain};
2932 die "internal error" if !$stat;
2933 next if $stat->{action} ne 'create';
2934
2935 $cmdlist .= ":$chain - [0:0]\n";
2936 }
2937
2938 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2939 if (!$hooks->{$h}) {
2940 $cmdlist .= "-A $h -j PVEFW-$h\n";
2941 }
2942 }
2943
2944 foreach my $chain (sort keys %$ruleset) {
2945 my $stat = $statushash->{$chain};
2946 die "internal error" if !$stat;
2947
2948 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
2949 $cmdlist .= "-F $chain\n";
2950 foreach my $cmd (@{$ruleset->{$chain}}) {
2951 $cmdlist .= "$cmd\n";
2952 }
2953 $cmdlist .= print_sig_rule($chain, $stat->{sig});
2954 } elsif ($stat->{action} eq 'delete') {
2955 die "internal error"; # this should not happen
2956 } elsif ($stat->{action} eq 'exists') {
2957 # do nothing
2958 } else {
2959 die "internal error - unknown status '$stat->{action}'";
2960 }
2961 }
2962
2963 foreach my $chain (keys %$statushash) {
2964 next if $statushash->{$chain}->{action} ne 'delete';
2965 $cmdlist .= "-F $chain\n";
2966 }
2967 foreach my $chain (keys %$statushash) {
2968 next if $statushash->{$chain}->{action} ne 'delete';
2969 next if $chain eq 'PVEFW-INPUT';
2970 next if $chain eq 'PVEFW-OUTPUT';
2971 next if $chain eq 'PVEFW-FORWARD';
2972 $cmdlist .= "-X $chain\n";
2973 }
2974
2975 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
2976
2977 $cmdlist .= "COMMIT\n";
2978
2979 return wantarray ? ($cmdlist, $changes) : $cmdlist;
2980 }
2981
2982 sub get_ipset_cmdlist {
2983 my ($ruleset, $verbose) = @_;
2984
2985 my $cmdlist = "";
2986
2987 my $delete_cmdlist = "";
2988
2989 my $active_chains = ipset_get_chains();
2990 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
2991
2992 # remove stale _swap chains
2993 foreach my $chain (keys %$active_chains) {
2994 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2995 $cmdlist .= "destroy $chain\n";
2996 }
2997 }
2998
2999 foreach my $chain (sort keys %$ruleset) {
3000 my $stat = $statushash->{$chain};
3001 die "internal error" if !$stat;
3002
3003 if ($stat->{action} eq 'create') {
3004 foreach my $cmd (@{$ruleset->{$chain}}) {
3005 $cmdlist .= "$cmd\n";
3006 }
3007 }
3008
3009 if ($stat->{action} eq 'update') {
3010 my $chain_swap = $chain."_swap";
3011
3012 foreach my $cmd (@{$ruleset->{$chain}}) {
3013 $cmd =~ s/$chain/$chain_swap/;
3014 $cmdlist .= "$cmd\n";
3015 }
3016 $cmdlist .= "swap $chain_swap $chain\n";
3017 $cmdlist .= "flush $chain_swap\n";
3018 $cmdlist .= "destroy $chain_swap\n";
3019 }
3020
3021 }
3022
3023 foreach my $chain (keys %$statushash) {
3024 next if $statushash->{$chain}->{action} ne 'delete';
3025
3026 $delete_cmdlist .= "flush $chain\n";
3027 $delete_cmdlist .= "destroy $chain\n";
3028 }
3029
3030 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
3031
3032 return ($cmdlist, $delete_cmdlist, $changes);
3033 }
3034
3035 sub apply_ruleset {
3036 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
3037
3038 enable_bridge_firewall();
3039
3040 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3041 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
3042
3043 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
3044
3045 if ($verbose) {
3046 if ($ipset_changes) {
3047 print "ipset changes:\n";
3048 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3049 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3050 }
3051
3052 if ($changes) {
3053 print "iptables changes:\n";
3054 print $cmdlist;
3055 }
3056 }
3057
3058 ipset_restore_cmdlist($ipset_create_cmdlist);
3059
3060 iptables_restore_cmdlist($cmdlist);
3061
3062 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3063
3064 # test: re-read status and check if everything is up to date
3065 my $active_chains = iptables_get_chains();
3066 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3067
3068 my $errors;
3069 foreach my $chain (sort keys %$ruleset) {
3070 my $stat = $statushash->{$chain};
3071 if ($stat->{action} ne 'exists') {
3072 warn "unable to update chain '$chain'\n";
3073 $errors = 1;
3074 }
3075 }
3076
3077 die "unable to apply firewall changes\n" if $errors;
3078
3079 update_nf_conntrack_max($hostfw_conf);
3080
3081 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
3082
3083 }
3084
3085 sub update_nf_conntrack_max {
3086 my ($hostfw_conf) = @_;
3087
3088 my $max = 65536; # reasonable default
3089
3090 my $options = $hostfw_conf->{options} || {};
3091
3092 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3093 $max = $options->{nf_conntrack_max};
3094 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3095 }
3096
3097 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3098 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3099
3100 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3101
3102 if ($current != $max) {
3103 my $hashsize = int($max/4);
3104 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3105 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3106 }
3107 }
3108
3109 sub update_nf_conntrack_tcp_timeout_established {
3110 my ($hostfw_conf) = @_;
3111
3112 my $options = $hostfw_conf->{options} || {};
3113
3114 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3115
3116 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3117 }
3118
3119 sub remove_pvefw_chains {
3120
3121 my ($chash, $hooks) = iptables_get_chains();
3122 my $cmdlist = "*filter\n";
3123
3124 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3125 if ($hooks->{$h}) {
3126 $cmdlist .= "-D $h -j PVEFW-$h\n";
3127 }
3128 }
3129
3130 foreach my $chain (keys %$chash) {
3131 $cmdlist .= "-F $chain\n";
3132 }
3133
3134 foreach my $chain (keys %$chash) {
3135 $cmdlist .= "-X $chain\n";
3136 }
3137 $cmdlist .= "COMMIT\n";
3138
3139 iptables_restore_cmdlist($cmdlist);
3140 }
3141
3142 sub init {
3143 my $cluster_conf = load_clusterfw_conf();
3144 my $cluster_options = $cluster_conf->{options};
3145 my $enable = $cluster_options->{enable};
3146
3147 return if !$enable;
3148
3149 # load required modules here
3150 }
3151
3152 sub update {
3153 my $code = sub {
3154
3155 my $cluster_conf = load_clusterfw_conf();
3156 my $cluster_options = $cluster_conf->{options};
3157
3158 my $enable = $cluster_options->{enable};
3159
3160 die "Firewall is disabled - cannot start\n" if !$enable;
3161
3162 if (!$enable) {
3163 PVE::Firewall::remove_pvefw_chains();
3164 return;
3165 }
3166
3167 my $hostfw_conf = load_hostfw_conf();
3168
3169 my ($ruleset, $ipset_ruleset) = compile($cluster_conf, $hostfw_conf);
3170
3171 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset);
3172 };
3173
3174 run_locked($code);
3175 }
3176
3177 1;