]> git.proxmox.com Git - pve-firewall.git/blame - src/PVE/Firewall.pm
bump version to 1.0-7
[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
b692f42c
DM
780sub compute_ipfilter_ipset_name {
781 my ($iface) = @_;
782
783 return "ipfilter-$iface";
784}
785
ecbea048
DM
786sub parse_address_list {
787 my ($str) = @_;
788
e2c62733
DM
789 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
790 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
791 return;
792 }
793
794 if ($str =~ m/^${ip_alias_pattern}$/) {
795 die "alias name too long\n" if length($str) > $max_alias_name_length;
796 return;
797 }
d72beb8e 798
3162af6b
DM
799 my $count = 0;
800 my $iprange = 0;
801 foreach my $elem (split(/,/, $str)) {
802 $count++;
803 if (!Net::IP->new($elem)) {
ecbea048
DM
804 my $err = Net::IP::Error();
805 die "invalid IP address: $err\n";
806 }
3162af6b 807 $iprange = 1 if $elem =~ m/-/;
ecbea048 808 }
e34d0e58 809
3162af6b 810 die "you can use a range in a list\n" if $iprange && $count > 1;
ecbea048 811}
dddd9413 812
fcba0beb
DM
813sub parse_port_name_number_or_range {
814 my ($str) = @_;
815
816 my $services = PVE::Firewall::get_etc_services();
7ca36671 817 my $count = 0;
041b7e8e
DM
818 my $icmp_port = 0;
819
fcba0beb 820 foreach my $item (split(/,/, $str)) {
7ca36671
DM
821 $count++;
822 if ($item =~ m/^(\d+):(\d+)$/) {
823 my ($port1, $port2) = ($1, $2);
824 die "invalid port '$port1'\n" if $port1 > 65535;
825 die "invalid port '$port2'\n" if $port2 > 65535;
826 } elsif ($item =~ m/^(\d+)$/) {
827 my $port = $1;
828 die "invalid port '$port'\n" if $port > 65535;
829 } else {
041b7e8e
DM
830 if ($icmp_type_names->{$item}) {
831 $icmp_port = 1;
832 } else {
e34d0e58 833 die "invalid port '$item'\n" if !$services->{byname}->{$item};
041b7e8e 834 }
fcba0beb
DM
835 }
836 }
837
041b7e8e
DM
838 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
839
7ca36671 840 return $count;
fcba0beb
DM
841}
842
54cd19a8
DM
843PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
844sub pve_fw_verify_port_spec {
845 my ($portstr) = @_;
846
7ca36671 847 parse_port_name_number_or_range($portstr);
54cd19a8
DM
848
849 return $portstr;
850}
851
852PVE::JSONSchema::register_format('pve-fw-v4addr-spec', \&pve_fw_verify_v4addr_spec);
853sub pve_fw_verify_v4addr_spec {
854 my ($list) = @_;
855
856 parse_address_list($list);
857
858 return $list;
859}
860
861PVE::JSONSchema::register_format('pve-fw-protocol-spec', \&pve_fw_verify_protocol_spec);
862sub pve_fw_verify_protocol_spec {
863 my ($proto) = @_;
864
865 my $protocols = get_etc_protocols();
866
867 die "unknown protocol '$proto'\n" if $proto &&
868 !(defined($protocols->{byname}->{$proto}) ||
869 defined($protocols->{byid}->{$proto}));
870
871 return $proto;
872}
873
874
d1c53b3e 875# helper function for API
d1c53b3e 876
5d38d64f
DM
877sub copy_opject_with_digest {
878 my ($object) = @_;
879
880 my $sha = Digest::SHA->new('sha1');
881
882 my $res = {};
883 foreach my $k (sort keys %$object) {
884 my $v = $object->{$k};
0365eb68 885 next if !defined($v);
5d38d64f
DM
886 $res->{$k} = $v;
887 $sha->add($k, ':', $v, "\n");
888 }
889
55e686c7 890 my $digest = $sha->hexdigest;
5d38d64f
DM
891
892 $res->{digest} = $digest;
893
894 return wantarray ? ($res, $digest) : $res;
895}
896
897sub copy_list_with_digest {
898 my ($list) = @_;
899
900 my $sha = Digest::SHA->new('sha1');
901
902 my $res = [];
903 foreach my $entry (@$list) {
904 my $data = {};
905 foreach my $k (sort keys %$entry) {
906 my $v = $entry->{$k};
0365eb68 907 next if !defined($v);
5d38d64f 908 $data->{$k} = $v;
6d9246e7
DM
909 # Note: digest ignores refs ($rule->{errors})
910 $sha->add($k, ':', $v, "\n") if !ref($v); ;
5d38d64f
DM
911 }
912 push @$res, $data;
913 }
914
55e686c7 915 my $digest = $sha->hexdigest;
5d38d64f
DM
916
917 foreach my $entry (@$res) {
918 $entry->{digest} = $digest;
919 }
920
921 return wantarray ? ($res, $digest) : $res;
922}
923
9c7e0858
DM
924my $rule_properties = {
925 pos => {
926 description => "Update rule at position <pos>.",
927 type => 'integer',
928 minimum => 0,
929 optional => 1,
930 },
c71e785f 931 digest => get_standard_option('pve-config-digest'),
9c7e0858
DM
932 type => {
933 type => 'string',
934 optional => 1,
935 enum => ['in', 'out', 'group'],
936 },
937 action => {
c14dacdf 938 description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
9c7e0858
DM
939 type => 'string',
940 optional => 1,
44be8ceb 941 pattern => $security_group_name_pattern,
c14dacdf
DM
942 maxLength => 20,
943 minLength => 2,
9c7e0858 944 },
e5076eee
DM
945 macro => {
946 type => 'string',
947 optional => 1,
54cd19a8 948 maxLength => 128,
e5076eee 949 },
54cd19a8 950 iface => get_standard_option('pve-iface', { optional => 1 }),
9c7e0858 951 source => {
54cd19a8 952 type => 'string', format => 'pve-fw-v4addr-spec',
9c7e0858
DM
953 optional => 1,
954 },
955 dest => {
54cd19a8 956 type => 'string', format => 'pve-fw-v4addr-spec',
9c7e0858
DM
957 optional => 1,
958 },
959 proto => {
54cd19a8 960 type => 'string', format => 'pve-fw-protocol-spec',
9c7e0858
DM
961 optional => 1,
962 },
963 enable => {
964 type => 'boolean',
965 optional => 1,
966 },
967 sport => {
54cd19a8 968 type => 'string', format => 'pve-fw-port-spec',
9c7e0858
DM
969 optional => 1,
970 },
971 dport => {
54cd19a8 972 type => 'string', format => 'pve-fw-port-spec',
9c7e0858
DM
973 optional => 1,
974 },
975 comment => {
976 type => 'string',
977 optional => 1,
978 },
979};
980
981sub add_rule_properties {
982 my ($properties) = @_;
983
984 foreach my $k (keys %$rule_properties) {
3655b01f
DM
985 my $h = $rule_properties->{$k};
986 # copy data, so that we can modify later without side effects
987 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
9c7e0858 988 }
cbb5d6f3 989
9c7e0858
DM
990 return $properties;
991}
992
5b7974df
DM
993sub delete_rule_properties {
994 my ($rule, $delete_str) = @_;
e34d0e58 995
5b7974df
DM
996 foreach my $opt (PVE::Tools::split_list($delete_str)) {
997 raise_param_exc({ 'delete' => "no such property ('$opt')"})
998 if !defined($rule_properties->{$opt});
999 raise_param_exc({ 'delete' => "unable to delete required property '$opt'"})
1000 if $opt eq 'type' || $opt eq 'action';
1001 delete $rule->{$opt};
1002 }
1003
1004 return $rule;
1005}
1006
9a2745a0
DM
1007my $apply_macro = sub {
1008 my ($macro_name, $param, $verify) = @_;
1009
1010 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1011 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1012
1013 my $rules = [];
1014
1015 foreach my $templ (@$macro_rules) {
1016 my $rule = {};
1017 my $param_used = {};
1018 foreach my $k (keys %$templ) {
1019 my $v = $templ->{$k};
1020 if ($v eq 'PARAM') {
1021 $v = $param->{$k};
1022 $param_used->{$k} = 1;
1023 } elsif ($v eq 'DEST') {
1024 $v = $param->{dest};
1025 $param_used->{dest} = 1;
1026 } elsif ($v eq 'SOURCE') {
1027 $v = $param->{source};
1028 $param_used->{source} = 1;
1029 }
1030
1031 if (!defined($v)) {
1032 my $msg = "missing parameter '$k' in macro '$macro_name'";
e34d0e58 1033 raise_param_exc({ macro => $msg }) if $verify;
9a2745a0
DM
1034 die "$msg\n";
1035 }
1036 $rule->{$k} = $v;
1037 }
1038 foreach my $k (keys %$param) {
1039 next if $k eq 'macro';
1040 next if !defined($param->{$k});
1041 next if $param_used->{$k};
1042 if (defined($rule->{$k})) {
1043 if ($rule->{$k} ne $param->{$k}) {
1044 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
e34d0e58 1045 raise_param_exc({ $k => $msg }) if $verify;
9a2745a0
DM
1046 die "$msg\n";
1047 }
1048 } else {
1049 $rule->{$k} = $param->{$k};
1050 }
1051 }
1052 push @$rules, $rule;
1053 }
1054
1055 return $rules;
1056};
1057
b6b8e6ad
DM
1058my $rule_env_iface_lookup = {
1059 'ct' => 1,
1060 'vm' => 1,
1061 'group' => 0,
1062 'cluster' => 1,
1063 'host' => 1,
1064};
1065
7ca36671 1066sub verify_rule {
a523e057 1067 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
b6b8e6ad
DM
1068
1069 my $allow_groups = $rule_env eq 'group' ? 0 : 1;
bfc488f6 1070
b6b8e6ad
DM
1071 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1072 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
7ca36671 1073
a523e057
DM
1074 my $errors = $rule->{errors} || {};
1075
6d9246e7 1076 my $error_count = 0;
7ca36671 1077
6d9246e7
DM
1078 my $add_error = sub {
1079 my ($param, $msg) = @_;
d4cda423 1080 chomp $msg;
6d9246e7
DM
1081 raise_param_exc({ $param => $msg }) if !$noerr;
1082 $error_count++;
1083 $errors->{$param} = $msg if !$errors->{$param};
1084 };
1085
a523e057
DM
1086 my $check_ipset_or_alias_property = sub {
1087 my ($name) = @_;
1088
1089 if (my $value = $rule->{$name}) {
1090 if ($value =~ m/^\+/) {
4dfe04e6 1091 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
bfc488f6 1092 &$add_error($name, "no such ipset '$1'")
a523e057 1093 if !($cluster_conf->{ipset}->{$1} || ($fw_conf && $fw_conf->{ipset}->{$1}));
bfc488f6 1094
a523e057 1095 } else {
351052d1 1096 &$add_error($name, "invalid ipset name '$value'");
a523e057
DM
1097 }
1098 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1099 my $alias = lc($value);
bfc488f6 1100 &$add_error($name, "no such alias '$value'")
a523e057
DM
1101 if !($cluster_conf->{aliases}->{$alias} || ($fw_conf && $fw_conf->{aliases}->{$alias}))
1102 }
1103 }
1104 };
1105
6d9246e7
DM
1106 my $type = $rule->{type};
1107 my $action = $rule->{action};
bfc488f6 1108
6d9246e7
DM
1109 &$add_error('type', "missing property") if !$type;
1110 &$add_error('action', "missing property") if !$action;
1111
1112 if ($type) {
1113 if ($type eq 'in' || $type eq 'out') {
1114 &$add_error('action', "unknown action '$action'")
1115 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1116 } elsif ($type eq 'group') {
1117 &$add_error('type', "security groups not allowed")
1118 if !$allow_groups;
1119 &$add_error('action', "invalid characters in security group name")
1120 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1121 } else {
1122 &$add_error('type', "unknown rule type '$type'");
1123 }
7ca36671 1124 }
e34d0e58 1125
dba740a9 1126 if ($rule->{iface}) {
bfc488f6 1127 &$add_error('type', "parameter -i not allowed for this rule type")
b6b8e6ad 1128 if !$allow_iface;
dba740a9 1129 eval { PVE::JSONSchema::pve_verify_iface($rule->{iface}); };
6d9246e7 1130 &$add_error('iface', $@) if $@;
b6b8e6ad
DM
1131 if ($rule_env eq 'vm') {
1132 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1133 if $rule->{iface} !~ m/^net(\d+)$/;
1134 } elsif ($rule_env eq 'ct') {
1135 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1136 if $rule->{iface} !~ m/^(venet|eth(\d+))$/;
1137 }
1138 }
7ca36671
DM
1139
1140 if ($rule->{macro}) {
6d9246e7
DM
1141 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1142 $rule->{macro} = $preferred_name;
1143 } else {
1144 &$add_error('macro', "unknown macro '$rule->{macro}'");
1145 }
1146 }
1147
1148 if ($rule->{proto}) {
1149 eval { pve_fw_verify_protocol_spec($rule->{proto}); };
1150 &$add_error('proto', $@) if $@;
1151 }
7ca36671
DM
1152
1153 if ($rule->{dport}) {
1154 eval { parse_port_name_number_or_range($rule->{dport}); };
6d9246e7
DM
1155 &$add_error('dport', $@) if $@;
1156 &$add_error('proto', "missing property - 'dport' requires this property")
914f9a50 1157 if !$rule->{proto};
6d9246e7 1158 }
7ca36671
DM
1159
1160 if ($rule->{sport}) {
1161 eval { parse_port_name_number_or_range($rule->{sport}); };
6d9246e7
DM
1162 &$add_error('sport', $@) if $@;
1163 &$add_error('proto', "missing property - 'sport' requires this property")
914f9a50 1164 if !$rule->{proto};
7ca36671
DM
1165 }
1166
1167 if ($rule->{source}) {
1168 eval { parse_address_list($rule->{source}); };
6d9246e7 1169 &$add_error('source', $@) if $@;
a523e057 1170 &$check_ipset_or_alias_property('source');
7ca36671
DM
1171 }
1172
1173 if ($rule->{dest}) {
1174 eval { parse_address_list($rule->{dest}); };
6d9246e7 1175 &$add_error('dest', $@) if $@;
a523e057 1176 &$check_ipset_or_alias_property('dest');
7ca36671
DM
1177 }
1178
a523e057 1179 if ($rule->{macro} && !$error_count) {
6d9246e7
DM
1180 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1181 if (my $err = $@) {
1182 if (ref($err) eq "PVE::Exception" && $err->{errors}) {
1183 my $eh = $err->{errors};
1184 foreach my $p (keys %$eh) {
1185 &$add_error($p, $eh->{$p});
1186 }
1187 } else {
1188 &$add_error('macro', "$err");
1189 }
1190 }
9a2745a0
DM
1191 }
1192
6d9246e7
DM
1193 $rule->{errors} = $errors if $error_count;
1194
7ca36671
DM
1195 return $rule;
1196}
1197
9c7e0858
DM
1198sub copy_rule_data {
1199 my ($rule, $param) = @_;
1200
1201 foreach my $k (keys %$rule_properties) {
1202 if (defined(my $v = $param->{$k})) {
1203 if ($v eq '' || $v eq '-') {
1204 delete $rule->{$k};
1205 } else {
1206 $rule->{$k} = $v;
1207 }
9c7e0858
DM
1208 }
1209 }
7ca36671 1210
9c7e0858
DM
1211 return $rule;
1212}
1213
1214# core functions
780bcc0f
DM
1215my $bridge_firewall_enabled = 0;
1216
1217sub enable_bridge_firewall {
1218
1219 return if $bridge_firewall_enabled; # only once
1220
5f0a912c
DM
1221 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1222 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
780bcc0f 1223
6a8a75db
DM
1224 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1225 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
1226
780bcc0f
DM
1227 $bridge_firewall_enabled = 1;
1228}
1229
8cebfa6f 1230my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
dddd9413 1231
b16e818e
DM
1232sub iptables_restore_cmdlist {
1233 my ($cmdlist) = @_;
3a616aa0 1234
3fa83edf 1235 run_command("/sbin/iptables-restore -n", input => $cmdlist);
3a616aa0
AD
1236}
1237
34cdedfa
AD
1238sub ipset_restore_cmdlist {
1239 my ($cmdlist) = @_;
1240
dd7a13fd 1241 run_command("/usr/sbin/ipset restore", input => $cmdlist);
34cdedfa
AD
1242}
1243
de2a57cd
DM
1244sub iptables_get_chains {
1245
1246 my $res = {};
1247
1248 # check what chains we want to track
1249 my $is_pvefw_chain = sub {
1250 my $name = shift;
1251
dec84fcd
DM
1252 return 1 if $name =~ m/^PVEFW-\S+$/;
1253
de2a57cd 1254 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
954f24b1
DM
1255
1256 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1257
9e15114a
DM
1258 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1259
a01c32c7 1260 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
f50656c2 1261 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
de2a57cd
DM
1262
1263 return undef;
1264 };
1265
1266 my $table = '';
1267
c4a2e5ae
DM
1268 my $hooks = {};
1269
de2a57cd
DM
1270 my $parser = sub {
1271 my $line = shift;
1272
1273 return if $line =~ m/^#/;
1274 return if $line =~ m/^\s*$/;
1275
1276 if ($line =~ m/^\*(\S+)$/) {
1277 $table = $1;
1278 return;
1279 }
1280
1281 return if $table ne 'filter';
1282
1283 if ($line =~ m/^:(\S+)\s/) {
1284 my $chain = $1;
1285 return if !&$is_pvefw_chain($chain);
3fa83edf 1286 $res->{$chain} = "unknown";
09d5f68e 1287 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
3fa83edf 1288 my ($chain, $sig) = ($1, $2);
de2a57cd 1289 return if !&$is_pvefw_chain($chain);
3fa83edf 1290 $res->{$chain} = $sig;
c4a2e5ae
DM
1291 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1292 $hooks->{$1} = 1;
de2a57cd
DM
1293 } else {
1294 # simply ignore the rest
1295 return;
1296 }
1297 };
1298
1299 run_command("/sbin/iptables-save", outfunc => $parser);
1300
c4a2e5ae 1301 return wantarray ? ($res, $hooks) : $res;
de2a57cd
DM
1302}
1303
9bf7d929
DM
1304sub iptables_chain_digest {
1305 my ($rules) = @_;
1306 my $digest = Digest::SHA->new('sha1');
1307 foreach my $rule (@$rules) { # order is important
1308 $digest->add($rule);
1309 }
1310 return $digest->b64digest;
1311}
1312
3f95d14a
DM
1313sub ipset_chain_digest {
1314 my ($rules) = @_;
4bd0a9c4 1315
3f95d14a
DM
1316 my $digest = Digest::SHA->new('sha1');
1317 foreach my $rule (sort @$rules) { # note: sorted
1318 $digest->add($rule);
1319 }
1320 return $digest->b64digest;
1321}
1322
34cdedfa
AD
1323sub ipset_get_chains {
1324
1325 my $res = {};
1326 my $chains = {};
1327
1328 my $parser = sub {
1329 my $line = shift;
1330
1331 return if $line =~ m/^#/;
1332 return if $line =~ m/^\s*$/;
4b96e877 1333 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
81a0bf43
DM
1334 my $chain = $1;
1335 $line =~ s/\s+$//; # delete trailing white space
1336 push @{$chains->{$chain}}, $line;
34cdedfa
AD
1337 } else {
1338 # simply ignore the rest
1339 return;
1340 }
1341 };
1342
3f95d14a 1343 run_command("/usr/sbin/ipset save", outfunc => $parser);
34cdedfa 1344
3f95d14a
DM
1345 # compute digest for each chain
1346 foreach my $chain (keys %$chains) {
1347 $res->{$chain} = ipset_chain_digest($chains->{$chain});
34cdedfa
AD
1348 }
1349
1350 return $res;
1351}
1352
eba0fb64 1353sub ruleset_generate_cmdstr {
e523d2bb 1354 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
3a616aa0 1355
00bb4391 1356 return if defined($rule->{enable}) && !$rule->{enable};
6d9246e7 1357 return if $rule->{errors};
11bac5c2 1358
e5076eee
DM
1359 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1360
1361 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
1362 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
e5076eee 1363
41524a58 1364 my @cmd = ();
3a616aa0 1365
eba0fb64
DM
1366 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1367 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1368
ba791b1f
AD
1369 my $source = $rule->{source};
1370 my $dest = $rule->{dest};
1371
cbb5d6f3 1372 if ($source) {
44be8ceb 1373 if ($source =~ m/^\+/) {
4dfe04e6 1374 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
e523d2bb
DM
1375 my $name = $1;
1376 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
708ba714
DM
1377 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name);
1378 push @cmd, "-m set --match-set ${ipset_chain} src";
e523d2bb 1379 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
708ba714
DM
1380 my $ipset_chain = compute_ipset_chain_name(0, $name);
1381 push @cmd, "-m set --match-set ${ipset_chain} src";
e523d2bb
DM
1382 } else {
1383 die "no such ipset '$name'\n";
1384 }
44be8ceb
DM
1385 } else {
1386 die "invalid security group name '$source'\n";
1387 }
1388 } elsif ($source =~ m/^${ip_alias_pattern}$/){
81d574a7 1389 my $alias = lc($source);
bfc488f6 1390 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
e523d2bb
DM
1391 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1392 die "no such alias '$source'\n" if !$e;
81d574a7 1393 push @cmd, "-s $e->{cidr}";
ac8242cc 1394 } elsif ($source =~ m/\-/){
ba791b1f 1395 push @cmd, "-m iprange --src-range $source";
cbb5d6f3 1396 } else {
ba791b1f
AD
1397 push @cmd, "-s $source";
1398 }
1399 }
1400
cbb5d6f3 1401 if ($dest) {
44be8ceb 1402 if ($dest =~ m/^\+/) {
4dfe04e6 1403 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
e523d2bb
DM
1404 my $name = $1;
1405 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
708ba714 1406 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name);
ac4580a0 1407 push @cmd, "-m set --match-set ${ipset_chain} dst";
e523d2bb 1408 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
708ba714
DM
1409 my $ipset_chain = compute_ipset_chain_name(0, $name);
1410 push @cmd, "-m set --match-set ${ipset_chain} dst";
e523d2bb
DM
1411 } else {
1412 die "no such ipset '$name'\n";
1413 }
44be8ceb
DM
1414 } else {
1415 die "invalid security group name '$dest'\n";
1416 }
1417 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
51b40846 1418 my $alias = lc($dest);
bfc488f6 1419 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
e523d2bb
DM
1420 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1421 die "no such alias '$dest'\n" if !$e;
81d574a7 1422 push @cmd, "-d $e->{cidr}";
cbb5d6f3 1423 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
ba791b1f 1424 push @cmd, "-m iprange --dst-range $dest";
cbb5d6f3 1425 } else {
d6d2a385 1426 push @cmd, "-d $dest";
ba791b1f
AD
1427 }
1428 }
4b586518 1429
181390b0 1430 if ($rule->{proto}) {
41524a58 1431 push @cmd, "-p $rule->{proto}";
e3a1d391 1432
181390b0 1433 my $multiport = 0;
e5076eee
DM
1434 $multiport++ if $nbdport > 1;
1435 $multiport++ if $nbsport > 1;
e3a1d391 1436
41524a58 1437 push @cmd, "--match multiport" if $multiport;
4b586518 1438
cbb5d6f3 1439 die "multiport: option '--sports' cannot be used together with '--dports'\n"
181390b0
DM
1440 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1441
1442 if ($rule->{dport}) {
1443 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
1444 # Note: we use dport to store --icmp-type
1445 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
41524a58 1446 push @cmd, "-m icmp --icmp-type $rule->{dport}";
181390b0 1447 } else {
e5076eee 1448 if ($nbdport > 1) {
181390b0 1449 if ($multiport == 2) {
41524a58 1450 push @cmd, "--ports $rule->{dport}";
181390b0 1451 } else {
41524a58 1452 push @cmd, "--dports $rule->{dport}";
181390b0 1453 }
e3a1d391 1454 } else {
41524a58 1455 push @cmd, "--dport $rule->{dport}";
e3a1d391 1456 }
4b586518
DM
1457 }
1458 }
4b586518 1459
181390b0 1460 if ($rule->{sport}) {
e5076eee 1461 if ($nbsport > 1) {
41524a58 1462 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
181390b0 1463 } else {
41524a58 1464 push @cmd, "--sport $rule->{sport}";
181390b0 1465 }
4b586518 1466 }
181390b0 1467 } elsif ($rule->{dport} || $rule->{sport}) {
93d96f83
DM
1468 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1469 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
4b586518
DM
1470 }
1471
41524a58 1472 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
4e6112f9
DM
1473
1474 if (my $action = $rule->{action}) {
cbb5d6f3 1475 $action = $actions->{$action} if defined($actions->{$action});
4e6112f9 1476 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
41524a58 1477 push @cmd, $goto ? "-g $action" : "-j $action";
181390b0 1478 }
3a616aa0 1479
eba0fb64
DM
1480 return scalar(@cmd) ? join(' ', @cmd) : undef;
1481}
1482
1483sub ruleset_generate_rule {
e523d2bb 1484 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
eba0fb64 1485
e5076eee
DM
1486 my $rules;
1487
1488 if ($rule->{macro}) {
1489 $rules = &$apply_macro($rule->{macro}, $rule);
1490 } else {
1491 $rules = [ $rule ];
1492 }
1493
d4091b82
DM
1494 # update all or nothing
1495
1496 my @cmds = ();
cbb5d6f3 1497 foreach my $tmp (@$rules) {
e523d2bb 1498 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
d4091b82 1499 push @cmds, $cmdstr;
e5076eee 1500 }
41524a58 1501 }
d4091b82
DM
1502
1503 foreach my $cmdstr (@cmds) {
1504 ruleset_addrule($ruleset, $chain, $cmdstr);
1505 }
3fa83edf 1506}
0f168d7b 1507
eba0fb64
DM
1508sub ruleset_generate_rule_insert {
1509 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1510
e5076eee
DM
1511 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1512
eba0fb64
DM
1513 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
1514 ruleset_insertrule($ruleset, $chain, $cmdstr);
1515 }
1516}
3fa83edf
DM
1517
1518sub ruleset_create_chain {
1519 my ($ruleset, $chain) = @_;
3a616aa0 1520
d050c724 1521 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
782c4cde 1522 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
d050c724 1523
3fa83edf
DM
1524 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1525
1526 $ruleset->{$chain} = [];
3a616aa0
AD
1527}
1528
3fa83edf
DM
1529sub ruleset_chain_exist {
1530 my ($ruleset, $chain) = @_;
3a616aa0 1531
3fa83edf
DM
1532 return $ruleset->{$chain} ? 1 : undef;
1533}
3a616aa0 1534
3fa83edf
DM
1535sub ruleset_addrule {
1536 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1537
3fa83edf 1538 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1539
3fa83edf
DM
1540 push @{$ruleset->{$chain}}, "-A $chain $rule";
1541}
3a616aa0 1542
3fa83edf
DM
1543sub ruleset_insertrule {
1544 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1545
3fa83edf 1546 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1547
3fa83edf
DM
1548 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1549}
3a616aa0 1550
782c4cde
DM
1551sub get_log_rule_base {
1552 my ($chain, $vmid, $msg, $loglevel) = @_;
cbb5d6f3 1553
782c4cde
DM
1554 die "internal error - no log level" if !defined($loglevel);
1555
1556 $vmid = 0 if !defined($vmid);
1557
cbb5d6f3 1558 # Note: we use special format for prefix to pass further
782c4cde
DM
1559 # info to log daemon (VMID, LOGVELEL and CHAIN)
1560
1561 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1562}
1563
1564sub ruleset_addlog {
1565 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1566
1567 return if !defined($loglevel);
1568
1569 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1570
1571 $logrule = "$rule $logrule" if defined($rule);
1572
88733a74 1573 ruleset_addrule($ruleset, $chain, $logrule);
782c4cde
DM
1574}
1575
ead850e8 1576sub ruleset_add_chain_policy {
782c4cde 1577 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
ead850e8
DM
1578
1579 if ($policy eq 'ACCEPT') {
1580
1581 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1582 { ACCEPT => $accept_action});
1583
1584 } elsif ($policy eq 'DROP') {
1585
1586 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1587
782c4cde 1588 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1589
1590 ruleset_addrule($ruleset, $chain, "-j DROP");
1591 } elsif ($policy eq 'REJECT') {
1592 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1593
782c4cde 1594 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1595
1596 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1597 } else {
1598 # should not happen
1599 die "internal error: unknown policy '$policy'";
1600 }
1601}
1602
e2943485
DM
1603sub ruleset_chain_add_conn_filters {
1604 my ($ruleset, $chain, $accept) = @_;
1605
1606 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1607 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1608}
1609
1610sub ruleset_chain_add_input_filters {
2428e394
AD
1611 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1612
1613 if ($cluster_conf->{ipset}->{blacklist}){
b5831a0d
AD
1614 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
1615 ruleset_create_chain($ruleset, "PVEFW-blacklist");
1616 ruleset_addlog($ruleset, "PVEFW-blacklist", 0, "DROP: ", $loglevel) if $loglevel;
1617 ruleset_addrule($ruleset, "PVEFW-blacklist", "-j DROP");
1618 }
708ba714
DM
1619 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1620 ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src -j PVEFW-blacklist");
2428e394 1621 }
e2943485
DM
1622
1623 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1624 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1625 }
1626
1627 if ($options->{tcpflags}) {
1628 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1629 }
1630}
1631
9e15114a 1632sub ruleset_create_vm_chain {
808d711d 1633 my ($ruleset, $chain, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
3a616aa0 1634
9e15114a 1635 ruleset_create_chain($ruleset, $chain);
b47ecc88 1636 my $accept = generate_nfqueue($options);
3a616aa0 1637
ce15d90b 1638 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
76a2d1e7 1639 if ($direction eq 'OUT') {
cbb5d6f3 1640 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
0f168d7b 1641 proto => 'udp', sport => 68, dport => 67 });
76a2d1e7 1642 } else {
cbb5d6f3 1643 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
0f168d7b 1644 proto => 'udp', sport => 67, dport => 68 });
76a2d1e7 1645 }
ce15d90b
DM
1646 }
1647
b21aca2c
DM
1648 if ($direction eq 'OUT') {
1649 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
9e15114a 1650 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
b21aca2c 1651 }
808d711d
DM
1652 if ($ipfilter_ipset) {
1653 ruleset_addrule($ruleset, $chain, "-m set ! --match-set $ipfilter_ipset src -j DROP");
1654 }
9e15114a 1655 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
c29f55c9 1656 }
9e15114a
DM
1657}
1658
4bc6b5ac
DM
1659sub ruleset_add_group_rule {
1660 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1661
1662 my $group = $rule->{action};
1663 my $group_chain = "GROUP-$group-$direction";
1664 if(!ruleset_chain_exist($ruleset, $group_chain)){
1665 generate_group_rules($ruleset, $cluster_conf, $group);
1666 }
bfc488f6 1667
f8b12fff
DM
1668 if ($direction eq 'OUT' && $rule->{iface_out}) {
1669 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain");
1670 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1671 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in} -j $group_chain");
4bc6b5ac
DM
1672 } else {
1673 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1674 }
1675
1676 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $action");
1677}
1678
9e15114a 1679sub ruleset_generate_vm_rules {
e523d2bb 1680 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options) = @_;
9e15114a
DM
1681
1682 my $lc_direction = lc($direction);
c29f55c9 1683
6b8ca015
DM
1684 my $in_accept = generate_nfqueue($options);
1685
92e976b3
DM
1686 foreach my $rule (@$rules) {
1687 next if $rule->{iface} && $rule->{iface} ne $netid;
b7ab6989 1688 next if !$rule->{enable} || $rule->{errors};
92e976b3 1689 if ($rule->{type} eq 'group') {
4bc6b5ac
DM
1690 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1691 $direction eq 'OUT' ? 'RETURN' : $in_accept);
92e976b3
DM
1692 } else {
1693 next if $rule->{type} ne $lc_direction;
921dfb33
DM
1694 eval {
1695 if ($direction eq 'OUT') {
1696 ruleset_generate_rule($ruleset, $chain, $rule,
e34d0e58 1697 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
e523d2bb 1698 undef, $cluster_conf, $vmfw_conf);
921dfb33 1699 } else {
e34d0e58
DM
1700 ruleset_generate_rule($ruleset, $chain, $rule,
1701 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
e523d2bb 1702 undef, $cluster_conf, $vmfw_conf);
921dfb33
DM
1703 }
1704 };
1705 warn $@ if $@;
4e6112f9 1706 }
3a616aa0 1707 }
9e15114a
DM
1708}
1709
b47ecc88
AD
1710sub generate_nfqueue {
1711 my ($options) = @_;
1712
73089769
DM
1713 if ($options->{ips}) {
1714 my $action = "NFQUEUE";
1715 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1716 if (defined($3) && defined($1)) {
b47ecc88 1717 $action .= " --queue-balance $1:$3";
73089769 1718 } elsif (defined($1)) {
b47ecc88
AD
1719 $action .= " --queue-num $1";
1720 }
1721 }
8dc92812 1722 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
73089769
DM
1723 return $action;
1724 } else {
1725 return "ACCEPT";
b47ecc88 1726 }
b47ecc88
AD
1727}
1728
da6fc60b 1729sub ruleset_generate_vm_ipsrules {
a01c32c7 1730 my ($ruleset, $options, $direction, $iface) = @_;
da6fc60b
AD
1731
1732 if ($options->{ips} && $direction eq 'IN') {
1733 my $nfqueue = generate_nfqueue($options);
1734
a01c32c7 1735 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
da6fc60b
AD
1736 ruleset_create_chain($ruleset, "PVEFW-IPS");
1737 }
1738
a01c32c7 1739 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
da6fc60b
AD
1740 }
1741}
1742
9e15114a 1743sub generate_venet_rules_direction {
58638f2c 1744 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
9e15114a 1745
9e15114a
DM
1746 my $lc_direction = lc($direction);
1747
1748 my $rules = $vmfw_conf->{rules};
1749
1750 my $options = $vmfw_conf->{options};
1751 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1752
1753 my $chain = "venet0-$vmid-$direction";
1754
b692f42c
DM
1755 my $ipfilter_name = compute_ipfilter_ipset_name('venet0');
1756 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name)
1757 if $vmfw_conf->{ipset}->{$ipfilter_name};
808d711d
DM
1758
1759 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $ipfilter_ipset, $direction);
9e15114a 1760
e523d2bb 1761 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction);
9e15114a
DM
1762
1763 # implement policy
1764 my $policy;
1765
1766 if ($direction eq 'OUT') {
1767 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1768 } else {
1769 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1770 }
1771
b47ecc88
AD
1772 my $accept = generate_nfqueue($options);
1773 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1774 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
9e15114a 1775
eba0fb64 1776 if ($direction eq 'OUT') {
41389aed 1777 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT", {
eba0fb64
DM
1778 action => $chain,
1779 source => $ip,
1780 iface_in => 'venet0'});
1781 } else {
41389aed 1782 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN", {
eba0fb64
DM
1783 action => $chain,
1784 dest => $ip,
1785 iface_out => 'venet0'});
1786 }
9e15114a
DM
1787}
1788
1789sub generate_tap_rules_direction {
58638f2c 1790 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
9e15114a
DM
1791
1792 my $lc_direction = lc($direction);
1793
1794 my $rules = $vmfw_conf->{rules};
1795
1796 my $options = $vmfw_conf->{options};
1797 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1798
1799 my $tapchain = "$iface-$direction";
1800
b692f42c
DM
1801 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
1802 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name)
1803 if $vmfw_conf->{ipset}->{$ipfilter_name};
808d711d
DM
1804
1805 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $ipfilter_ipset, $direction);
9e15114a 1806
e523d2bb 1807 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options);
3a616aa0 1808
a01c32c7 1809 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
da6fc60b 1810
ccae0b50
DM
1811 # implement policy
1812 my $policy;
1813
1814 if ($direction eq 'OUT') {
72f63fde 1815 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
ccae0b50 1816 } else {
72f63fde 1817 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
ccae0b50
DM
1818 }
1819
b47ecc88
AD
1820 my $accept = generate_nfqueue($options);
1821 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1822 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
3a616aa0 1823
3fa83edf 1824 # plug the tap chain to bridge chain
3cc81077 1825 if ($direction eq 'IN') {
a01c32c7
DM
1826 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
1827 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
3cc81077 1828 } else {
a01c32c7
DM
1829 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
1830 "-m physdev --physdev-is-bridged --physdev-in $iface -j $tapchain");
3cc81077 1831 }
3a616aa0
AD
1832}
1833
d18c1e2b 1834sub enable_host_firewall {
fca39c2c 1835 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
0bd5f137 1836
92e976b3 1837 my $options = $hostfw_conf->{options};
63324b09 1838 my $cluster_options = $cluster_conf->{options};
92e976b3 1839 my $rules = $hostfw_conf->{rules};
35f0c37e 1840 my $cluster_rules = $cluster_conf->{rules};
178a63be 1841
3fa83edf 1842 # host inbound firewall
dec84fcd
DM
1843 my $chain = "PVEFW-HOST-IN";
1844 ruleset_create_chain($ruleset, $chain);
0bd5f137 1845
178a63be
DM
1846 my $loglevel = get_option_log_level($options, "log_level_in");
1847
e2943485 1848 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
4ac863a6 1849
e2943485 1850 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2428e394 1851 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
fb424a00 1852
23e888f8
DM
1853 # we use RETURN because we need to check also tap rules
1854 my $accept_action = 'RETURN';
1855
cc8dc02f
DM
1856 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
1857
35f0c37e
DM
1858 # add host rules first, so that cluster wide rules can be overwritten
1859 foreach my $rule (@$rules, @$cluster_rules) {
5383df39 1860 next if !$rule->{enable} || $rule->{errors};
bfc488f6 1861
f8b12fff 1862 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
5383df39 1863
1a9978ed
DM
1864 eval {
1865 if ($rule->{type} eq 'group') {
1866 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1867 } elsif ($rule->{type} eq 'in') {
bfc488f6 1868 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
e523d2bb 1869 undef, $cluster_conf, $hostfw_conf);
1a9978ed
DM
1870 }
1871 };
1872 warn $@ if $@;
f8b12fff 1873 delete $rule->{iface_in};
0bd5f137 1874 }
eb399cef
DM
1875
1876 # allow standard traffic for management ipset (includes cluster network)
708ba714
DM
1877 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management");
1878 my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src";
eb399cef 1879 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006 -j $accept_action"); # PVE API
bfc488f6 1880 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
eb399cef
DM
1881 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
1882 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22 -j $accept_action"); # SSH
bfc488f6 1883
525778d7 1884 my $localnet = local_network();
3bc79f87 1885
eb399cef 1886 # corosync
525778d7 1887 if ($localnet) {
c5191f57 1888 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
525778d7
DM
1889 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule");
1890 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule");
3bc79f87 1891 }
0bd5f137 1892
23e888f8 1893 # implement input policy
63324b09 1894 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
782c4cde 1895 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
0bd5f137 1896
3fa83edf 1897 # host outbound firewall
aadd745e 1898 $chain = "PVEFW-HOST-OUT";
dec84fcd
DM
1899 ruleset_create_chain($ruleset, $chain);
1900
178a63be
DM
1901 $loglevel = get_option_log_level($options, "log_level_out");
1902
dec84fcd 1903 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
e2943485
DM
1904
1905 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1906
23e888f8
DM
1907 # we use RETURN because we may want to check other thigs later
1908 $accept_action = 'RETURN';
1909
cc8dc02f
DM
1910 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
1911
35f0c37e
DM
1912 # add host rules first, so that cluster wide rules can be overwritten
1913 foreach my $rule (@$rules, @$cluster_rules) {
5383df39
DM
1914 next if !$rule->{enable} || $rule->{errors};
1915
f8b12fff 1916 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1a9978ed
DM
1917 eval {
1918 if ($rule->{type} eq 'group') {
1919 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1920 } elsif ($rule->{type} eq 'out') {
bfc488f6 1921 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
e523d2bb 1922 undef, $cluster_conf, $hostfw_conf);
1a9978ed
DM
1923 }
1924 };
1925 warn $@ if $@;
f8b12fff 1926 delete $rule->{iface_out};
0bd5f137
AD
1927 }
1928
3bc79f87 1929 # allow standard traffic on cluster network
525778d7
DM
1930 if ($localnet) {
1931 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006 -j $accept_action"); # PVE API
1932 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22 -j $accept_action"); # SSH
bfc488f6 1933 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
525778d7 1934 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
bfc488f6 1935
c5191f57 1936 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
525778d7 1937 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule");
f573ae2c 1938 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule");
3bc79f87
DM
1939 }
1940
23e888f8 1941 # implement output policy
63324b09 1942 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
782c4cde 1943 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
6158271d 1944
dec84fcd
DM
1945 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1946 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
9d31b418
AD
1947}
1948
1949sub generate_group_rules {
fca39c2c 1950 my ($ruleset, $cluster_conf, $group) = @_;
9d31b418 1951
c6f5cc88 1952 my $rules = $cluster_conf->{groups}->{$group};
6158271d 1953
b4deedab
DM
1954 if (!$rules) {
1955 warn "no such security group '$group'\n";
1956 $rules = []; # create empty chain
1957 }
1958
3fa83edf 1959 my $chain = "GROUP-${group}-IN";
9d31b418 1960
3fa83edf 1961 ruleset_create_chain($ruleset, $chain);
b47ecc88 1962 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 1963
92e976b3
DM
1964 foreach my $rule (@$rules) {
1965 next if $rule->{type} ne 'in';
ba791b1f 1966 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418
AD
1967 }
1968
3fa83edf 1969 $chain = "GROUP-${group}-OUT";
9d31b418 1970
3fa83edf 1971 ruleset_create_chain($ruleset, $chain);
4e6112f9 1972 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 1973
92e976b3
DM
1974 foreach my $rule (@$rules) {
1975 next if $rule->{type} ne 'out';
1976 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1977 # check also other tap rules later
cbb5d6f3 1978 ruleset_generate_rule($ruleset, $chain, $rule,
ba791b1f 1979 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418 1980 }
9d31b418
AD
1981}
1982
51bae274
DM
1983my $MAX_NETS = 32;
1984my $valid_netdev_names = {};
1985for (my $i = 0; $i < $MAX_NETS; $i++) {
1986 $valid_netdev_names->{"net$i"} = 1;
1987}
5e1267a5 1988
51bae274 1989sub parse_fw_rule {
a523e057 1990 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
5e1267a5 1991
d4cda423
DM
1992 my $orig_line = $line;
1993
6d9246e7
DM
1994 my $rule = {};
1995
11bac5c2 1996 # we can add single line comments to the end of the rule
6d9246e7
DM
1997 if ($line =~ s/#\s*(.*?)\s*$//) {
1998 $rule->{comment} = decode('utf8', $1);
1999 }
11bac5c2
DM
2000
2001 # we can disable a rule when prefixed with '|'
ea9e5116 2002
6d9246e7 2003 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
51bae274 2004
dba740a9
DM
2005 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2006 die "unable to parse rule: $line\n";
6d9246e7
DM
2007
2008 $rule->{type} = lc($1);
2009 $rule->{action} = $2;
2010
2011 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2012 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2013 $rule->{macro} = $1;
2014 $rule->{action} = $2;
92e976b3 2015 }
51bae274
DM
2016 }
2017
dba740a9
DM
2018 while (length($line)) {
2019 if ($line =~ s/^-i (\S+)\s*//) {
6d9246e7 2020 $rule->{iface} = $1;
dba740a9
DM
2021 next;
2022 }
51bae274 2023
6d9246e7 2024 last if $rule->{type} eq 'group';
51bae274 2025
dba740a9 2026 if ($line =~ s/^-p (\S+)\s*//) {
6d9246e7 2027 $rule->{proto} = $1;
dba740a9
DM
2028 next;
2029 }
6d9246e7 2030
dba740a9 2031 if ($line =~ s/^-dport (\S+)\s*//) {
6d9246e7 2032 $rule->{dport} = $1;
dba740a9
DM
2033 next;
2034 }
6d9246e7 2035
dba740a9 2036 if ($line =~ s/^-sport (\S+)\s*//) {
6d9246e7 2037 $rule->{sport} = $1;
dba740a9
DM
2038 next;
2039 }
2040 if ($line =~ s/^-source (\S+)\s*//) {
6d9246e7 2041 $rule->{source} = $1;
dba740a9
DM
2042 next;
2043 }
2044 if ($line =~ s/^-dest (\S+)\s*//) {
6d9246e7 2045 $rule->{dest} = $1;
dba740a9
DM
2046 next;
2047 }
51bae274 2048
dba740a9
DM
2049 last;
2050 }
ba791b1f 2051
dba740a9 2052 die "unable to parse rule parameters: $line\n" if length($line);
51bae274 2053
a523e057 2054 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
d4cda423
DM
2055 if ($verbose && $rule->{errors}) {
2056 warn "$prefix - errors in rule parameters: $orig_line\n";
2057 foreach my $p (keys %{$rule->{errors}}) {
2058 warn " $p: $rule->{errors}->{$p}\n";
2059 }
2060 }
6d9246e7
DM
2061
2062 return $rule;
51bae274
DM
2063}
2064
2d404ffc 2065sub parse_vmfw_option {
85c6eaed
DM
2066 my ($line) = @_;
2067
2068 my ($opt, $value);
2069
178a63be
DM
2070 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2071
6bafd113 2072 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
9c6b6efd
DM
2073 $opt = lc($1);
2074 $value = int($2);
178a63be
DM
2075 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2076 $opt = lc($1);
2077 $value = $2 ? lc($3) : '';
72f63fde 2078 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
85c6eaed
DM
2079 $opt = lc($1);
2080 $value = uc($3);
b47ecc88
AD
2081 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2082 $opt = lc($1);
2083 $value = $2;
9c6b6efd 2084 } else {
85c6eaed
DM
2085 die "can't parse option '$line'\n"
2086 }
2087
2088 return ($opt, $value);
2089}
2090
2d404ffc
DM
2091sub parse_hostfw_option {
2092 my ($line) = @_;
2093
2094 my ($opt, $value);
2095
2096 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2097
c50a5a68 2098 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2d404ffc
DM
2099 $opt = lc($1);
2100 $value = int($2);
178a63be 2101 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2d404ffc
DM
2102 $opt = lc($1);
2103 $value = $2 ? lc($3) : '';
28c082a1 2104 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
490cdead
DM
2105 $opt = lc($1);
2106 $value = int($2);
2d404ffc 2107 } else {
2d404ffc
DM
2108 die "can't parse option '$line'\n"
2109 }
2110
2111 return ($opt, $value);
2112}
2113
c6f5cc88
DM
2114sub parse_clusterfw_option {
2115 my ($line) = @_;
2116
2117 my ($opt, $value);
2118
2119 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2120 $opt = lc($1);
2121 $value = int($2);
63324b09
DM
2122 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2123 $opt = lc($1);
2124 $value = uc($3);
c6f5cc88 2125 } else {
c6f5cc88
DM
2126 die "can't parse option '$line'\n"
2127 }
2128
2129 return ($opt, $value);
2130}
2131
6c221576
DM
2132sub resolve_alias {
2133 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2134
2135 if ($cidr !~ m/^\d/) {
2136 my $alias = lc($cidr);
2137 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2138 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2139 return $e->{cidr} if $e;
2140
2141 die "no such alias '$cidr'\n";
2142 }
2143
2144 return $cidr;
2145}
2146
e76a9f53 2147sub parse_alias {
92e1209b
AD
2148 my ($line) = @_;
2149
81d574a7
DM
2150 # we can add single line comments to the end of the line
2151 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2152
92e1209b 2153 if ($line =~ m/^(\S+)\s(\S+)$/) {
81d574a7
DM
2154 my ($name, $cidr) = ($1, $2);
2155 $cidr =~ s|/32$||;
2156 pve_verify_ipv4_or_cidr($cidr);
2157 my $data = {
2158 name => $name,
2159 cidr => $cidr,
2160 };
2161 $data->{comment} = $comment if $comment;
2162 return $data;
92e1209b
AD
2163 }
2164
81d574a7 2165 return undef;
92e1209b
AD
2166}
2167
e5cd1ee0 2168sub generic_fw_config_parser {
1210ae94 2169 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
5e1267a5 2170
51bae274
DM
2171 my $section;
2172 my $group;
2173
1210ae94 2174 my $res = $empty_conf;
6158271d 2175
51bae274
DM
2176 while (defined(my $line = <$fh>)) {
2177 next if $line =~ m/^#/;
2178 next if $line =~ m/^\s*$/;
2179
c8c534f7
DM
2180 chomp $line;
2181
961b4928
DM
2182 my $linenr = $fh->input_line_number();
2183 my $prefix = "$filename (line $linenr)";
2184
1210ae94 2185 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
c6f5cc88
DM
2186 $section = 'options';
2187 next;
2188 }
2189
1210ae94 2190 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
92e1209b
AD
2191 $section = 'aliases';
2192 next;
2193 }
2194
1210ae94 2195 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
c6f5cc88 2196 $section = 'groups';
92e976b3 2197 $group = lc($1);
0d22acb3 2198 my $comment = $2;
351052d1
DM
2199 eval {
2200 die "security group name too long\n" if length($group) > $max_group_name_length;
2201 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2202 };
2203 if (my $err = $@) {
2204 ($section, $group, $comment) = undef;
2205 warn "$prefix: $err";
2206 next;
2207 }
2208
c85c87f9 2209 $res->{$section}->{$group} = [];
649e4d57
DM
2210 $res->{group_comments}->{$group} = decode('utf8', $comment)
2211 if $comment;
51bae274
DM
2212 next;
2213 }
34cdedfa 2214
1210ae94 2215 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
c6f5cc88
DM
2216 $section = 'rules';
2217 next;
2218 }
cbb5d6f3 2219
1210ae94 2220 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
34cdedfa
AD
2221 $section = 'ipset';
2222 $group = lc($1);
d72c631c 2223 my $comment = $2;
351052d1
DM
2224 eval {
2225 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2226 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2227 };
2228 if (my $err = $@) {
2229 ($section, $group, $comment) = undef;
2230 warn "$prefix: $err";
2231 next;
2232 }
2233
c85c87f9 2234 $res->{$section}->{$group} = [];
e34d0e58 2235 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
649e4d57 2236 if $comment;
34cdedfa
AD
2237 next;
2238 }
2239
c6f5cc88 2240 if (!$section) {
cbb5d6f3 2241 warn "$prefix: skip line - no section\n";
51bae274
DM
2242 next;
2243 }
2244
c6f5cc88
DM
2245 if ($section eq 'options') {
2246 eval {
1210ae94
DM
2247 my ($opt, $value);
2248 if ($rule_env eq 'cluster') {
2249 ($opt, $value) = parse_clusterfw_option($line);
2250 } elsif ($rule_env eq 'host') {
2251 ($opt, $value) = parse_hostfw_option($line);
2252 } else {
2253 ($opt, $value) = parse_vmfw_option($line);
2254 }
c6f5cc88
DM
2255 $res->{options}->{$opt} = $value;
2256 };
2257 warn "$prefix: $@" if $@;
92e1209b
AD
2258 } elsif ($section eq 'aliases') {
2259 eval {
e76a9f53 2260 my $data = parse_alias($line);
81d574a7 2261 $res->{aliases}->{lc($data->{name})} = $data;
92e1209b
AD
2262 };
2263 warn "$prefix: $@" if $@;
c6f5cc88
DM
2264 } elsif ($section eq 'rules') {
2265 my $rule;
1210ae94 2266 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
c6f5cc88
DM
2267 if (my $err = $@) {
2268 warn "$prefix: $err";
2269 next;
2270 }
2271 push @{$res->{$section}}, $rule;
2272 } elsif ($section eq 'groups') {
34cdedfa 2273 my $rule;
1210ae94 2274 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); };
34cdedfa
AD
2275 if (my $err = $@) {
2276 warn "$prefix: $err";
2277 next;
2278 }
3f95d14a 2279 push @{$res->{$section}->{$group}}, $rule;
3f95d14a 2280 } elsif ($section eq 'ipset') {
9d6f90e6
DM
2281 # we can add single line comments to the end of the rule
2282 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2283
30f1b100 2284 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2a052ee3 2285 my $nomatch = $1;
9d6f90e6 2286 my $cidr = $2;
d46b1ef6
DM
2287 my $errors;
2288
2289 if ($nomatch && !$feature_ipset_nomatch) {
2290 $errors->{nomatch} = "nomatch not supported by kernel";
2291 }
2a052ee3 2292
4803b296
DM
2293 eval {
2294 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2295 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2296 } else {
2297 $cidr =~ s|/32$||;
d46b1ef6 2298 pve_verify_ipv4_or_cidr_or_alias($cidr);
92e1209b 2299 }
4803b296
DM
2300 };
2301 if (my $err = $@) {
c8c534f7 2302 chomp $err;
d46b1ef6 2303 $errors->{cidr} = $err;
2a052ee3 2304 }
2a052ee3 2305
e34d0e58 2306 my $entry = { cidr => $cidr };
9d6f90e6
DM
2307 $entry->{nomatch} = 1 if $nomatch;
2308 $entry->{comment} = $comment if $comment;
d46b1ef6 2309 $entry->{errors} = $errors if $errors;
e34d0e58 2310
c8c534f7 2311 if ($verbose && $errors) {
9a3061c7 2312 warn "$prefix - errors in ipset '$group': $line\n";
c8c534f7
DM
2313 foreach my $p (keys %{$errors}) {
2314 warn " $p: $errors->{$p}\n";
2315 }
2316 }
2317
9d6f90e6 2318 push @{$res->{$section}->{$group}}, $entry;
1210ae94
DM
2319 } else {
2320 warn "$prefix: skip line - unknown section\n";
2321 next;
51bae274 2322 }
5e1267a5
DM
2323 }
2324
2325 return $res;
2326}
2327
e5cd1ee0 2328sub parse_hostfw_config {
1210ae94
DM
2329 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2330
2331 my $empty_conf = { rules => [], options => {}};
2332
e5cd1ee0 2333 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host');
1210ae94
DM
2334}
2335
e5cd1ee0 2336sub parse_vmfw_config {
1210ae94
DM
2337 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2338
2339 my $empty_conf = {
2340 rules => [],
2341 options => {},
2342 aliases => {},
2343 ipset => {} ,
2344 ipset_comments => {},
2345 };
2346
e5cd1ee0 2347 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
1210ae94
DM
2348}
2349
e5cd1ee0 2350sub parse_clusterfw_config {
1210ae94
DM
2351 my ($filename, $fh, $verbose) = @_;
2352
2353 my $section;
2354 my $group;
2355
2356 my $empty_conf = {
2357 rules => [],
2358 options => {},
2359 aliases => {},
2360 groups => {},
2361 group_comments => {},
2362 ipset => {} ,
2363 ipset_comments => {},
2364 };
2365
e5cd1ee0 2366 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster');
1210ae94
DM
2367}
2368
06320eb0
DM
2369sub run_locked {
2370 my ($code, @param) = @_;
2371
2372 my $timeout = 10;
2373
2374 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2375
2376 die $@ if $@;
2377
2378 return $res;
2379}
2380
5e1267a5
DM
2381sub read_local_vm_config {
2382
2383 my $openvz = {};
5e1267a5
DM
2384 my $qemu = {};
2385
c8301d63 2386 my $vmdata = { openvz => $openvz, qemu => $qemu };
5e1267a5 2387
c8301d63
DM
2388 my $vmlist = PVE::Cluster::get_vmlist();
2389 return $vmdata if !$vmlist || !$vmlist->{ids};
2390 my $ids = $vmlist->{ids};
2391
2392 foreach my $vmid (keys %$ids) {
2393 next if !$vmid; # skip VE0
2394 my $d = $ids->{$vmid};
2395 next if !$d->{node} || $d->{node} ne $nodename;
2396 next if !$d->{type};
2397 if ($d->{type} eq 'openvz') {
d9fee004
DM
2398 if ($have_pve_manager) {
2399 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2400 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2401 $openvz->{$vmid} = $conf;
2402 }
c8301d63
DM
2403 }
2404 } elsif ($d->{type} eq 'qemu') {
d9fee004
DM
2405 if ($have_qemu_server) {
2406 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2407 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2408 $qemu->{$vmid} = $conf;
2409 }
c8301d63 2410 }
5e1267a5
DM
2411 }
2412 }
d9fee004 2413
5e1267a5
DM
2414 return $vmdata;
2415};
2416
e7b35711 2417sub load_vmfw_conf {
a523e057 2418 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
e7b35711
DM
2419
2420 my $vmfw_conf = {};
2421
21053409 2422 $dir = $pvefw_conf_dir if !defined($dir);
8aef5177
DM
2423
2424 my $filename = "$dir/$vmid.fw";
e7b35711 2425 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 2426 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
708ba714 2427 $vmfw_conf->{vmid} = $vmid;
e7b35711
DM
2428 }
2429
2430 return $vmfw_conf;
2431}
2432
464f933e 2433my $format_rules = sub {
dba740a9 2434 my ($rules, $allow_iface) = @_;
464f933e
DM
2435
2436 my $raw = '';
2437
2438 foreach my $rule (@$rules) {
c14dacdf 2439 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
464f933e
DM
2440 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2441 $raw .= uc($rule->{type});
7ca36671
DM
2442 if ($rule->{macro}) {
2443 $raw .= " $rule->{macro}($rule->{action})";
2444 } else {
2445 $raw .= " " . $rule->{action};
2446 }
dba740a9
DM
2447 if ($allow_iface && $rule->{iface}) {
2448 $raw .= " -i $rule->{iface}";
2449 }
c14dacdf
DM
2450
2451 if ($rule->{type} ne 'group') {
dba740a9
DM
2452 $raw .= " -source $rule->{source}" if $rule->{source};
2453 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2454 $raw .= " -p $rule->{proto}" if $rule->{proto};
2455 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2456 $raw .= " -sport $rule->{sport}" if $rule->{sport};
c14dacdf
DM
2457 }
2458
cbb5d6f3 2459 $raw .= " # " . encode('utf8', $rule->{comment})
464f933e
DM
2460 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2461 $raw .= "\n";
2462 } else {
c14dacdf 2463 die "unknown rule type '$rule->{type}'";
464f933e
DM
2464 }
2465 }
2466
2467 return $raw;
2468};
2469
2470my $format_options = sub {
68c90e21
DM
2471 my ($options) = @_;
2472
2473 my $raw = '';
464f933e
DM
2474
2475 $raw .= "[OPTIONS]\n\n";
2476 foreach my $opt (keys %$options) {
2477 $raw .= "$opt: $options->{$opt}\n";
2478 }
2479 $raw .= "\n";
68c90e21
DM
2480
2481 return $raw;
464f933e
DM
2482};
2483
0d5f0a0f
DM
2484my $format_aliases = sub {
2485 my ($aliases) = @_;
2486
2487 my $raw = '';
2488
2489 $raw .= "[ALIASES]\n\n";
2490 foreach my $k (keys %$aliases) {
81d574a7
DM
2491 my $e = $aliases->{$k};
2492 $raw .= "$e->{name} $e->{cidr}";
2493 $raw .= " # " . encode('utf8', $e->{comment})
2494 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2495 $raw .= "\n";
0d5f0a0f
DM
2496 }
2497 $raw .= "\n";
2498
2499 return $raw;
2500};
2501
1210ae94
DM
2502my $format_ipsets = sub {
2503 my ($fw_conf) = @_;
2504
9d6f90e6
DM
2505 my $raw = '';
2506
1210ae94
DM
2507 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2508 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2509 my $utf8comment = encode('utf8', $comment);
2510 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2511 } else {
2512 $raw .= "[IPSET $ipset]\n\n";
2513 }
2514 my $options = $fw_conf->{ipset}->{$ipset};
6e299ae3 2515
1210ae94
DM
2516 my $nethash = {};
2517 foreach my $entry (@$options) {
2518 $nethash->{$entry->{cidr}} = $entry;
2519 }
2520
2521 foreach my $cidr (sort keys %$nethash) {
2522 my $entry = $nethash->{$cidr};
2523 my $line = $entry->{nomatch} ? '!' : '';
2524 $line .= $entry->{cidr};
2525 $line .= " # " . encode('utf8', $entry->{comment})
2526 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2527 $raw .= "$line\n";
2528 }
2529
2530 $raw .= "\n";
9d6f90e6 2531 }
e34d0e58 2532
9d6f90e6
DM
2533 return $raw;
2534};
2535
464f933e
DM
2536sub save_vmfw_conf {
2537 my ($vmid, $vmfw_conf) = @_;
2538
2539 my $raw = '';
2540
2541 my $options = $vmfw_conf->{options};
89ea63c8 2542 $raw .= &$format_options($options) if $options && scalar(keys %$options);
cbb5d6f3 2543
e76a9f53 2544 my $aliases = $vmfw_conf->{aliases};
89ea63c8 2545 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
e76a9f53 2546
89ea63c8 2547 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
1210ae94 2548
8824b2f0 2549 my $rules = $vmfw_conf->{rules} || [];
89ea63c8 2550 if ($rules && scalar(@$rules)) {
464f933e
DM
2551 $raw .= "[RULES]\n\n";
2552 $raw .= &$format_rules($rules, 1);
2553 $raw .= "\n";
2554 }
2555
21053409
DM
2556 mkdir $pvefw_conf_dir;
2557
2558 my $filename = "$pvefw_conf_dir/$vmid.fw";
464f933e
DM
2559 PVE::Tools::file_set_contents($filename, $raw);
2560}
2561
6fc63ffd 2562sub read_vm_firewall_configs {
a523e057 2563 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
8aef5177 2564
6fc63ffd 2565 my $vmfw_configs = {};
c8301d63 2566
b6b8e6ad 2567 foreach my $vmid (keys %{$vmdata->{qemu}}) {
a523e057 2568 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose);
b6b8e6ad
DM
2569 next if !$vmfw_conf->{options}; # skip if file does not exists
2570 $vmfw_configs->{$vmid} = $vmfw_conf;
2571 }
2572 foreach my $vmid (keys %{$vmdata->{openvz}}) {
a523e057 2573 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose);
e7b35711
DM
2574 next if !$vmfw_conf->{options}; # skip if file does not exists
2575 $vmfw_configs->{$vmid} = $vmfw_conf;
5e1267a5
DM
2576 }
2577
6fc63ffd 2578 return $vmfw_configs;
5e1267a5
DM
2579}
2580
2d404ffc
DM
2581sub get_option_log_level {
2582 my ($options, $k) = @_;
2583
2584 my $v = $options->{$k};
178a63be 2585 $v = $default_log_level if !defined($v);
2d404ffc
DM
2586
2587 return undef if $v eq '' || $v eq 'nolog';
2588
2589 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2590
2591 return $v if ($v >= 0) && ($v <= 7);
2592
2593 warn "unknown log level ($k = '$v')\n";
2594
2595 return undef;
2596}
2597
d8f2505e 2598sub generate_std_chains {
2d404ffc 2599 my ($ruleset, $options) = @_;
cbb5d6f3 2600
2d404ffc
DM
2601 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2602
2603 # same as shorewall smurflog.
782c4cde 2604 my $chain = 'PVEFW-smurflog';
12f3796e 2605 $pve_std_chains->{$chain} = [];
782c4cde
DM
2606
2607 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2608 push @{$pve_std_chains->{$chain}}, "-j DROP";
2d404ffc
DM
2609
2610 # same as shorewall logflags action.
2611 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
782c4cde 2612 $chain = 'PVEFW-logflags';
12f3796e
DM
2613 $pve_std_chains->{$chain} = [];
2614
782c4cde
DM
2615 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2616 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2617 push @{$pve_std_chains->{$chain}}, "-j DROP";
d8f2505e
DM
2618
2619 foreach my $chain (keys %$pve_std_chains) {
2620 ruleset_create_chain($ruleset, $chain);
2621 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2622 if (ref($rule)) {
2623 ruleset_generate_rule($ruleset, $chain, $rule);
2624 } else {
2625 ruleset_addrule($ruleset, $chain, $rule);
2626 }
2627 }
2628 }
2629}
2630
34cdedfa 2631sub generate_ipset_chains {
708ba714 2632 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
34cdedfa 2633
dd7a13fd 2634 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
708ba714
DM
2635 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2636 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
34cdedfa
AD
2637 }
2638}
2639
2640sub generate_ipset {
708ba714
DM
2641 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2642
2643 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
34cdedfa 2644
dd7a13fd
DM
2645 my $hashsize = scalar(@$options);
2646 if ($hashsize <= 64) {
2a052ee3 2647 $hashsize = 64;
dd7a13fd 2648 } else {
2a052ee3
AD
2649 $hashsize = round_powerof2($hashsize);
2650 }
2651
708ba714 2652 $ipset_ruleset->{$name} = ["create $name hash:net family inet hashsize $hashsize maxelem $hashsize"];
34cdedfa 2653
30f1b100
DM
2654 # remove duplicates
2655 my $nethash = {};
9d6f90e6 2656 foreach my $entry (@$options) {
c8c534f7 2657 next if $entry->{errors}; # skip entries with errors
6c221576
DM
2658 eval {
2659 my $cidr = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2660 $nethash->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2661 };
2662 warn $@ if $@;
30f1b100
DM
2663 }
2664
2665 foreach my $cidr (sort keys %$nethash) {
2666 my $entry = $nethash->{$cidr};
2667
9d6f90e6
DM
2668 my $cmd = "add $name $cidr";
2669 if ($entry->{nomatch}) {
2670 if ($feature_ipset_nomatch) {
2671 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2672 } else {
2673 warn "ignore !$cidr - nomatch not supported by kernel\n";
2674 }
2675 } else {
2676 push @{$ipset_ruleset->{$name}}, $cmd;
2677 }
34cdedfa 2678 }
2a052ee3
AD
2679}
2680
2681sub round_powerof2 {
dd7a13fd 2682 my ($int) = @_;
2a052ee3 2683
dd7a13fd
DM
2684 $int--;
2685 $int |= $int >> $_ foreach (1,2,4,8,16);
2686 return ++$int;
34cdedfa
AD
2687}
2688
fca39c2c 2689sub load_clusterfw_conf {
d4cda423 2690 my ($filename, $verbose) = @_;
8aef5177
DM
2691
2692 $filename = $clusterfw_conf_filename if !defined($filename);
530c005e 2693
fca39c2c 2694 my $cluster_conf = {};
8aef5177 2695 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 2696 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
51bae274 2697 }
5e1267a5 2698
fca39c2c 2699 return $cluster_conf;
e5d76bde
DM
2700}
2701
fca39c2c
DM
2702sub save_clusterfw_conf {
2703 my ($cluster_conf) = @_;
9c7e0858
DM
2704
2705 my $raw = '';
9c7e0858 2706
c6f5cc88 2707 my $options = $cluster_conf->{options};
89ea63c8 2708 $raw .= &$format_options($options) if $options && scalar(keys %$options);
9c7e0858 2709
0d5f0a0f 2710 my $aliases = $cluster_conf->{aliases};
89ea63c8 2711 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
e34d0e58 2712
89ea63c8 2713 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
1210ae94 2714
c6f5cc88 2715 my $rules = $cluster_conf->{rules};
89ea63c8 2716 if ($rules && scalar(@$rules)) {
c6f5cc88 2717 $raw .= "[RULES]\n\n";
63c91681 2718 $raw .= &$format_rules($rules, 1);
c6f5cc88
DM
2719 $raw .= "\n";
2720 }
2721
89ea63c8
DM
2722 if ($cluster_conf->{groups}) {
2723 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2724 my $rules = $cluster_conf->{groups}->{$group};
2725 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2726 my $utf8comment = encode('utf8', $comment);
2727 $raw .= "[group $group] # $utf8comment\n\n";
2728 } else {
2729 $raw .= "[group $group]\n\n";
2730 }
0d22acb3 2731
89ea63c8
DM
2732 $raw .= &$format_rules($rules, 0);
2733 $raw .= "\n";
2734 }
9c7e0858
DM
2735 }
2736
21053409 2737 mkdir $pvefw_conf_dir;
fca39c2c 2738 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
9c7e0858
DM
2739}
2740
8b27beb9 2741sub load_hostfw_conf {
a523e057 2742 my ($cluster_conf, $filename, $verbose) = @_;
8aef5177
DM
2743
2744 $filename = $hostfw_conf_filename if !defined($filename);
8b27beb9
DM
2745
2746 my $hostfw_conf = {};
8aef5177 2747 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 2748 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
8b27beb9
DM
2749 }
2750 return $hostfw_conf;
2751}
2752
63c91681
DM
2753sub save_hostfw_conf {
2754 my ($hostfw_conf) = @_;
2755
2756 my $raw = '';
2757
2758 my $options = $hostfw_conf->{options};
89ea63c8 2759 $raw .= &$format_options($options) if $options && scalar(keys %$options);
cbb5d6f3 2760
63c91681 2761 my $rules = $hostfw_conf->{rules};
89ea63c8 2762 if ($rules && scalar(@$rules)) {
63c91681
DM
2763 $raw .= "[RULES]\n\n";
2764 $raw .= &$format_rules($rules, 1);
2765 $raw .= "\n";
2766 }
2767
2768 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2769}
2770
e5d76bde 2771sub compile {
d4cda423 2772 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3dfa8a7f 2773
8aef5177
DM
2774 my $vmfw_configs;
2775
2776 if ($vmdata) { # test mode
2777 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2778 my $filename = "$testdir/cluster.fw";
d4cda423 2779 $cluster_conf = load_clusterfw_conf($filename, $verbose);
8aef5177
DM
2780
2781 $filename = "$testdir/host.fw";
a523e057 2782 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
8aef5177 2783
a523e057 2784 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
8aef5177 2785 } else { # normal operation
d4cda423 2786 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
8aef5177 2787
a523e057 2788 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
8aef5177
DM
2789
2790 $vmdata = read_local_vm_config();
a523e057 2791 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
8aef5177 2792 }
3dfa8a7f 2793
27083984 2794 $cluster_conf->{ipset}->{venet0} = [];
708ba714 2795 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0');
bfc488f6 2796
525778d7
DM
2797 my $localnet;
2798 if ($cluster_conf->{aliases}->{local_network}) {
2799 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2800 } else {
2801 $localnet = local_network() || '127.0.0.0/8';
2802 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2803 }
2804
2805 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
bfc488f6 2806
085fd492
DM
2807 return ({}, {}) if !$cluster_conf->{options}->{enable};
2808
3fa83edf
DM
2809 my $ruleset = {};
2810
dec84fcd
DM
2811 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2812 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
5b1df9a0 2813
fadb13dd 2814 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
e34d0e58 2815
8b27beb9 2816 my $hostfw_options = $hostfw_conf->{options} || {};
fadb13dd 2817
88733a74
AD
2818 # fixme: what log level should we use here?
2819 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2820
097820b0 2821 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
88733a74 2822
708ba714 2823
e2943485 2824 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
708ba714
DM
2825 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2826 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
e2943485
DM
2827
2828 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2428e394 2829 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
e2943485 2830
d1b41c08 2831 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
e2943485
DM
2832
2833 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
d1b41c08 2834 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
e2943485
DM
2835
2836 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2428e394 2837 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
e2943485 2838
708ba714 2839 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
e2943485 2840
92e976b3 2841 generate_std_chains($ruleset, $hostfw_options);
fadb13dd 2842
6d2ab017 2843 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2d404ffc 2844
708ba714
DM
2845 my $ipset_ruleset = {};
2846
1a9978ed
DM
2847 if ($hostfw_enable) {
2848 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2849 warn $@ if $@; # just to be sure - should not happen
2850 }
3fa83edf 2851
708ba714 2852 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
62689a1e 2853
6158271d 2854 # generate firewall rules for QEMU VMs
3fa83edf 2855 foreach my $vmid (keys %{$vmdata->{qemu}}) {
1a9978ed
DM
2856 eval {
2857 my $conf = $vmdata->{qemu}->{$vmid};
2858 my $vmfw_conf = $vmfw_configs->{$vmid};
2859 return if !$vmfw_conf;
2860 return if !$vmfw_conf->{options}->{enable};
2861
708ba714
DM
2862 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2863
1a9978ed
DM
2864 foreach my $netid (keys %$conf) {
2865 next if $netid !~ m/^net(\d+)$/;
2866 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2867 next if !$net->{firewall};
2868 my $iface = "tap${vmid}i$1";
2869
2870 my $macaddr = $net->{macaddr};
2871 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2872 $vmfw_conf, $vmid, 'IN');
2873 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2874 $vmfw_conf, $vmid, 'OUT');
2875 }
2876 };
2877 warn $@ if $@; # just to be sure - should not happen
3fa83edf 2878 }
c8301d63
DM
2879
2880 # generate firewall rules for OpenVZ containers
2881 foreach my $vmid (keys %{$vmdata->{openvz}}) {
1a9978ed
DM
2882 eval {
2883 my $conf = $vmdata->{openvz}->{$vmid};
c8301d63 2884
1a9978ed
DM
2885 my $vmfw_conf = $vmfw_configs->{$vmid};
2886 return if !$vmfw_conf;
2887 return if !$vmfw_conf->{options}->{enable};
c8301d63 2888
708ba714
DM
2889 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2890
1a9978ed
DM
2891 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2892 my $ip = $conf->{ip_address}->{value};
2893 $ip =~ s/\s+/,/g;
2894 parse_address_list($ip); # make sure we have a valid $ip list
27083984 2895
1a9978ed 2896 my @ips = split(',', $ip);
27083984 2897
1a9978ed
DM
2898 foreach my $singleip (@ips) {
2899 my $venet0ipset = {};
2900 $venet0ipset->{cidr} = $singleip;
2901 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2902 }
c8301d63 2903
1a9978ed
DM
2904 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN');
2905 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT');
2906 }
530c005e 2907
1a9978ed
DM
2908 if ($conf->{netif} && $conf->{netif}->{value}) {
2909 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2910 foreach my $netid (keys %$netif) {
2911 my $d = $netif->{$netid};
2912
2913 my $macaddr = $d->{mac};
2914 my $iface = $d->{host_ifname};
2915 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2916 $vmfw_conf, $vmid, 'IN');
2917 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2918 $vmfw_conf, $vmid, 'OUT');
2919 }
c8301d63 2920 }
1a9978ed
DM
2921 };
2922 warn $@ if $@; # just to be sure - should not happen
c8301d63 2923 }
c0413e35 2924
097820b0
AD
2925 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2926 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2927 }
2928
708ba714 2929 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
27083984 2930
3dfa8a7f 2931 return ($ruleset, $ipset_ruleset);
3fa83edf
DM
2932}
2933
2934sub get_ruleset_status {
4bd0a9c4 2935 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3fa83edf
DM
2936
2937 my $statushash = {};
2938
2939 foreach my $chain (sort keys %$ruleset) {
4bd0a9c4 2940 my $sig = &$digest_fn($ruleset->{$chain});
9bf7d929 2941
3fa83edf
DM
2942 $statushash->{$chain}->{sig} = $sig;
2943
2944 my $oldsig = $active_chains->{$chain};
2945 if (!defined($oldsig)) {
2946 $statushash->{$chain}->{action} = 'create';
2947 } else {
2948 if ($oldsig eq $sig) {
2949 $statushash->{$chain}->{action} = 'exists';
2950 } else {
2951 $statushash->{$chain}->{action} = 'update';
2952 }
2953 }
2954 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2955 foreach my $cmd (@{$ruleset->{$chain}}) {
2956 print "\t$cmd\n" if $verbose;
2957 }
2958 }
2959
2960 foreach my $chain (sort keys %$active_chains) {
2961 if (!defined($ruleset->{$chain})) {
2962 my $sig = $active_chains->{$chain};
2963 $statushash->{$chain}->{action} = 'delete';
2964 $statushash->{$chain}->{sig} = $sig;
2965 print "delete $chain ($sig)\n" if $verbose;
2966 }
6158271d 2967 }
2a052ee3 2968
3fa83edf
DM
2969 return $statushash;
2970}
2971
3fa83edf
DM
2972sub print_sig_rule {
2973 my ($chain, $sig) = @_;
2974
09d5f68e
DM
2975 # We just use this to store a SHA1 checksum used to detect changes
2976 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
b6360c3f
DM
2977}
2978
df7cb349 2979sub get_ruleset_cmdlist {
a84f4d96 2980 my ($ruleset, $verbose) = @_;
3fa83edf 2981
3fa83edf 2982 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
cbb5d6f3 2983
4bd0a9c4
DM
2984 my ($active_chains, $hooks) = iptables_get_chains();
2985 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3fa83edf
DM
2986
2987 # create missing chains first
2988 foreach my $chain (sort keys %$ruleset) {
2989 my $stat = $statushash->{$chain};
2990 die "internal error" if !$stat;
2991 next if $stat->{action} ne 'create';
886aba9c 2992
3fa83edf
DM
2993 $cmdlist .= ":$chain - [0:0]\n";
2994 }
2995
4bd0a9c4 2996 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
55fad3b7
DM
2997 my $chain = "PVEFW-$h";
2998 if ($ruleset->{$chain} && !$hooks->{$h}) {
2999 $cmdlist .= "-A $h -j $chain\n";
4bd0a9c4 3000 }
3fa83edf
DM
3001 }
3002
3003 foreach my $chain (sort keys %$ruleset) {
3004 my $stat = $statushash->{$chain};
3005 die "internal error" if !$stat;
3006
3007 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
3008 $cmdlist .= "-F $chain\n";
3009 foreach my $cmd (@{$ruleset->{$chain}}) {
3010 $cmdlist .= "$cmd\n";
3011 }
3012 $cmdlist .= print_sig_rule($chain, $stat->{sig});
3013 } elsif ($stat->{action} eq 'delete') {
f5d28682 3014 die "internal error"; # this should not happen
3fa83edf
DM
3015 } elsif ($stat->{action} eq 'exists') {
3016 # do nothing
3017 } else {
3018 die "internal error - unknown status '$stat->{action}'";
3019 }
3020 }
3021
f5d28682
DM
3022 foreach my $chain (keys %$statushash) {
3023 next if $statushash->{$chain}->{action} ne 'delete';
3024 $cmdlist .= "-F $chain\n";
3025 }
3026 foreach my $chain (keys %$statushash) {
3027 next if $statushash->{$chain}->{action} ne 'delete';
fadb13dd
DM
3028 next if $chain eq 'PVEFW-INPUT';
3029 next if $chain eq 'PVEFW-OUTPUT';
3030 next if $chain eq 'PVEFW-FORWARD';
f5d28682
DM
3031 $cmdlist .= "-X $chain\n";
3032 }
3033
3f95d14a 3034 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
4bd0a9c4 3035
3fa83edf
DM
3036 $cmdlist .= "COMMIT\n";
3037
3f95d14a 3038 return wantarray ? ($cmdlist, $changes) : $cmdlist;
6b9f68a2
DM
3039}
3040
34cdedfa 3041sub get_ipset_cmdlist {
dd7a13fd 3042 my ($ruleset, $verbose) = @_;
34cdedfa
AD
3043
3044 my $cmdlist = "";
3045
dd7a13fd
DM
3046 my $delete_cmdlist = "";
3047
4bd0a9c4
DM
3048 my $active_chains = ipset_get_chains();
3049 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
34cdedfa 3050
e34d0e58 3051 # remove stale _swap chains
30f1b100
DM
3052 foreach my $chain (keys %$active_chains) {
3053 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3054 $cmdlist .= "destroy $chain\n";
3055 }
3056 }
3057
dd7a13fd
DM
3058 foreach my $chain (sort keys %$ruleset) {
3059 my $stat = $statushash->{$chain};
3060 die "internal error" if !$stat;
2a052ee3 3061
dd7a13fd
DM
3062 if ($stat->{action} eq 'create') {
3063 foreach my $cmd (@{$ruleset->{$chain}}) {
34cdedfa
AD
3064 $cmdlist .= "$cmd\n";
3065 }
dd7a13fd 3066 }
34cdedfa 3067
dd7a13fd
DM
3068 if ($stat->{action} eq 'update') {
3069 my $chain_swap = $chain."_swap";
cbb5d6f3 3070
dd7a13fd
DM
3071 foreach my $cmd (@{$ruleset->{$chain}}) {
3072 $cmd =~ s/$chain/$chain_swap/;
3073 $cmdlist .= "$cmd\n";
34cdedfa 3074 }
dd7a13fd
DM
3075 $cmdlist .= "swap $chain_swap $chain\n";
3076 $cmdlist .= "flush $chain_swap\n";
3077 $cmdlist .= "destroy $chain_swap\n";
2a052ee3 3078 }
34cdedfa 3079
dd7a13fd 3080 }
3f95d14a 3081
dd7a13fd
DM
3082 foreach my $chain (keys %$statushash) {
3083 next if $statushash->{$chain}->{action} ne 'delete';
2a052ee3 3084
dd7a13fd
DM
3085 $delete_cmdlist .= "flush $chain\n";
3086 $delete_cmdlist .= "destroy $chain\n";
34cdedfa
AD
3087 }
3088
dd7a13fd 3089 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
cbb5d6f3 3090
dd7a13fd 3091 return ($cmdlist, $delete_cmdlist, $changes);
34cdedfa
AD
3092}
3093
6b9f68a2 3094sub apply_ruleset {
34cdedfa 3095 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
6b9f68a2
DM
3096
3097 enable_bridge_firewall();
3098
cbb5d6f3 3099 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
81a0bf43 3100 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
6b9f68a2 3101
81a0bf43 3102 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
2a052ee3 3103
81a0bf43
DM
3104 if ($verbose) {
3105 if ($ipset_changes) {
3106 print "ipset changes:\n";
3107 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3108 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3109 }
3f95d14a 3110
81a0bf43
DM
3111 if ($changes) {
3112 print "iptables changes:\n";
3113 print $cmdlist;
3114 }
3115 }
3fa83edf 3116
2a052ee3 3117 ipset_restore_cmdlist($ipset_create_cmdlist);
34cdedfa 3118
3fa83edf
DM
3119 iptables_restore_cmdlist($cmdlist);
3120
dd7a13fd 3121 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2a052ee3 3122
6158271d 3123 # test: re-read status and check if everything is up to date
4bd0a9c4 3124 my $active_chains = iptables_get_chains();
81a0bf43 3125 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3fa83edf
DM
3126
3127 my $errors;
3128 foreach my $chain (sort keys %$ruleset) {
3129 my $stat = $statushash->{$chain};
3130 if ($stat->{action} ne 'exists') {
3131 warn "unable to update chain '$chain'\n";
3132 $errors = 1;
3133 }
3134 }
b6360c3f 3135
3fa83edf 3136 die "unable to apply firewall changes\n" if $errors;
46a2ac1f
AD
3137
3138 update_nf_conntrack_max($hostfw_conf);
3139
3140 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
3141
b6360c3f
DM
3142}
3143
490cdead
DM
3144sub update_nf_conntrack_max {
3145 my ($hostfw_conf) = @_;
3146
3147 my $max = 65536; # reasonable default
3148
3149 my $options = $hostfw_conf->{options} || {};
3150
3151 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3152 $max = $options->{nf_conntrack_max};
3153 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3154 }
3155
3156 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3157 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3158
3159 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3160
3161 if ($current != $max) {
3162 my $hashsize = int($max/4);
3163 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3164 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3165 }
3166}
3167
28c082a1
AD
3168sub update_nf_conntrack_tcp_timeout_established {
3169 my ($hostfw_conf) = @_;
3170
3171 my $options = $hostfw_conf->{options} || {};
3172
3173 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3174
3175 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3176}
3177
c4a2e5ae
DM
3178sub remove_pvefw_chains {
3179
3180 my ($chash, $hooks) = iptables_get_chains();
3181 my $cmdlist = "*filter\n";
3182
3183 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3184 if ($hooks->{$h}) {
3185 $cmdlist .= "-D $h -j PVEFW-$h\n";
3186 }
3187 }
cbb5d6f3 3188
c4a2e5ae
DM
3189 foreach my $chain (keys %$chash) {
3190 $cmdlist .= "-F $chain\n";
3191 }
3192
3193 foreach my $chain (keys %$chash) {
3194 $cmdlist .= "-X $chain\n";
3195 }
3196 $cmdlist .= "COMMIT\n";
3197
3198 iptables_restore_cmdlist($cmdlist);
55fad3b7
DM
3199
3200 my $ipset_chains = ipset_get_chains();
3201
3202 $cmdlist = "";
3203
3204 foreach my $chain (keys %$ipset_chains) {
3205 $cmdlist .= "flush $chain\n";
3206 $cmdlist .= "destroy $chain\n";
3207 }
3208
3209 ipset_restore_cmdlist($cmdlist) if $cmdlist;
c4a2e5ae
DM
3210}
3211
8b453a09
DM
3212sub init {
3213 my $cluster_conf = load_clusterfw_conf();
3214 my $cluster_options = $cluster_conf->{options};
3215 my $enable = $cluster_options->{enable};
3216
3217 return if !$enable;
3218
3219 # load required modules here
3220}
3221
6b9f68a2 3222sub update {
6b9f68a2 3223 my $code = sub {
3dfa8a7f
DM
3224
3225 my $cluster_conf = load_clusterfw_conf();
3226 my $cluster_options = $cluster_conf->{options};
3227
55fad3b7 3228 if (!$cluster_options->{enable}) {
b22130d3 3229 PVE::Firewall::remove_pvefw_chains();
3dfa8a7f
DM
3230 return;
3231 }
3232
3233 my $hostfw_conf = load_hostfw_conf();
3234
3235 my ($ruleset, $ipset_ruleset) = compile($cluster_conf, $hostfw_conf);
490cdead 3236
d4cda423 3237 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset);
6b9f68a2
DM
3238 };
3239
3240 run_locked($code);
3241}
3242
b6360c3f 32431;