]> git.proxmox.com Git - pve-firewall.git/blame - src/PVE/Firewall.pm
verify_rule: correctly set ipversion for aliases
[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
eea9d2a1
DM
1220 my $ipversion;
1221 my $set_ip_version = sub {
1222 my $vers = shift;
1223 if ($vers) {
1224 die "detected mixed ipv4/ipv6 adresses in rule\n"
1225 if $ipversion && ($vers != $ipversion);
1226 $ipversion = $vers;
1227 }
1228 };
1229
a523e057 1230 my $check_ipset_or_alias_property = sub {
ae029a88 1231 my ($name, $expected_ipversion) = @_;
a523e057
DM
1232
1233 if (my $value = $rule->{$name}) {
1234 if ($value =~ m/^\+/) {
4dfe04e6 1235 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
bfc488f6 1236 &$add_error($name, "no such ipset '$1'")
a523e057 1237 if !($cluster_conf->{ipset}->{$1} || ($fw_conf && $fw_conf->{ipset}->{$1}));
bfc488f6 1238
a523e057 1239 } else {
351052d1 1240 &$add_error($name, "invalid ipset name '$value'");
a523e057
DM
1241 }
1242 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1243 my $alias = lc($value);
bfc488f6 1244 &$add_error($name, "no such alias '$value'")
70e524eb
AD
1245 if !($cluster_conf->{aliases}->{$alias} || ($fw_conf && $fw_conf->{aliases}->{$alias}));
1246
1247 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
1248 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1249
eea9d2a1 1250 &$set_ip_version($e->{ipversion});
a523e057
DM
1251 }
1252 }
1253 };
1254
6d9246e7
DM
1255 my $type = $rule->{type};
1256 my $action = $rule->{action};
bfc488f6 1257
6d9246e7
DM
1258 &$add_error('type', "missing property") if !$type;
1259 &$add_error('action', "missing property") if !$action;
1260
1261 if ($type) {
1262 if ($type eq 'in' || $type eq 'out') {
1263 &$add_error('action', "unknown action '$action'")
1264 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1265 } elsif ($type eq 'group') {
1266 &$add_error('type', "security groups not allowed")
1267 if !$allow_groups;
1268 &$add_error('action', "invalid characters in security group name")
1269 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1270 } else {
1271 &$add_error('type', "unknown rule type '$type'");
1272 }
7ca36671 1273 }
e34d0e58 1274
dba740a9 1275 if ($rule->{iface}) {
bfc488f6 1276 &$add_error('type', "parameter -i not allowed for this rule type")
b6b8e6ad 1277 if !$allow_iface;
dba740a9 1278 eval { PVE::JSONSchema::pve_verify_iface($rule->{iface}); };
6d9246e7 1279 &$add_error('iface', $@) if $@;
b6b8e6ad
DM
1280 if ($rule_env eq 'vm') {
1281 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1282 if $rule->{iface} !~ m/^net(\d+)$/;
1283 } elsif ($rule_env eq 'ct') {
1284 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1285 if $rule->{iface} !~ m/^(venet|eth(\d+))$/;
1286 }
1287 }
7ca36671
DM
1288
1289 if ($rule->{macro}) {
6d9246e7
DM
1290 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1291 $rule->{macro} = $preferred_name;
1292 } else {
1293 &$add_error('macro', "unknown macro '$rule->{macro}'");
1294 }
1295 }
1296
1297 if ($rule->{proto}) {
1298 eval { pve_fw_verify_protocol_spec($rule->{proto}); };
1299 &$add_error('proto', $@) if $@;
041b9277
DM
1300 &$set_ip_version(4) if $rule->{proto} eq 'icmp';
1301 &$set_ip_version(6) if $rule->{proto} eq 'icmpv6';
6d9246e7 1302 }
7ca36671
DM
1303
1304 if ($rule->{dport}) {
1305 eval { parse_port_name_number_or_range($rule->{dport}); };
6d9246e7
DM
1306 &$add_error('dport', $@) if $@;
1307 &$add_error('proto', "missing property - 'dport' requires this property")
914f9a50 1308 if !$rule->{proto};
6d9246e7 1309 }
7ca36671
DM
1310
1311 if ($rule->{sport}) {
1312 eval { parse_port_name_number_or_range($rule->{sport}); };
6d9246e7
DM
1313 &$add_error('sport', $@) if $@;
1314 &$add_error('proto', "missing property - 'sport' requires this property")
914f9a50 1315 if !$rule->{proto};
7ca36671
DM
1316 }
1317
1318 if ($rule->{source}) {
041b9277
DM
1319 eval {
1320 my $source_ipversion = parse_address_list($rule->{source});
1321 &$set_ip_version($source_ipversion);
1322 };
6d9246e7 1323 &$add_error('source', $@) if $@;
ae029a88 1324 &$check_ipset_or_alias_property('source', $ipversion);
7ca36671
DM
1325 }
1326
1327 if ($rule->{dest}) {
9e2205e5
DM
1328 eval {
1329 my $dest_ipversion = parse_address_list($rule->{dest});
041b9277 1330 &$set_ip_version($dest_ipversion);
9e2205e5 1331 };
6d9246e7 1332 &$add_error('dest', $@) if $@;
ae029a88 1333 &$check_ipset_or_alias_property('dest', $ipversion);
7ca36671
DM
1334 }
1335
a523e057 1336 if ($rule->{macro} && !$error_count) {
6d9246e7
DM
1337 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1338 if (my $err = $@) {
1339 if (ref($err) eq "PVE::Exception" && $err->{errors}) {
1340 my $eh = $err->{errors};
1341 foreach my $p (keys %$eh) {
1342 &$add_error($p, $eh->{$p});
1343 }
1344 } else {
1345 &$add_error('macro', "$err");
1346 }
1347 }
9a2745a0
DM
1348 }
1349
6d9246e7 1350 $rule->{errors} = $errors if $error_count;
7697c041 1351 $rule->{ipversion} = $ipversion if $ipversion;
6d9246e7 1352
7ca36671
DM
1353 return $rule;
1354}
1355
9c7e0858
DM
1356sub copy_rule_data {
1357 my ($rule, $param) = @_;
1358
1359 foreach my $k (keys %$rule_properties) {
1360 if (defined(my $v = $param->{$k})) {
1361 if ($v eq '' || $v eq '-') {
1362 delete $rule->{$k};
1363 } else {
1364 $rule->{$k} = $v;
1365 }
9c7e0858
DM
1366 }
1367 }
7ca36671 1368
9c7e0858
DM
1369 return $rule;
1370}
1371
9f6845cf
DM
1372sub rules_modify_permissions {
1373 my ($rule_env) = @_;
1374
1375 if ($rule_env eq 'host') {
1376 return {
1377 check => ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1378 };
1379 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1380 return {
1381 check => ['perm', '/', [ 'Sys.Modify' ]],
1382 };
1383 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1384 return {
1385 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1386 }
1387 }
1388
1389 return undef;
1390}
1391
1392sub rules_audit_permissions {
1393 my ($rule_env) = @_;
1394
1395 if ($rule_env eq 'host') {
1396 return {
1397 check => ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1398 };
1399 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1400 return {
1401 check => ['perm', '/', [ 'Sys.Audit' ]],
1402 };
1403 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1404 return {
1405 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1406 }
1407 }
1408
1409 return undef;
1410}
1411
9c7e0858 1412# core functions
780bcc0f
DM
1413my $bridge_firewall_enabled = 0;
1414
1415sub enable_bridge_firewall {
1416
1417 return if $bridge_firewall_enabled; # only once
1418
5f0a912c
DM
1419 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1420 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
780bcc0f 1421
6a8a75db
DM
1422 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1423 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
1424
780bcc0f
DM
1425 $bridge_firewall_enabled = 1;
1426}
1427
8cebfa6f 1428my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
dddd9413 1429
b16e818e
DM
1430sub iptables_restore_cmdlist {
1431 my ($cmdlist) = @_;
3a616aa0 1432
59f9b456 1433 run_command("/sbin/iptables-restore -n", input => $cmdlist, errmsg => "iptables_restore_cmdlist");
3a616aa0
AD
1434}
1435
17da5c0f
AD
1436sub ip6tables_restore_cmdlist {
1437 my ($cmdlist) = @_;
1438
59f9b456 1439 run_command("/sbin/ip6tables-restore -n", input => $cmdlist, errmsg => "iptables_restore_cmdlist");
17da5c0f
AD
1440}
1441
34cdedfa
AD
1442sub ipset_restore_cmdlist {
1443 my ($cmdlist) = @_;
1444
59f9b456 1445 run_command("/usr/sbin/ipset restore", input => $cmdlist, errmsg => "ipset_restore_cmdlist");
34cdedfa
AD
1446}
1447
de2a57cd 1448sub iptables_get_chains {
17da5c0f
AD
1449 my ($iptablescmd) = @_;
1450
1451 $iptablescmd = "iptables" if !$iptablescmd;
de2a57cd
DM
1452
1453 my $res = {};
1454
1455 # check what chains we want to track
1456 my $is_pvefw_chain = sub {
1457 my $name = shift;
1458
dec84fcd
DM
1459 return 1 if $name =~ m/^PVEFW-\S+$/;
1460
de2a57cd 1461 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
954f24b1
DM
1462
1463 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1464
9e15114a
DM
1465 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1466
a01c32c7 1467 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
f50656c2 1468 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
de2a57cd
DM
1469
1470 return undef;
1471 };
1472
1473 my $table = '';
1474
c4a2e5ae
DM
1475 my $hooks = {};
1476
de2a57cd
DM
1477 my $parser = sub {
1478 my $line = shift;
1479
1480 return if $line =~ m/^#/;
1481 return if $line =~ m/^\s*$/;
1482
1483 if ($line =~ m/^\*(\S+)$/) {
1484 $table = $1;
1485 return;
1486 }
1487
1488 return if $table ne 'filter';
1489
1490 if ($line =~ m/^:(\S+)\s/) {
1491 my $chain = $1;
1492 return if !&$is_pvefw_chain($chain);
3fa83edf 1493 $res->{$chain} = "unknown";
09d5f68e 1494 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
3fa83edf 1495 my ($chain, $sig) = ($1, $2);
de2a57cd 1496 return if !&$is_pvefw_chain($chain);
3fa83edf 1497 $res->{$chain} = $sig;
c4a2e5ae
DM
1498 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1499 $hooks->{$1} = 1;
de2a57cd
DM
1500 } else {
1501 # simply ignore the rest
1502 return;
1503 }
1504 };
1505
17da5c0f 1506 run_command("/sbin/$iptablescmd-save", outfunc => $parser);
de2a57cd 1507
c4a2e5ae 1508 return wantarray ? ($res, $hooks) : $res;
de2a57cd
DM
1509}
1510
9bf7d929
DM
1511sub iptables_chain_digest {
1512 my ($rules) = @_;
1513 my $digest = Digest::SHA->new('sha1');
1514 foreach my $rule (@$rules) { # order is important
1515 $digest->add($rule);
1516 }
1517 return $digest->b64digest;
1518}
1519
3f95d14a
DM
1520sub ipset_chain_digest {
1521 my ($rules) = @_;
4bd0a9c4 1522
3f95d14a
DM
1523 my $digest = Digest::SHA->new('sha1');
1524 foreach my $rule (sort @$rules) { # note: sorted
1525 $digest->add($rule);
1526 }
1527 return $digest->b64digest;
1528}
1529
34cdedfa
AD
1530sub ipset_get_chains {
1531
1532 my $res = {};
1533 my $chains = {};
1534
1535 my $parser = sub {
1536 my $line = shift;
1537
1538 return if $line =~ m/^#/;
1539 return if $line =~ m/^\s*$/;
4b96e877 1540 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
81a0bf43
DM
1541 my $chain = $1;
1542 $line =~ s/\s+$//; # delete trailing white space
1543 push @{$chains->{$chain}}, $line;
34cdedfa
AD
1544 } else {
1545 # simply ignore the rest
1546 return;
1547 }
1548 };
1549
3f95d14a 1550 run_command("/usr/sbin/ipset save", outfunc => $parser);
34cdedfa 1551
3f95d14a
DM
1552 # compute digest for each chain
1553 foreach my $chain (keys %$chains) {
1554 $res->{$chain} = ipset_chain_digest($chains->{$chain});
34cdedfa
AD
1555 }
1556
1557 return $res;
1558}
1559
eba0fb64 1560sub ruleset_generate_cmdstr {
e523d2bb 1561 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
3a616aa0 1562
00bb4391 1563 return if defined($rule->{enable}) && !$rule->{enable};
6d9246e7 1564 return if $rule->{errors};
11bac5c2 1565
e5076eee
DM
1566 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1567
1568 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
1569 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
e5076eee 1570
41524a58 1571 my @cmd = ();
3a616aa0 1572
eba0fb64
DM
1573 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1574 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1575
ba791b1f
AD
1576 my $source = $rule->{source};
1577 my $dest = $rule->{dest};
1578
cbb5d6f3 1579 if ($source) {
44be8ceb 1580 if ($source =~ m/^\+/) {
4dfe04e6 1581 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
e523d2bb
DM
1582 my $name = $1;
1583 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
708ba714
DM
1584 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name);
1585 push @cmd, "-m set --match-set ${ipset_chain} src";
e523d2bb 1586 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
708ba714
DM
1587 my $ipset_chain = compute_ipset_chain_name(0, $name);
1588 push @cmd, "-m set --match-set ${ipset_chain} src";
e523d2bb
DM
1589 } else {
1590 die "no such ipset '$name'\n";
1591 }
44be8ceb
DM
1592 } else {
1593 die "invalid security group name '$source'\n";
1594 }
1595 } elsif ($source =~ m/^${ip_alias_pattern}$/){
81d574a7 1596 my $alias = lc($source);
bfc488f6 1597 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
e523d2bb
DM
1598 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1599 die "no such alias '$source'\n" if !$e;
81d574a7 1600 push @cmd, "-s $e->{cidr}";
ac8242cc 1601 } elsif ($source =~ m/\-/){
ba791b1f 1602 push @cmd, "-m iprange --src-range $source";
cbb5d6f3 1603 } else {
ba791b1f
AD
1604 push @cmd, "-s $source";
1605 }
1606 }
1607
cbb5d6f3 1608 if ($dest) {
44be8ceb 1609 if ($dest =~ m/^\+/) {
4dfe04e6 1610 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
e523d2bb
DM
1611 my $name = $1;
1612 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
708ba714 1613 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name);
ac4580a0 1614 push @cmd, "-m set --match-set ${ipset_chain} dst";
e523d2bb 1615 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
708ba714
DM
1616 my $ipset_chain = compute_ipset_chain_name(0, $name);
1617 push @cmd, "-m set --match-set ${ipset_chain} dst";
e523d2bb
DM
1618 } else {
1619 die "no such ipset '$name'\n";
1620 }
44be8ceb
DM
1621 } else {
1622 die "invalid security group name '$dest'\n";
1623 }
1624 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
51b40846 1625 my $alias = lc($dest);
bfc488f6 1626 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
e523d2bb
DM
1627 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1628 die "no such alias '$dest'\n" if !$e;
81d574a7 1629 push @cmd, "-d $e->{cidr}";
cbb5d6f3 1630 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
ba791b1f 1631 push @cmd, "-m iprange --dst-range $dest";
cbb5d6f3 1632 } else {
d6d2a385 1633 push @cmd, "-d $dest";
ba791b1f
AD
1634 }
1635 }
4b586518 1636
181390b0 1637 if ($rule->{proto}) {
41524a58 1638 push @cmd, "-p $rule->{proto}";
e3a1d391 1639
181390b0 1640 my $multiport = 0;
e5076eee
DM
1641 $multiport++ if $nbdport > 1;
1642 $multiport++ if $nbsport > 1;
e3a1d391 1643
41524a58 1644 push @cmd, "--match multiport" if $multiport;
4b586518 1645
cbb5d6f3 1646 die "multiport: option '--sports' cannot be used together with '--dports'\n"
181390b0
DM
1647 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1648
1649 if ($rule->{dport}) {
1650 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
1651 # Note: we use dport to store --icmp-type
1652 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
41524a58 1653 push @cmd, "-m icmp --icmp-type $rule->{dport}";
041b9277
DM
1654 } elsif ($rule->{proto} && $rule->{proto} eq 'icmpv6') {
1655 # Note: we use dport to store --icmpv6-type
1656 die "unknown icmpv6-type '$rule->{dport}'\n" if !defined($icmpv6_type_names->{$rule->{dport}});
1657 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
181390b0 1658 } else {
e5076eee 1659 if ($nbdport > 1) {
181390b0 1660 if ($multiport == 2) {
41524a58 1661 push @cmd, "--ports $rule->{dport}";
181390b0 1662 } else {
41524a58 1663 push @cmd, "--dports $rule->{dport}";
181390b0 1664 }
e3a1d391 1665 } else {
41524a58 1666 push @cmd, "--dport $rule->{dport}";
e3a1d391 1667 }
4b586518
DM
1668 }
1669 }
4b586518 1670
181390b0 1671 if ($rule->{sport}) {
e5076eee 1672 if ($nbsport > 1) {
41524a58 1673 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
181390b0 1674 } else {
41524a58 1675 push @cmd, "--sport $rule->{sport}";
181390b0 1676 }
4b586518 1677 }
181390b0 1678 } elsif ($rule->{dport} || $rule->{sport}) {
93d96f83
DM
1679 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1680 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
4b586518
DM
1681 }
1682
41524a58 1683 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
4e6112f9
DM
1684
1685 if (my $action = $rule->{action}) {
cbb5d6f3 1686 $action = $actions->{$action} if defined($actions->{$action});
4e6112f9 1687 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
41524a58 1688 push @cmd, $goto ? "-g $action" : "-j $action";
181390b0 1689 }
3a616aa0 1690
eba0fb64
DM
1691 return scalar(@cmd) ? join(' ', @cmd) : undef;
1692}
1693
1694sub ruleset_generate_rule {
e523d2bb 1695 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
eba0fb64 1696
e5076eee
DM
1697 my $rules;
1698
1699 if ($rule->{macro}) {
1700 $rules = &$apply_macro($rule->{macro}, $rule);
1701 } else {
1702 $rules = [ $rule ];
1703 }
1704
d4091b82
DM
1705 # update all or nothing
1706
1707 my @cmds = ();
cbb5d6f3 1708 foreach my $tmp (@$rules) {
e523d2bb 1709 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
d4091b82 1710 push @cmds, $cmdstr;
e5076eee 1711 }
41524a58 1712 }
d4091b82
DM
1713
1714 foreach my $cmdstr (@cmds) {
1715 ruleset_addrule($ruleset, $chain, $cmdstr);
1716 }
3fa83edf 1717}
0f168d7b 1718
eba0fb64
DM
1719sub ruleset_generate_rule_insert {
1720 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1721
e5076eee
DM
1722 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1723
eba0fb64
DM
1724 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
1725 ruleset_insertrule($ruleset, $chain, $cmdstr);
1726 }
1727}
3fa83edf
DM
1728
1729sub ruleset_create_chain {
1730 my ($ruleset, $chain) = @_;
3a616aa0 1731
d050c724 1732 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
782c4cde 1733 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
d050c724 1734
3fa83edf
DM
1735 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1736
1737 $ruleset->{$chain} = [];
3a616aa0
AD
1738}
1739
3fa83edf
DM
1740sub ruleset_chain_exist {
1741 my ($ruleset, $chain) = @_;
3a616aa0 1742
3fa83edf
DM
1743 return $ruleset->{$chain} ? 1 : undef;
1744}
3a616aa0 1745
3fa83edf
DM
1746sub ruleset_addrule {
1747 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1748
3fa83edf 1749 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1750
3fa83edf
DM
1751 push @{$ruleset->{$chain}}, "-A $chain $rule";
1752}
3a616aa0 1753
3fa83edf
DM
1754sub ruleset_insertrule {
1755 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1756
3fa83edf 1757 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1758
3fa83edf
DM
1759 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1760}
3a616aa0 1761
782c4cde
DM
1762sub get_log_rule_base {
1763 my ($chain, $vmid, $msg, $loglevel) = @_;
cbb5d6f3 1764
782c4cde
DM
1765 die "internal error - no log level" if !defined($loglevel);
1766
1767 $vmid = 0 if !defined($vmid);
1768
cbb5d6f3 1769 # Note: we use special format for prefix to pass further
782c4cde
DM
1770 # info to log daemon (VMID, LOGVELEL and CHAIN)
1771
1772 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1773}
1774
1775sub ruleset_addlog {
1776 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1777
1778 return if !defined($loglevel);
1779
1780 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1781
1782 $logrule = "$rule $logrule" if defined($rule);
1783
88733a74 1784 ruleset_addrule($ruleset, $chain, $logrule);
782c4cde
DM
1785}
1786
ead850e8 1787sub ruleset_add_chain_policy {
782c4cde 1788 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
ead850e8
DM
1789
1790 if ($policy eq 'ACCEPT') {
1791
1792 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1793 { ACCEPT => $accept_action});
1794
1795 } elsif ($policy eq 'DROP') {
1796
1797 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1798
782c4cde 1799 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1800
1801 ruleset_addrule($ruleset, $chain, "-j DROP");
1802 } elsif ($policy eq 'REJECT') {
1803 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1804
782c4cde 1805 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1806
1807 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1808 } else {
1809 # should not happen
1810 die "internal error: unknown policy '$policy'";
1811 }
1812}
1813
e2943485
DM
1814sub ruleset_chain_add_conn_filters {
1815 my ($ruleset, $chain, $accept) = @_;
1816
1817 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1818 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1819}
1820
1821sub ruleset_chain_add_input_filters {
5b5c42b1 1822 my ($ruleset, $chain, $options, $cluster_conf, $ipversion, $loglevel) = @_;
2428e394
AD
1823
1824 if ($cluster_conf->{ipset}->{blacklist}){
b5831a0d
AD
1825 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
1826 ruleset_create_chain($ruleset, "PVEFW-blacklist");
1827 ruleset_addlog($ruleset, "PVEFW-blacklist", 0, "DROP: ", $loglevel) if $loglevel;
1828 ruleset_addrule($ruleset, "PVEFW-blacklist", "-j DROP");
1829 }
708ba714
DM
1830 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1831 ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src -j PVEFW-blacklist");
2428e394 1832 }
e2943485
DM
1833
1834 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
5b5c42b1
DM
1835 if ($ipversion == 4) {
1836 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1837 }
e2943485
DM
1838 }
1839
1840 if ($options->{tcpflags}) {
1841 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1842 }
1843}
1844
9e15114a 1845sub ruleset_create_vm_chain {
808d711d 1846 my ($ruleset, $chain, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
3a616aa0 1847
9e15114a 1848 ruleset_create_chain($ruleset, $chain);
b47ecc88 1849 my $accept = generate_nfqueue($options);
3a616aa0 1850
ce15d90b 1851 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
76a2d1e7 1852 if ($direction eq 'OUT') {
cbb5d6f3 1853 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
0f168d7b 1854 proto => 'udp', sport => 68, dport => 67 });
76a2d1e7 1855 } else {
cbb5d6f3 1856 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
0f168d7b 1857 proto => 'udp', sport => 67, dport => 68 });
76a2d1e7 1858 }
ce15d90b
DM
1859 }
1860
b21aca2c
DM
1861 if ($direction eq 'OUT') {
1862 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
9e15114a 1863 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
b21aca2c 1864 }
808d711d
DM
1865 if ($ipfilter_ipset) {
1866 ruleset_addrule($ruleset, $chain, "-m set ! --match-set $ipfilter_ipset src -j DROP");
1867 }
9e15114a 1868 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
c29f55c9 1869 }
9e15114a
DM
1870}
1871
4bc6b5ac 1872sub ruleset_add_group_rule {
aedde2c2 1873 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
4bc6b5ac
DM
1874
1875 my $group = $rule->{action};
1876 my $group_chain = "GROUP-$group-$direction";
1877 if(!ruleset_chain_exist($ruleset, $group_chain)){
aedde2c2 1878 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
4bc6b5ac 1879 }
bfc488f6 1880
f8b12fff
DM
1881 if ($direction eq 'OUT' && $rule->{iface_out}) {
1882 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain");
1883 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1884 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in} -j $group_chain");
4bc6b5ac
DM
1885 } else {
1886 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1887 }
1888
1889 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $action");
1890}
1891
9e15114a 1892sub ruleset_generate_vm_rules {
84870b1a 1893 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
9e15114a
DM
1894
1895 my $lc_direction = lc($direction);
c29f55c9 1896
6b8ca015
DM
1897 my $in_accept = generate_nfqueue($options);
1898
92e976b3
DM
1899 foreach my $rule (@$rules) {
1900 next if $rule->{iface} && $rule->{iface} ne $netid;
b7ab6989 1901 next if !$rule->{enable} || $rule->{errors};
006490cb 1902 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
84870b1a 1903
92e976b3 1904 if ($rule->{type} eq 'group') {
4bc6b5ac 1905 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
aedde2c2 1906 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
92e976b3
DM
1907 } else {
1908 next if $rule->{type} ne $lc_direction;
921dfb33
DM
1909 eval {
1910 if ($direction eq 'OUT') {
1911 ruleset_generate_rule($ruleset, $chain, $rule,
e34d0e58 1912 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
e523d2bb 1913 undef, $cluster_conf, $vmfw_conf);
921dfb33 1914 } else {
e34d0e58
DM
1915 ruleset_generate_rule($ruleset, $chain, $rule,
1916 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
e523d2bb 1917 undef, $cluster_conf, $vmfw_conf);
921dfb33
DM
1918 }
1919 };
1920 warn $@ if $@;
4e6112f9 1921 }
3a616aa0 1922 }
9e15114a
DM
1923}
1924
b47ecc88
AD
1925sub generate_nfqueue {
1926 my ($options) = @_;
1927
73089769
DM
1928 if ($options->{ips}) {
1929 my $action = "NFQUEUE";
1930 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1931 if (defined($3) && defined($1)) {
b47ecc88 1932 $action .= " --queue-balance $1:$3";
73089769 1933 } elsif (defined($1)) {
b47ecc88
AD
1934 $action .= " --queue-num $1";
1935 }
1936 }
8dc92812 1937 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
73089769
DM
1938 return $action;
1939 } else {
1940 return "ACCEPT";
b47ecc88 1941 }
b47ecc88
AD
1942}
1943
da6fc60b 1944sub ruleset_generate_vm_ipsrules {
a01c32c7 1945 my ($ruleset, $options, $direction, $iface) = @_;
da6fc60b
AD
1946
1947 if ($options->{ips} && $direction eq 'IN') {
1948 my $nfqueue = generate_nfqueue($options);
1949
a01c32c7 1950 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
da6fc60b
AD
1951 ruleset_create_chain($ruleset, "PVEFW-IPS");
1952 }
1953
a01c32c7 1954 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
da6fc60b
AD
1955 }
1956}
1957
9e15114a 1958sub generate_venet_rules_direction {
84870b1a 1959 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction, $ipversion) = @_;
9e15114a 1960
9e15114a
DM
1961 my $lc_direction = lc($direction);
1962
1963 my $rules = $vmfw_conf->{rules};
1964
1965 my $options = $vmfw_conf->{options};
1966 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1967
1968 my $chain = "venet0-$vmid-$direction";
1969
a34cfdd0 1970 ruleset_create_vm_chain($ruleset, $chain, $options, undef, undef, $direction);
9e15114a 1971
84870b1a 1972 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction, undef, $ipversion);
9e15114a
DM
1973
1974 # implement policy
1975 my $policy;
1976
1977 if ($direction eq 'OUT') {
1978 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1979 } else {
1980 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1981 }
1982
b47ecc88
AD
1983 my $accept = generate_nfqueue($options);
1984 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1985 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
9e15114a 1986
eba0fb64 1987 if ($direction eq 'OUT') {
41389aed 1988 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT", {
eba0fb64
DM
1989 action => $chain,
1990 source => $ip,
1991 iface_in => 'venet0'});
1992 } else {
41389aed 1993 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN", {
eba0fb64
DM
1994 action => $chain,
1995 dest => $ip,
1996 iface_out => 'venet0'});
1997 }
9e15114a
DM
1998}
1999
2000sub generate_tap_rules_direction {
84870b1a 2001 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
9e15114a
DM
2002
2003 my $lc_direction = lc($direction);
2004
2005 my $rules = $vmfw_conf->{rules};
2006
2007 my $options = $vmfw_conf->{options};
2008 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
2009
2010 my $tapchain = "$iface-$direction";
2011
b692f42c
DM
2012 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2013 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name)
2014 if $vmfw_conf->{ipset}->{$ipfilter_name};
808d711d 2015
a34cfdd0 2016 # create chain with mac and ip filter
808d711d 2017 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $ipfilter_ipset, $direction);
9e15114a 2018
a34cfdd0 2019 if ($options->{enable}) {
84870b1a 2020 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
3a616aa0 2021
a34cfdd0 2022 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
da6fc60b 2023
a34cfdd0
DM
2024 # implement policy
2025 my $policy;
ccae0b50 2026
a34cfdd0
DM
2027 if ($direction eq 'OUT') {
2028 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2029 } else {
72f63fde 2030 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
a34cfdd0 2031 }
ccae0b50 2032
a34cfdd0
DM
2033 my $accept = generate_nfqueue($options);
2034 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
2035 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
2036 } else {
2037 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : 'ACCEPT';
2038 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, 'ACCEPT', $loglevel, $accept_action);
2039 }
3a616aa0 2040
3fa83edf 2041 # plug the tap chain to bridge chain
3cc81077 2042 if ($direction eq 'IN') {
a01c32c7
DM
2043 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
2044 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
3cc81077 2045 } else {
a01c32c7
DM
2046 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
2047 "-m physdev --physdev-is-bridged --physdev-in $iface -j $tapchain");
3cc81077 2048 }
3a616aa0
AD
2049}
2050
d18c1e2b 2051sub enable_host_firewall {
aedde2c2 2052 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
0bd5f137 2053
92e976b3 2054 my $options = $hostfw_conf->{options};
63324b09 2055 my $cluster_options = $cluster_conf->{options};
92e976b3 2056 my $rules = $hostfw_conf->{rules};
35f0c37e 2057 my $cluster_rules = $cluster_conf->{rules};
178a63be 2058
3fa83edf 2059 # host inbound firewall
dec84fcd
DM
2060 my $chain = "PVEFW-HOST-IN";
2061 ruleset_create_chain($ruleset, $chain);
0bd5f137 2062
178a63be
DM
2063 my $loglevel = get_option_log_level($options, "log_level_in");
2064
e2943485 2065 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
4ac863a6 2066
e2943485 2067 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
5b5c42b1 2068 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $ipversion, $loglevel);
fb424a00 2069
23e888f8
DM
2070 # we use RETURN because we need to check also tap rules
2071 my $accept_action = 'RETURN';
2072
cc8dc02f
DM
2073 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
2074
35f0c37e
DM
2075 # add host rules first, so that cluster wide rules can be overwritten
2076 foreach my $rule (@$rules, @$cluster_rules) {
5383df39 2077 next if !$rule->{enable} || $rule->{errors};
bfc488f6 2078
f8b12fff 2079 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
5383df39 2080
1a9978ed
DM
2081 eval {
2082 if ($rule->{type} eq 'group') {
aedde2c2 2083 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
1a9978ed 2084 } elsif ($rule->{type} eq 'in') {
bfc488f6 2085 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
e523d2bb 2086 undef, $cluster_conf, $hostfw_conf);
1a9978ed
DM
2087 }
2088 };
2089 warn $@ if $@;
f8b12fff 2090 delete $rule->{iface_in};
0bd5f137 2091 }
eb399cef
DM
2092
2093 # allow standard traffic for management ipset (includes cluster network)
708ba714
DM
2094 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management");
2095 my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src";
eb399cef 2096 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006 -j $accept_action"); # PVE API
bfc488f6 2097 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
eb399cef
DM
2098 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
2099 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22 -j $accept_action"); # SSH
bfc488f6 2100
525778d7 2101 my $localnet = local_network();
3bc79f87 2102
eb399cef 2103 # corosync
525778d7 2104 if ($localnet) {
c5191f57 2105 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
525778d7
DM
2106 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule");
2107 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule");
3bc79f87 2108 }
0bd5f137 2109
23e888f8 2110 # implement input policy
63324b09 2111 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
782c4cde 2112 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
0bd5f137 2113
3fa83edf 2114 # host outbound firewall
aadd745e 2115 $chain = "PVEFW-HOST-OUT";
dec84fcd
DM
2116 ruleset_create_chain($ruleset, $chain);
2117
178a63be
DM
2118 $loglevel = get_option_log_level($options, "log_level_out");
2119
dec84fcd 2120 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
e2943485
DM
2121
2122 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2123
23e888f8
DM
2124 # we use RETURN because we may want to check other thigs later
2125 $accept_action = 'RETURN';
2126
cc8dc02f
DM
2127 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
2128
35f0c37e
DM
2129 # add host rules first, so that cluster wide rules can be overwritten
2130 foreach my $rule (@$rules, @$cluster_rules) {
5383df39
DM
2131 next if !$rule->{enable} || $rule->{errors};
2132
f8b12fff 2133 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1a9978ed
DM
2134 eval {
2135 if ($rule->{type} eq 'group') {
aedde2c2 2136 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
1a9978ed 2137 } elsif ($rule->{type} eq 'out') {
bfc488f6 2138 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
e523d2bb 2139 undef, $cluster_conf, $hostfw_conf);
1a9978ed
DM
2140 }
2141 };
2142 warn $@ if $@;
f8b12fff 2143 delete $rule->{iface_out};
0bd5f137
AD
2144 }
2145
3bc79f87 2146 # allow standard traffic on cluster network
525778d7
DM
2147 if ($localnet) {
2148 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006 -j $accept_action"); # PVE API
2149 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22 -j $accept_action"); # SSH
bfc488f6 2150 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
525778d7 2151 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
bfc488f6 2152
c5191f57 2153 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
525778d7 2154 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule");
f573ae2c 2155 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule");
3bc79f87
DM
2156 }
2157
23e888f8 2158 # implement output policy
63324b09 2159 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
782c4cde 2160 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
6158271d 2161
dec84fcd
DM
2162 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
2163 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
9d31b418
AD
2164}
2165
2166sub generate_group_rules {
aedde2c2 2167 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
9d31b418 2168
c6f5cc88 2169 my $rules = $cluster_conf->{groups}->{$group};
6158271d 2170
b4deedab
DM
2171 if (!$rules) {
2172 warn "no such security group '$group'\n";
2173 $rules = []; # create empty chain
2174 }
2175
3fa83edf 2176 my $chain = "GROUP-${group}-IN";
9d31b418 2177
3fa83edf 2178 ruleset_create_chain($ruleset, $chain);
b47ecc88 2179 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 2180
92e976b3
DM
2181 foreach my $rule (@$rules) {
2182 next if $rule->{type} ne 'in';
aedde2c2 2183 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
ba791b1f 2184 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418
AD
2185 }
2186
3fa83edf 2187 $chain = "GROUP-${group}-OUT";
9d31b418 2188
3fa83edf 2189 ruleset_create_chain($ruleset, $chain);
4e6112f9 2190 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 2191
92e976b3
DM
2192 foreach my $rule (@$rules) {
2193 next if $rule->{type} ne 'out';
aedde2c2 2194 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
92e976b3
DM
2195 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2196 # check also other tap rules later
cbb5d6f3 2197 ruleset_generate_rule($ruleset, $chain, $rule,
ba791b1f 2198 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418 2199 }
9d31b418
AD
2200}
2201
51bae274
DM
2202my $MAX_NETS = 32;
2203my $valid_netdev_names = {};
2204for (my $i = 0; $i < $MAX_NETS; $i++) {
2205 $valid_netdev_names->{"net$i"} = 1;
2206}
5e1267a5 2207
51bae274 2208sub parse_fw_rule {
a523e057 2209 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
5e1267a5 2210
d4cda423
DM
2211 my $orig_line = $line;
2212
6d9246e7
DM
2213 my $rule = {};
2214
11bac5c2 2215 # we can add single line comments to the end of the rule
6d9246e7
DM
2216 if ($line =~ s/#\s*(.*?)\s*$//) {
2217 $rule->{comment} = decode('utf8', $1);
2218 }
11bac5c2
DM
2219
2220 # we can disable a rule when prefixed with '|'
ea9e5116 2221
6d9246e7 2222 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
51bae274 2223
dba740a9
DM
2224 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2225 die "unable to parse rule: $line\n";
6d9246e7
DM
2226
2227 $rule->{type} = lc($1);
2228 $rule->{action} = $2;
2229
2230 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2231 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2232 $rule->{macro} = $1;
2233 $rule->{action} = $2;
92e976b3 2234 }
51bae274
DM
2235 }
2236
dba740a9
DM
2237 while (length($line)) {
2238 if ($line =~ s/^-i (\S+)\s*//) {
6d9246e7 2239 $rule->{iface} = $1;
dba740a9
DM
2240 next;
2241 }
51bae274 2242
6d9246e7 2243 last if $rule->{type} eq 'group';
51bae274 2244
dba740a9 2245 if ($line =~ s/^-p (\S+)\s*//) {
6d9246e7 2246 $rule->{proto} = $1;
dba740a9
DM
2247 next;
2248 }
6d9246e7 2249
dba740a9 2250 if ($line =~ s/^-dport (\S+)\s*//) {
6d9246e7 2251 $rule->{dport} = $1;
dba740a9
DM
2252 next;
2253 }
6d9246e7 2254
dba740a9 2255 if ($line =~ s/^-sport (\S+)\s*//) {
6d9246e7 2256 $rule->{sport} = $1;
dba740a9
DM
2257 next;
2258 }
2259 if ($line =~ s/^-source (\S+)\s*//) {
6d9246e7 2260 $rule->{source} = $1;
dba740a9
DM
2261 next;
2262 }
2263 if ($line =~ s/^-dest (\S+)\s*//) {
6d9246e7 2264 $rule->{dest} = $1;
dba740a9
DM
2265 next;
2266 }
51bae274 2267
dba740a9
DM
2268 last;
2269 }
ba791b1f 2270
dba740a9 2271 die "unable to parse rule parameters: $line\n" if length($line);
51bae274 2272
a523e057 2273 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
d4cda423
DM
2274 if ($verbose && $rule->{errors}) {
2275 warn "$prefix - errors in rule parameters: $orig_line\n";
2276 foreach my $p (keys %{$rule->{errors}}) {
2277 warn " $p: $rule->{errors}->{$p}\n";
2278 }
2279 }
6d9246e7
DM
2280
2281 return $rule;
51bae274
DM
2282}
2283
2d404ffc 2284sub parse_vmfw_option {
85c6eaed
DM
2285 my ($line) = @_;
2286
2287 my ($opt, $value);
2288
178a63be
DM
2289 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2290
6bafd113 2291 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
9c6b6efd
DM
2292 $opt = lc($1);
2293 $value = int($2);
178a63be
DM
2294 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2295 $opt = lc($1);
2296 $value = $2 ? lc($3) : '';
72f63fde 2297 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
85c6eaed
DM
2298 $opt = lc($1);
2299 $value = uc($3);
b47ecc88
AD
2300 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2301 $opt = lc($1);
2302 $value = $2;
9c6b6efd 2303 } else {
85c6eaed
DM
2304 die "can't parse option '$line'\n"
2305 }
2306
2307 return ($opt, $value);
2308}
2309
2d404ffc
DM
2310sub parse_hostfw_option {
2311 my ($line) = @_;
2312
2313 my ($opt, $value);
2314
2315 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2316
c50a5a68 2317 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2d404ffc
DM
2318 $opt = lc($1);
2319 $value = int($2);
178a63be 2320 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2d404ffc
DM
2321 $opt = lc($1);
2322 $value = $2 ? lc($3) : '';
28c082a1 2323 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
490cdead
DM
2324 $opt = lc($1);
2325 $value = int($2);
2d404ffc 2326 } else {
2d404ffc
DM
2327 die "can't parse option '$line'\n"
2328 }
2329
2330 return ($opt, $value);
2331}
2332
c6f5cc88
DM
2333sub parse_clusterfw_option {
2334 my ($line) = @_;
2335
2336 my ($opt, $value);
2337
2338 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2339 $opt = lc($1);
2340 $value = int($2);
63324b09
DM
2341 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2342 $opt = lc($1);
2343 $value = uc($3);
c6f5cc88 2344 } else {
c6f5cc88
DM
2345 die "can't parse option '$line'\n"
2346 }
2347
2348 return ($opt, $value);
2349}
2350
6c221576
DM
2351sub resolve_alias {
2352 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2353
6d959e3f
DM
2354 my $alias = lc($cidr);
2355 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2356 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
6c221576 2357
6d959e3f
DM
2358 die "no such alias '$cidr'\n" if !$e;;
2359
2360 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
6c221576
DM
2361}
2362
ae029a88
DM
2363sub parse_ip_or_cidr {
2364 my ($cidr) = @_;
2365
2366 my $ipversion;
2367
2368 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2369 $cidr =~ s|/128$||;
2370 $ipversion = 6;
2371 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2372 $cidr =~ s|/32$||;
2373 $ipversion = 4;
2374 } else {
2375 die "value does not look like a valid IP address or CIDR network\n";
2376 }
2377
2378 return wantarray ? ($cidr, $ipversion) : $cidr;
2379}
2380
e76a9f53 2381sub parse_alias {
92e1209b
AD
2382 my ($line) = @_;
2383
81d574a7
DM
2384 # we can add single line comments to the end of the line
2385 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2386
92e1209b 2387 if ($line =~ m/^(\S+)\s(\S+)$/) {
81d574a7 2388 my ($name, $cidr) = ($1, $2);
ae029a88
DM
2389 my $ipversion;
2390
2391 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2392
81d574a7
DM
2393 my $data = {
2394 name => $name,
2395 cidr => $cidr,
70e524eb 2396 ipversion => $ipversion,
81d574a7
DM
2397 };
2398 $data->{comment} = $comment if $comment;
2399 return $data;
92e1209b
AD
2400 }
2401
81d574a7 2402 return undef;
92e1209b
AD
2403}
2404
e5cd1ee0 2405sub generic_fw_config_parser {
1210ae94 2406 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
5e1267a5 2407
51bae274
DM
2408 my $section;
2409 my $group;
2410
1210ae94 2411 my $res = $empty_conf;
6158271d 2412
51bae274
DM
2413 while (defined(my $line = <$fh>)) {
2414 next if $line =~ m/^#/;
2415 next if $line =~ m/^\s*$/;
2416
c8c534f7
DM
2417 chomp $line;
2418
961b4928
DM
2419 my $linenr = $fh->input_line_number();
2420 my $prefix = "$filename (line $linenr)";
2421
1210ae94 2422 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
c6f5cc88
DM
2423 $section = 'options';
2424 next;
2425 }
2426
1210ae94 2427 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
92e1209b
AD
2428 $section = 'aliases';
2429 next;
2430 }
2431
1210ae94 2432 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
c6f5cc88 2433 $section = 'groups';
92e976b3 2434 $group = lc($1);
0d22acb3 2435 my $comment = $2;
351052d1
DM
2436 eval {
2437 die "security group name too long\n" if length($group) > $max_group_name_length;
2438 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2439 };
2440 if (my $err = $@) {
2441 ($section, $group, $comment) = undef;
2442 warn "$prefix: $err";
2443 next;
2444 }
2445
c85c87f9 2446 $res->{$section}->{$group} = [];
649e4d57
DM
2447 $res->{group_comments}->{$group} = decode('utf8', $comment)
2448 if $comment;
51bae274
DM
2449 next;
2450 }
34cdedfa 2451
1210ae94 2452 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
c6f5cc88
DM
2453 $section = 'rules';
2454 next;
2455 }
cbb5d6f3 2456
1210ae94 2457 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
34cdedfa
AD
2458 $section = 'ipset';
2459 $group = lc($1);
d72c631c 2460 my $comment = $2;
351052d1
DM
2461 eval {
2462 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2463 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2464 };
2465 if (my $err = $@) {
2466 ($section, $group, $comment) = undef;
2467 warn "$prefix: $err";
2468 next;
2469 }
2470
c85c87f9 2471 $res->{$section}->{$group} = [];
e34d0e58 2472 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
649e4d57 2473 if $comment;
34cdedfa
AD
2474 next;
2475 }
2476
c6f5cc88 2477 if (!$section) {
cbb5d6f3 2478 warn "$prefix: skip line - no section\n";
51bae274
DM
2479 next;
2480 }
2481
c6f5cc88
DM
2482 if ($section eq 'options') {
2483 eval {
1210ae94
DM
2484 my ($opt, $value);
2485 if ($rule_env eq 'cluster') {
2486 ($opt, $value) = parse_clusterfw_option($line);
2487 } elsif ($rule_env eq 'host') {
2488 ($opt, $value) = parse_hostfw_option($line);
2489 } else {
2490 ($opt, $value) = parse_vmfw_option($line);
2491 }
c6f5cc88
DM
2492 $res->{options}->{$opt} = $value;
2493 };
2494 warn "$prefix: $@" if $@;
92e1209b
AD
2495 } elsif ($section eq 'aliases') {
2496 eval {
e76a9f53 2497 my $data = parse_alias($line);
81d574a7 2498 $res->{aliases}->{lc($data->{name})} = $data;
92e1209b
AD
2499 };
2500 warn "$prefix: $@" if $@;
c6f5cc88
DM
2501 } elsif ($section eq 'rules') {
2502 my $rule;
1210ae94 2503 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
c6f5cc88
DM
2504 if (my $err = $@) {
2505 warn "$prefix: $err";
2506 next;
2507 }
2508 push @{$res->{$section}}, $rule;
2509 } elsif ($section eq 'groups') {
34cdedfa 2510 my $rule;
1210ae94 2511 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); };
34cdedfa
AD
2512 if (my $err = $@) {
2513 warn "$prefix: $err";
2514 next;
2515 }
3f95d14a 2516 push @{$res->{$section}->{$group}}, $rule;
3f95d14a 2517 } elsif ($section eq 'ipset') {
9d6f90e6
DM
2518 # we can add single line comments to the end of the rule
2519 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2520
30f1b100 2521 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2a052ee3 2522 my $nomatch = $1;
9d6f90e6 2523 my $cidr = $2;
d46b1ef6
DM
2524 my $errors;
2525
2526 if ($nomatch && !$feature_ipset_nomatch) {
2527 $errors->{nomatch} = "nomatch not supported by kernel";
2528 }
2a052ee3 2529
4803b296
DM
2530 eval {
2531 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2532 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2533 } else {
ae029a88 2534 $cidr = parse_ip_or_cidr($cidr);
92e1209b 2535 }
4803b296
DM
2536 };
2537 if (my $err = $@) {
c8c534f7 2538 chomp $err;
d46b1ef6 2539 $errors->{cidr} = $err;
2a052ee3 2540 }
2a052ee3 2541
e34d0e58 2542 my $entry = { cidr => $cidr };
9d6f90e6
DM
2543 $entry->{nomatch} = 1 if $nomatch;
2544 $entry->{comment} = $comment if $comment;
d46b1ef6 2545 $entry->{errors} = $errors if $errors;
e34d0e58 2546
c8c534f7 2547 if ($verbose && $errors) {
9a3061c7 2548 warn "$prefix - errors in ipset '$group': $line\n";
c8c534f7
DM
2549 foreach my $p (keys %{$errors}) {
2550 warn " $p: $errors->{$p}\n";
2551 }
2552 }
2553
9d6f90e6 2554 push @{$res->{$section}->{$group}}, $entry;
1210ae94
DM
2555 } else {
2556 warn "$prefix: skip line - unknown section\n";
2557 next;
51bae274 2558 }
5e1267a5
DM
2559 }
2560
2561 return $res;
2562}
2563
e5cd1ee0 2564sub parse_hostfw_config {
1210ae94
DM
2565 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2566
2567 my $empty_conf = { rules => [], options => {}};
2568
e5cd1ee0 2569 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host');
1210ae94
DM
2570}
2571
e5cd1ee0 2572sub parse_vmfw_config {
1210ae94
DM
2573 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2574
2575 my $empty_conf = {
2576 rules => [],
2577 options => {},
2578 aliases => {},
2579 ipset => {} ,
2580 ipset_comments => {},
2581 };
2582
e5cd1ee0 2583 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
1210ae94
DM
2584}
2585
e5cd1ee0 2586sub parse_clusterfw_config {
1210ae94
DM
2587 my ($filename, $fh, $verbose) = @_;
2588
2589 my $section;
2590 my $group;
2591
2592 my $empty_conf = {
2593 rules => [],
2594 options => {},
2595 aliases => {},
2596 groups => {},
2597 group_comments => {},
2598 ipset => {} ,
2599 ipset_comments => {},
2600 };
2601
e5cd1ee0 2602 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster');
1210ae94
DM
2603}
2604
06320eb0
DM
2605sub run_locked {
2606 my ($code, @param) = @_;
2607
2608 my $timeout = 10;
2609
2610 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2611
2612 die $@ if $@;
2613
2614 return $res;
2615}
2616
5e1267a5
DM
2617sub read_local_vm_config {
2618
2619 my $openvz = {};
5e1267a5
DM
2620 my $qemu = {};
2621
c8301d63 2622 my $vmdata = { openvz => $openvz, qemu => $qemu };
5e1267a5 2623
c8301d63
DM
2624 my $vmlist = PVE::Cluster::get_vmlist();
2625 return $vmdata if !$vmlist || !$vmlist->{ids};
2626 my $ids = $vmlist->{ids};
2627
2628 foreach my $vmid (keys %$ids) {
2629 next if !$vmid; # skip VE0
2630 my $d = $ids->{$vmid};
2631 next if !$d->{node} || $d->{node} ne $nodename;
2632 next if !$d->{type};
2633 if ($d->{type} eq 'openvz') {
d9fee004
DM
2634 if ($have_pve_manager) {
2635 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2636 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2637 $openvz->{$vmid} = $conf;
2638 }
c8301d63
DM
2639 }
2640 } elsif ($d->{type} eq 'qemu') {
d9fee004
DM
2641 if ($have_qemu_server) {
2642 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2643 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2644 $qemu->{$vmid} = $conf;
2645 }
c8301d63 2646 }
5e1267a5
DM
2647 }
2648 }
d9fee004 2649
5e1267a5
DM
2650 return $vmdata;
2651};
2652
e7b35711 2653sub load_vmfw_conf {
a523e057 2654 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
e7b35711
DM
2655
2656 my $vmfw_conf = {};
2657
21053409 2658 $dir = $pvefw_conf_dir if !defined($dir);
8aef5177
DM
2659
2660 my $filename = "$dir/$vmid.fw";
e7b35711 2661 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 2662 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
708ba714 2663 $vmfw_conf->{vmid} = $vmid;
e7b35711
DM
2664 }
2665
2666 return $vmfw_conf;
2667}
2668
464f933e 2669my $format_rules = sub {
dba740a9 2670 my ($rules, $allow_iface) = @_;
464f933e
DM
2671
2672 my $raw = '';
2673
2674 foreach my $rule (@$rules) {
c14dacdf 2675 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
464f933e
DM
2676 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2677 $raw .= uc($rule->{type});
7ca36671
DM
2678 if ($rule->{macro}) {
2679 $raw .= " $rule->{macro}($rule->{action})";
2680 } else {
2681 $raw .= " " . $rule->{action};
2682 }
dba740a9
DM
2683 if ($allow_iface && $rule->{iface}) {
2684 $raw .= " -i $rule->{iface}";
2685 }
c14dacdf
DM
2686
2687 if ($rule->{type} ne 'group') {
dba740a9
DM
2688 $raw .= " -source $rule->{source}" if $rule->{source};
2689 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2690 $raw .= " -p $rule->{proto}" if $rule->{proto};
2691 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2692 $raw .= " -sport $rule->{sport}" if $rule->{sport};
c14dacdf
DM
2693 }
2694
cbb5d6f3 2695 $raw .= " # " . encode('utf8', $rule->{comment})
464f933e
DM
2696 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2697 $raw .= "\n";
2698 } else {
c14dacdf 2699 die "unknown rule type '$rule->{type}'";
464f933e
DM
2700 }
2701 }
2702
2703 return $raw;
2704};
2705
2706my $format_options = sub {
68c90e21
DM
2707 my ($options) = @_;
2708
2709 my $raw = '';
464f933e
DM
2710
2711 $raw .= "[OPTIONS]\n\n";
2712 foreach my $opt (keys %$options) {
2713 $raw .= "$opt: $options->{$opt}\n";
2714 }
2715 $raw .= "\n";
68c90e21
DM
2716
2717 return $raw;
464f933e
DM
2718};
2719
0d5f0a0f
DM
2720my $format_aliases = sub {
2721 my ($aliases) = @_;
2722
2723 my $raw = '';
2724
2725 $raw .= "[ALIASES]\n\n";
2726 foreach my $k (keys %$aliases) {
81d574a7
DM
2727 my $e = $aliases->{$k};
2728 $raw .= "$e->{name} $e->{cidr}";
2729 $raw .= " # " . encode('utf8', $e->{comment})
2730 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2731 $raw .= "\n";
0d5f0a0f
DM
2732 }
2733 $raw .= "\n";
2734
2735 return $raw;
2736};
2737
1210ae94
DM
2738my $format_ipsets = sub {
2739 my ($fw_conf) = @_;
2740
9d6f90e6
DM
2741 my $raw = '';
2742
1210ae94
DM
2743 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2744 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2745 my $utf8comment = encode('utf8', $comment);
2746 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2747 } else {
2748 $raw .= "[IPSET $ipset]\n\n";
2749 }
2750 my $options = $fw_conf->{ipset}->{$ipset};
6e299ae3 2751
1210ae94
DM
2752 my $nethash = {};
2753 foreach my $entry (@$options) {
2754 $nethash->{$entry->{cidr}} = $entry;
2755 }
2756
2757 foreach my $cidr (sort keys %$nethash) {
2758 my $entry = $nethash->{$cidr};
2759 my $line = $entry->{nomatch} ? '!' : '';
2760 $line .= $entry->{cidr};
2761 $line .= " # " . encode('utf8', $entry->{comment})
2762 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2763 $raw .= "$line\n";
2764 }
2765
2766 $raw .= "\n";
9d6f90e6 2767 }
e34d0e58 2768
9d6f90e6
DM
2769 return $raw;
2770};
2771
464f933e
DM
2772sub save_vmfw_conf {
2773 my ($vmid, $vmfw_conf) = @_;
2774
2775 my $raw = '';
2776
2777 my $options = $vmfw_conf->{options};
89ea63c8 2778 $raw .= &$format_options($options) if $options && scalar(keys %$options);
cbb5d6f3 2779
e76a9f53 2780 my $aliases = $vmfw_conf->{aliases};
89ea63c8 2781 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
e76a9f53 2782
89ea63c8 2783 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
1210ae94 2784
8824b2f0 2785 my $rules = $vmfw_conf->{rules} || [];
89ea63c8 2786 if ($rules && scalar(@$rules)) {
464f933e
DM
2787 $raw .= "[RULES]\n\n";
2788 $raw .= &$format_rules($rules, 1);
2789 $raw .= "\n";
2790 }
2791
21053409
DM
2792 mkdir $pvefw_conf_dir;
2793
2794 my $filename = "$pvefw_conf_dir/$vmid.fw";
464f933e
DM
2795 PVE::Tools::file_set_contents($filename, $raw);
2796}
2797
6fc63ffd 2798sub read_vm_firewall_configs {
a523e057 2799 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
8aef5177 2800
6fc63ffd 2801 my $vmfw_configs = {};
c8301d63 2802
b6b8e6ad 2803 foreach my $vmid (keys %{$vmdata->{qemu}}) {
a523e057 2804 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose);
b6b8e6ad
DM
2805 next if !$vmfw_conf->{options}; # skip if file does not exists
2806 $vmfw_configs->{$vmid} = $vmfw_conf;
2807 }
2808 foreach my $vmid (keys %{$vmdata->{openvz}}) {
a523e057 2809 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose);
e7b35711
DM
2810 next if !$vmfw_conf->{options}; # skip if file does not exists
2811 $vmfw_configs->{$vmid} = $vmfw_conf;
5e1267a5
DM
2812 }
2813
6fc63ffd 2814 return $vmfw_configs;
5e1267a5
DM
2815}
2816
2d404ffc
DM
2817sub get_option_log_level {
2818 my ($options, $k) = @_;
2819
2820 my $v = $options->{$k};
178a63be 2821 $v = $default_log_level if !defined($v);
2d404ffc
DM
2822
2823 return undef if $v eq '' || $v eq 'nolog';
2824
2825 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2826
2827 return $v if ($v >= 0) && ($v <= 7);
2828
2829 warn "unknown log level ($k = '$v')\n";
2830
2831 return undef;
2832}
2833
d8f2505e 2834sub generate_std_chains {
db8a955f
DM
2835 my ($ruleset, $options, $ipversion) = @_;
2836
2837 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
cbb5d6f3 2838
2d404ffc
DM
2839 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2840
db8a955f 2841 my $chain;
782c4cde 2842
db8a955f
DM
2843 if ($ipversion == 4) {
2844 # same as shorewall smurflog.
2845 $chain = 'PVEFW-smurflog';
2846 $std_chains->{$chain} = [];
2847
2848 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2849 push @{$std_chains->{$chain}}, "-j DROP";
2850 }
2d404ffc
DM
2851
2852 # same as shorewall logflags action.
2853 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
782c4cde 2854 $chain = 'PVEFW-logflags';
db8a955f 2855 $std_chains->{$chain} = [];
12f3796e 2856
782c4cde 2857 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
db8a955f
DM
2858 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2859 push @{$std_chains->{$chain}}, "-j DROP";
d8f2505e 2860
db8a955f 2861 foreach my $chain (keys %$std_chains) {
d8f2505e 2862 ruleset_create_chain($ruleset, $chain);
db8a955f 2863 foreach my $rule (@{$std_chains->{$chain}}) {
d8f2505e
DM
2864 if (ref($rule)) {
2865 ruleset_generate_rule($ruleset, $chain, $rule);
2866 } else {
2867 ruleset_addrule($ruleset, $chain, $rule);
2868 }
2869 }
2870 }
2871}
2872
34cdedfa 2873sub generate_ipset_chains {
708ba714 2874 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
34cdedfa 2875
dd7a13fd 2876 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
708ba714
DM
2877 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2878 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
34cdedfa
AD
2879 }
2880}
2881
2882sub generate_ipset {
708ba714
DM
2883 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2884
2885 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
34cdedfa 2886
6d959e3f 2887 $ipset_ruleset->{$name} = ["create $name list:set size 4"];
34cdedfa 2888
30f1b100
DM
2889 # remove duplicates
2890 my $nethash = {};
9d6f90e6 2891 foreach my $entry (@$options) {
c8c534f7 2892 next if $entry->{errors}; # skip entries with errors
6c221576 2893 eval {
6d959e3f
DM
2894 my ($cidr, $ipversion);
2895 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2896 ($cidr, $ipversion) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2897 } else {
2898 ($cidr, $ipversion) = parse_ip_or_cidr($entry->{cidr});
2899 }
2900 #http://backreference.org/2013/03/01/ipv6-address-normalization/
2901 if ($ipversion == 6) {
2902 my $ipv6 = inet_pton(AF_INET6, lc($cidr));
2903 $cidr = inet_ntop(AF_INET6, $ipv6);
2904 $cidr =~ s|/128$||;
2905 } else {
2906 $cidr =~ s|/32$||;
2907 }
2908
2909 $nethash->{$ipversion}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
6c221576
DM
2910 };
2911 warn $@ if $@;
30f1b100
DM
2912 }
2913
6d959e3f
DM
2914 foreach my $ipversion (sort keys %$nethash) {
2915 my $data = $nethash->{$ipversion};
2916 my $subname = "$name-v$ipversion";
2917
2918 my $hashsize = scalar(@$options);
2919 if ($hashsize <= 64) {
2920 $hashsize = 64;
2921 } else {
2922 $hashsize = round_powerof2($hashsize);
2923 }
2924
2925 my $family = $ipversion == "6" ? "inet6" : "inet";
30f1b100 2926
6d959e3f
DM
2927 $ipset_ruleset->{$subname} = ["create $subname hash:net family $family hashsize $hashsize maxelem $hashsize"];
2928
2929 foreach my $cidr (sort keys %$data) {
2930 my $entry = $data->{$cidr};
2931
2932 my $cmd = "add $subname $cidr";
2933 if ($entry->{nomatch}) {
2934 if ($feature_ipset_nomatch) {
2935 push @{$ipset_ruleset->{$subname}}, "$cmd nomatch";
2936 } else {
2937 warn "ignore !$cidr - nomatch not supported by kernel\n";
2938 }
9d6f90e6 2939 } else {
6d959e3f 2940 push @{$ipset_ruleset->{$subname}}, $cmd;
9d6f90e6 2941 }
9d6f90e6 2942 }
6d959e3f
DM
2943
2944 push @{$ipset_ruleset->{$name}}, "add $name $subname";
34cdedfa 2945 }
2a052ee3
AD
2946}
2947
2948sub round_powerof2 {
dd7a13fd 2949 my ($int) = @_;
2a052ee3 2950
dd7a13fd
DM
2951 $int--;
2952 $int |= $int >> $_ foreach (1,2,4,8,16);
2953 return ++$int;
34cdedfa
AD
2954}
2955
fca39c2c 2956sub load_clusterfw_conf {
d4cda423 2957 my ($filename, $verbose) = @_;
8aef5177
DM
2958
2959 $filename = $clusterfw_conf_filename if !defined($filename);
530c005e 2960
fca39c2c 2961 my $cluster_conf = {};
8aef5177 2962 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 2963 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
51bae274 2964 }
5e1267a5 2965
fca39c2c 2966 return $cluster_conf;
e5d76bde
DM
2967}
2968
fca39c2c
DM
2969sub save_clusterfw_conf {
2970 my ($cluster_conf) = @_;
9c7e0858
DM
2971
2972 my $raw = '';
9c7e0858 2973
c6f5cc88 2974 my $options = $cluster_conf->{options};
89ea63c8 2975 $raw .= &$format_options($options) if $options && scalar(keys %$options);
9c7e0858 2976
0d5f0a0f 2977 my $aliases = $cluster_conf->{aliases};
89ea63c8 2978 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
e34d0e58 2979
89ea63c8 2980 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
1210ae94 2981
c6f5cc88 2982 my $rules = $cluster_conf->{rules};
89ea63c8 2983 if ($rules && scalar(@$rules)) {
c6f5cc88 2984 $raw .= "[RULES]\n\n";
63c91681 2985 $raw .= &$format_rules($rules, 1);
c6f5cc88
DM
2986 $raw .= "\n";
2987 }
2988
89ea63c8
DM
2989 if ($cluster_conf->{groups}) {
2990 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2991 my $rules = $cluster_conf->{groups}->{$group};
2992 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2993 my $utf8comment = encode('utf8', $comment);
2994 $raw .= "[group $group] # $utf8comment\n\n";
2995 } else {
2996 $raw .= "[group $group]\n\n";
2997 }
0d22acb3 2998
89ea63c8
DM
2999 $raw .= &$format_rules($rules, 0);
3000 $raw .= "\n";
3001 }
9c7e0858
DM
3002 }
3003
21053409 3004 mkdir $pvefw_conf_dir;
fca39c2c 3005 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
9c7e0858
DM
3006}
3007
8b27beb9 3008sub load_hostfw_conf {
a523e057 3009 my ($cluster_conf, $filename, $verbose) = @_;
8aef5177
DM
3010
3011 $filename = $hostfw_conf_filename if !defined($filename);
8b27beb9
DM
3012
3013 my $hostfw_conf = {};
8aef5177 3014 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 3015 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
8b27beb9
DM
3016 }
3017 return $hostfw_conf;
3018}
3019
63c91681
DM
3020sub save_hostfw_conf {
3021 my ($hostfw_conf) = @_;
3022
3023 my $raw = '';
3024
3025 my $options = $hostfw_conf->{options};
89ea63c8 3026 $raw .= &$format_options($options) if $options && scalar(keys %$options);
cbb5d6f3 3027
63c91681 3028 my $rules = $hostfw_conf->{rules};
89ea63c8 3029 if ($rules && scalar(@$rules)) {
63c91681
DM
3030 $raw .= "[RULES]\n\n";
3031 $raw .= &$format_rules($rules, 1);
3032 $raw .= "\n";
3033 }
3034
3035 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3036}
3037
e5d76bde 3038sub compile {
d4cda423 3039 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3dfa8a7f 3040
8aef5177
DM
3041 my $vmfw_configs;
3042
3043 if ($vmdata) { # test mode
3044 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3045 my $filename = "$testdir/cluster.fw";
d4cda423 3046 $cluster_conf = load_clusterfw_conf($filename, $verbose);
8aef5177
DM
3047
3048 $filename = "$testdir/host.fw";
a523e057 3049 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
8aef5177 3050
a523e057 3051 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
8aef5177 3052 } else { # normal operation
d4cda423 3053 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
8aef5177 3054
a523e057 3055 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
8aef5177
DM
3056
3057 $vmdata = read_local_vm_config();
a523e057 3058 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
8aef5177 3059 }
3dfa8a7f 3060
9268573a 3061 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
638c755a
AD
3062 my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3063
3064 return ($ruleset, $ipset_ruleset, $rulesetv6);
9268573a
AD
3065}
3066
3067sub compile_iptables_filter {
3068 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3069
27083984 3070 $cluster_conf->{ipset}->{venet0} = [];
708ba714 3071 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0');
bfc488f6 3072
525778d7
DM
3073 my $localnet;
3074 if ($cluster_conf->{aliases}->{local_network}) {
3075 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3076 } else {
3077 $localnet = local_network() || '127.0.0.0/8';
3078 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
3079 }
3080
3081 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
bfc488f6 3082
085fd492
DM
3083 return ({}, {}) if !$cluster_conf->{options}->{enable};
3084
3fa83edf
DM
3085 my $ruleset = {};
3086
dec84fcd
DM
3087 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3088 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
5b1df9a0 3089
fadb13dd 3090 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
e34d0e58 3091
8b27beb9 3092 my $hostfw_options = $hostfw_conf->{options} || {};
fadb13dd 3093
88733a74
AD
3094 # fixme: what log level should we use here?
3095 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3096
097820b0 3097 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
88733a74 3098
708ba714 3099
e2943485 3100 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
708ba714
DM
3101 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3102 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
e2943485
DM
3103
3104 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
5b5c42b1 3105 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $ipversion, $loglevel);
e2943485 3106
d1b41c08 3107 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
e2943485
DM
3108
3109 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
d1b41c08 3110 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
e2943485
DM
3111
3112 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
5b5c42b1 3113 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $ipversion, $loglevel);
e2943485 3114
708ba714 3115 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
e2943485 3116
db8a955f 3117 generate_std_chains($ruleset, $hostfw_options, $ipversion);
fadb13dd 3118
6d2ab017 3119 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2d404ffc 3120
708ba714
DM
3121 my $ipset_ruleset = {};
3122
b546f500
DM
3123 # currently pveproxy don't works with ipv6, so let's generate host fw ipv4 only for the moment
3124 if ($hostfw_enable && ($ipversion == 4)) {
aedde2c2 3125 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
1a9978ed
DM
3126 warn $@ if $@; # just to be sure - should not happen
3127 }
3fa83edf 3128
708ba714 3129 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
62689a1e 3130
6158271d 3131 # generate firewall rules for QEMU VMs
3fa83edf 3132 foreach my $vmid (keys %{$vmdata->{qemu}}) {
1a9978ed
DM
3133 eval {
3134 my $conf = $vmdata->{qemu}->{$vmid};
3135 my $vmfw_conf = $vmfw_configs->{$vmid};
3136 return if !$vmfw_conf;
1a9978ed 3137
708ba714
DM
3138 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3139
1a9978ed
DM
3140 foreach my $netid (keys %$conf) {
3141 next if $netid !~ m/^net(\d+)$/;
3142 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3143 next if !$net->{firewall};
3144 my $iface = "tap${vmid}i$1";
3145
3146 my $macaddr = $net->{macaddr};
3147 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
84870b1a 3148 $vmfw_conf, $vmid, 'IN', $ipversion);
1a9978ed 3149 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
84870b1a 3150 $vmfw_conf, $vmid, 'OUT', $ipversion);
1a9978ed
DM
3151 }
3152 };
3153 warn $@ if $@; # just to be sure - should not happen
3fa83edf 3154 }
c8301d63
DM
3155
3156 # generate firewall rules for OpenVZ containers
3157 foreach my $vmid (keys %{$vmdata->{openvz}}) {
1a9978ed
DM
3158 eval {
3159 my $conf = $vmdata->{openvz}->{$vmid};
c8301d63 3160
1a9978ed
DM
3161 my $vmfw_conf = $vmfw_configs->{$vmid};
3162 return if !$vmfw_conf;
c8301d63 3163
708ba714
DM
3164 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3165
a34cfdd0
DM
3166 if ($vmfw_conf->{options}->{enable}) {
3167 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
3168 my $ip = $conf->{ip_address}->{value};
3169 $ip =~ s/\s+/,/g;
27083984 3170
b33ce1b5 3171 my @ips = ();
27083984 3172
b33ce1b5
DM
3173 foreach my $singleip (split(',', $ip)) {
3174 my $singleip_ver = parse_address_list($singleip); # make sure we have a valid $ip list
3175 push @{$cluster_conf->{ipset}->{venet0}}, { cidr => $singleip };
3176 push @ips, $singleip if $singleip_ver == $ipversion;
a34cfdd0 3177 }
c8301d63 3178
b33ce1b5
DM
3179 if (scalar(@ips)) {
3180 my $ip_list = join(',', @ips);
3181 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'IN', $ipversion);
3182 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'OUT', $ipversion);
3183 }
a34cfdd0 3184 }
1a9978ed 3185 }
530c005e 3186
1a9978ed
DM
3187 if ($conf->{netif} && $conf->{netif}->{value}) {
3188 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
3189 foreach my $netid (keys %$netif) {
3190 my $d = $netif->{$netid};
a34cfdd0
DM
3191 my $bridge = $d->{bridge};
3192 next if !$bridge || $bridge !~ m/^vmbr\d+(v(\d+))?f$/; # firewall enabled ?
1a9978ed
DM
3193 my $macaddr = $d->{mac};
3194 my $iface = $d->{host_ifname};
3195 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
84870b1a 3196 $vmfw_conf, $vmid, 'IN', $ipversion);
1a9978ed 3197 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
84870b1a 3198 $vmfw_conf, $vmid, 'OUT', $ipversion);
1a9978ed 3199 }
c8301d63 3200 }
1a9978ed
DM
3201 };
3202 warn $@ if $@; # just to be sure - should not happen
c8301d63 3203 }
c0413e35 3204
097820b0
AD
3205 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3206 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3207 }
3208
708ba714 3209 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
27083984 3210
3dfa8a7f 3211 return ($ruleset, $ipset_ruleset);
3fa83edf
DM
3212}
3213
3214sub get_ruleset_status {
4bd0a9c4 3215 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3fa83edf
DM
3216
3217 my $statushash = {};
3218
3219 foreach my $chain (sort keys %$ruleset) {
4bd0a9c4 3220 my $sig = &$digest_fn($ruleset->{$chain});
9bf7d929 3221
3fa83edf
DM
3222 $statushash->{$chain}->{sig} = $sig;
3223
3224 my $oldsig = $active_chains->{$chain};
3225 if (!defined($oldsig)) {
3226 $statushash->{$chain}->{action} = 'create';
3227 } else {
3228 if ($oldsig eq $sig) {
3229 $statushash->{$chain}->{action} = 'exists';
3230 } else {
3231 $statushash->{$chain}->{action} = 'update';
3232 }
3233 }
3234 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3235 foreach my $cmd (@{$ruleset->{$chain}}) {
3236 print "\t$cmd\n" if $verbose;
3237 }
3238 }
3239
3240 foreach my $chain (sort keys %$active_chains) {
3241 if (!defined($ruleset->{$chain})) {
3242 my $sig = $active_chains->{$chain};
3243 $statushash->{$chain}->{action} = 'delete';
3244 $statushash->{$chain}->{sig} = $sig;
3245 print "delete $chain ($sig)\n" if $verbose;
3246 }
6158271d 3247 }
2a052ee3 3248
3fa83edf
DM
3249 return $statushash;
3250}
3251
3fa83edf
DM
3252sub print_sig_rule {
3253 my ($chain, $sig) = @_;
3254
09d5f68e
DM
3255 # We just use this to store a SHA1 checksum used to detect changes
3256 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
b6360c3f
DM
3257}
3258
df7cb349 3259sub get_ruleset_cmdlist {
17da5c0f 3260 my ($ruleset, $verbose, $iptablescmd) = @_;
3fa83edf 3261
3fa83edf 3262 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
cbb5d6f3 3263
17da5c0f 3264 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
4bd0a9c4 3265 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3fa83edf
DM
3266
3267 # create missing chains first
3268 foreach my $chain (sort keys %$ruleset) {
3269 my $stat = $statushash->{$chain};
3270 die "internal error" if !$stat;
3271 next if $stat->{action} ne 'create';
886aba9c 3272
3fa83edf
DM
3273 $cmdlist .= ":$chain - [0:0]\n";
3274 }
3275
4bd0a9c4 3276 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
55fad3b7
DM
3277 my $chain = "PVEFW-$h";
3278 if ($ruleset->{$chain} && !$hooks->{$h}) {
3279 $cmdlist .= "-A $h -j $chain\n";
4bd0a9c4 3280 }
3fa83edf
DM
3281 }
3282
3283 foreach my $chain (sort keys %$ruleset) {
3284 my $stat = $statushash->{$chain};
3285 die "internal error" if !$stat;
3286
3287 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
3288 $cmdlist .= "-F $chain\n";
3289 foreach my $cmd (@{$ruleset->{$chain}}) {
3290 $cmdlist .= "$cmd\n";
3291 }
3292 $cmdlist .= print_sig_rule($chain, $stat->{sig});
3293 } elsif ($stat->{action} eq 'delete') {
f5d28682 3294 die "internal error"; # this should not happen
3fa83edf
DM
3295 } elsif ($stat->{action} eq 'exists') {
3296 # do nothing
3297 } else {
3298 die "internal error - unknown status '$stat->{action}'";
3299 }
3300 }
3301
f5d28682
DM
3302 foreach my $chain (keys %$statushash) {
3303 next if $statushash->{$chain}->{action} ne 'delete';
3304 $cmdlist .= "-F $chain\n";
3305 }
3306 foreach my $chain (keys %$statushash) {
3307 next if $statushash->{$chain}->{action} ne 'delete';
fadb13dd
DM
3308 next if $chain eq 'PVEFW-INPUT';
3309 next if $chain eq 'PVEFW-OUTPUT';
3310 next if $chain eq 'PVEFW-FORWARD';
f5d28682
DM
3311 $cmdlist .= "-X $chain\n";
3312 }
3313
3f95d14a 3314 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
4bd0a9c4 3315
3fa83edf
DM
3316 $cmdlist .= "COMMIT\n";
3317
3f95d14a 3318 return wantarray ? ($cmdlist, $changes) : $cmdlist;
6b9f68a2
DM
3319}
3320
34cdedfa 3321sub get_ipset_cmdlist {
dd7a13fd 3322 my ($ruleset, $verbose) = @_;
34cdedfa
AD
3323
3324 my $cmdlist = "";
3325
dd7a13fd
DM
3326 my $delete_cmdlist = "";
3327
4bd0a9c4
DM
3328 my $active_chains = ipset_get_chains();
3329 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
34cdedfa 3330
e34d0e58 3331 # remove stale _swap chains
30f1b100
DM
3332 foreach my $chain (keys %$active_chains) {
3333 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3334 $cmdlist .= "destroy $chain\n";
3335 }
3336 }
3337
c69cf614
DM
3338 # create -v4 and -v6 chains first
3339 foreach my $chain (keys %$ruleset) {
3340 next if $chain !~ m/-v[46]$/;
dd7a13fd
DM
3341 my $stat = $statushash->{$chain};
3342 die "internal error" if !$stat;
2a052ee3 3343
dd7a13fd
DM
3344 if ($stat->{action} eq 'create') {
3345 foreach my $cmd (@{$ruleset->{$chain}}) {
34cdedfa
AD
3346 $cmdlist .= "$cmd\n";
3347 }
dd7a13fd 3348 }
6d959e3f
DM
3349 }
3350
c69cf614
DM
3351 # then create list chains which use above -v4 and -v6 chains
3352 foreach my $chain (keys %$ruleset) {
3353 next if $chain =~ m/-v[46]$/;
3354 my $stat = $statushash->{$chain};
3355 die "internal error" if !$stat;
3356
3357 if ($stat->{action} eq 'create') {
3358 foreach my $cmd (@{$ruleset->{$chain}}) {
3359 $cmdlist .= "$cmd\n";
3360 }
3361 }
3362 }
3363
3364 foreach my $chain (keys %$ruleset) {
6d959e3f
DM
3365 my $stat = $statushash->{$chain};
3366 die "internal error" if !$stat;
34cdedfa 3367
dd7a13fd
DM
3368 if ($stat->{action} eq 'update') {
3369 my $chain_swap = $chain."_swap";
cbb5d6f3 3370
dd7a13fd
DM
3371 foreach my $cmd (@{$ruleset->{$chain}}) {
3372 $cmd =~ s/$chain/$chain_swap/;
3373 $cmdlist .= "$cmd\n";
34cdedfa 3374 }
dd7a13fd
DM
3375 $cmdlist .= "swap $chain_swap $chain\n";
3376 $cmdlist .= "flush $chain_swap\n";
3377 $cmdlist .= "destroy $chain_swap\n";
2a052ee3 3378 }
dd7a13fd 3379 }
3f95d14a 3380
c69cf614
DM
3381 # remove unused list chains first
3382 foreach my $chain (keys %$statushash) {
3383 next if $statushash->{$chain}->{action} ne 'delete';
3384 next if $chain !~ m/-v[46]$/;
3385
3386 $delete_cmdlist .= "flush $chain\n";
3387 $delete_cmdlist .= "destroy $chain\n";
3388 }
3389
3390 # the remove unused -v4 -v6 chains
3391 foreach my $chain (keys %$statushash) {
dd7a13fd 3392 next if $statushash->{$chain}->{action} ne 'delete';
c69cf614 3393 next if $chain =~ m/-v[46]$/;
2a052ee3 3394
dd7a13fd
DM
3395 $delete_cmdlist .= "flush $chain\n";
3396 $delete_cmdlist .= "destroy $chain\n";
34cdedfa
AD
3397 }
3398
dd7a13fd 3399 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
cbb5d6f3 3400
dd7a13fd 3401 return ($cmdlist, $delete_cmdlist, $changes);
34cdedfa
AD
3402}
3403
6b9f68a2 3404sub apply_ruleset {
17da5c0f 3405 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
6b9f68a2
DM
3406
3407 enable_bridge_firewall();
3408
cbb5d6f3 3409 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
81a0bf43 3410 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
6b9f68a2 3411
81a0bf43 3412 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
17da5c0f 3413 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
2a052ee3 3414
81a0bf43
DM
3415 if ($verbose) {
3416 if ($ipset_changes) {
3417 print "ipset changes:\n";
3418 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3419 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3420 }
3f95d14a 3421
81a0bf43
DM
3422 if ($changes) {
3423 print "iptables changes:\n";
3424 print $cmdlist;
3425 }
17da5c0f
AD
3426
3427 if ($changesv6) {
3428 print "ip6tables changes:\n";
3429 print $cmdlistv6;
3430 }
81a0bf43 3431 }
3fa83edf 3432
259db1e6
DM
3433 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3434 PVE::Tools::file_set_contents($tmpfile, $ipset_create_cmdlist || '');
3435
2a052ee3 3436 ipset_restore_cmdlist($ipset_create_cmdlist);
34cdedfa 3437
259db1e6
DM
3438 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3439 PVE::Tools::file_set_contents($tmpfile, $cmdlist || '');
3440
3fa83edf 3441 iptables_restore_cmdlist($cmdlist);
259db1e6
DM
3442
3443 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3444 PVE::Tools::file_set_contents($tmpfile, $cmdlistv6 || '');
3445
17da5c0f 3446 ip6tables_restore_cmdlist($cmdlistv6);
3fa83edf 3447
259db1e6
DM
3448 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3449 PVE::Tools::file_set_contents($tmpfile, $ipset_delete_cmdlist || '');
3450
dd7a13fd 3451 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2a052ee3 3452
6158271d 3453 # test: re-read status and check if everything is up to date
4bd0a9c4 3454 my $active_chains = iptables_get_chains();
81a0bf43 3455 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3fa83edf
DM
3456
3457 my $errors;
3458 foreach my $chain (sort keys %$ruleset) {
3459 my $stat = $statushash->{$chain};
3460 if ($stat->{action} ne 'exists') {
3461 warn "unable to update chain '$chain'\n";
3462 $errors = 1;
3463 }
3464 }
b6360c3f 3465
17da5c0f
AD
3466 my $active_chainsv6 = iptables_get_chains("ip6tables");
3467 my $statushashv6 = get_ruleset_status($rulesetv6, $active_chainsv6, \&iptables_chain_digest, 0);
3468
3469 foreach my $chain (sort keys %$rulesetv6) {
3470 my $stat = $statushashv6->{$chain};
3471 if ($stat->{action} ne 'exists') {
3472 warn "unable to update chain '$chain'\n";
3473 $errors = 1;
3474 }
3475 }
3476
3fa83edf 3477 die "unable to apply firewall changes\n" if $errors;
46a2ac1f
AD
3478
3479 update_nf_conntrack_max($hostfw_conf);
3480
3481 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
3482
b6360c3f
DM
3483}
3484
490cdead
DM
3485sub update_nf_conntrack_max {
3486 my ($hostfw_conf) = @_;
3487
3488 my $max = 65536; # reasonable default
3489
3490 my $options = $hostfw_conf->{options} || {};
3491
3492 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3493 $max = $options->{nf_conntrack_max};
3494 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3495 }
3496
3497 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3498 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3499
3500 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3501
3502 if ($current != $max) {
3503 my $hashsize = int($max/4);
3504 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3505 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3506 }
3507}
3508
28c082a1
AD
3509sub update_nf_conntrack_tcp_timeout_established {
3510 my ($hostfw_conf) = @_;
3511
3512 my $options = $hostfw_conf->{options} || {};
3513
3514 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3515
3516 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3517}
3518
c4a2e5ae
DM
3519sub remove_pvefw_chains {
3520
7b7b2654
AD
3521 PVE::Firewall::remove_pvefw_chains_iptables("iptables");
3522 PVE::Firewall::remove_pvefw_chains_iptables("ip6tables");
3523 PVE::Firewall::remove_pvefw_chains_ipset();
3524
3525}
3526
3527sub remove_pvefw_chains_iptables {
3528 my ($iptablescmd) = @_;
3529
3530 my ($chash, $hooks) = iptables_get_chains($iptablescmd);
c4a2e5ae
DM
3531 my $cmdlist = "*filter\n";
3532
3533 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3534 if ($hooks->{$h}) {
3535 $cmdlist .= "-D $h -j PVEFW-$h\n";
3536 }
3537 }
cbb5d6f3 3538
c4a2e5ae
DM
3539 foreach my $chain (keys %$chash) {
3540 $cmdlist .= "-F $chain\n";
3541 }
3542
3543 foreach my $chain (keys %$chash) {
3544 $cmdlist .= "-X $chain\n";
3545 }
3546 $cmdlist .= "COMMIT\n";
3547
7b7b2654
AD
3548 if($iptablescmd eq "ip6tables") {
3549 ip6tables_restore_cmdlist($cmdlist);
3550 } else {
3551 iptables_restore_cmdlist($cmdlist);
3552 }
3553}
3554
3555sub remove_pvefw_chains_ipset {
55fad3b7
DM
3556
3557 my $ipset_chains = ipset_get_chains();
3558
7b7b2654
AD
3559 my $sub_cmdlist = "";
3560 my $cmdlist = "";
55fad3b7
DM
3561
3562 foreach my $chain (keys %$ipset_chains) {
7b7b2654
AD
3563 if ($chain =~ m/^PVEFW-\S+\-(v4|v6)$/) {
3564 $sub_cmdlist .= "flush $chain\n";
3565 $sub_cmdlist .= "destroy $chain\n";
3566 }else{
3567 $cmdlist .= "flush $chain\n";
3568 $cmdlist .= "destroy $chain\n";
3569 }
55fad3b7
DM
3570 }
3571
7b7b2654
AD
3572 $cmdlist .= $sub_cmdlist;
3573
3574 ipset_restore_cmdlist($cmdlist) if $cmdlist;
c4a2e5ae
DM
3575}
3576
8b453a09
DM
3577sub init {
3578 my $cluster_conf = load_clusterfw_conf();
3579 my $cluster_options = $cluster_conf->{options};
3580 my $enable = $cluster_options->{enable};
3581
3582 return if !$enable;
3583
3584 # load required modules here
3585}
3586
6b9f68a2 3587sub update {
6b9f68a2 3588 my $code = sub {
3dfa8a7f
DM
3589
3590 my $cluster_conf = load_clusterfw_conf();
3591 my $cluster_options = $cluster_conf->{options};
3592
55fad3b7 3593 if (!$cluster_options->{enable}) {
b22130d3 3594 PVE::Firewall::remove_pvefw_chains();
3dfa8a7f
DM
3595 return;
3596 }
3597
3598 my $hostfw_conf = load_hostfw_conf();
3599
638c755a 3600 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile($cluster_conf, $hostfw_conf);
490cdead 3601
17da5c0f 3602 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);
6b9f68a2
DM
3603 };
3604
3605 run_locked($code);
3606}
3607
b6360c3f 36081;