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