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