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