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