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