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