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