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