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