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