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