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