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