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