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