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