]> git.proxmox.com Git - pve-firewall.git/blame - src/PVE/Firewall.pm
eliminate unused nbdport in pve_std_chains_conf
[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
1e9c5070 1802sub ruleset_generate_match {
88c26d5e 1803 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
3a616aa0 1804
00bb4391 1805 return if defined($rule->{enable}) && !$rule->{enable};
6d9246e7 1806 return if $rule->{errors};
11bac5c2 1807
044409e5
TW
1808 return $rule->{match} if defined $rule->{match};
1809
e5076eee
DM
1810 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1811
a1c04f71
WB
1812 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}, 1) : 0;
1813 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}, 0) : 0;
e5076eee 1814
41524a58 1815 my @cmd = ();
3a616aa0 1816
eba0fb64
DM
1817 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1818 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1819
ba791b1f
AD
1820 my $source = $rule->{source};
1821 my $dest = $rule->{dest};
1822
cbb5d6f3 1823 if ($source) {
44be8ceb 1824 if ($source =~ m/^\+/) {
4dfe04e6 1825 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
e523d2bb
DM
1826 my $name = $1;
1827 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
88c26d5e 1828 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
708ba714 1829 push @cmd, "-m set --match-set ${ipset_chain} src";
e523d2bb 1830 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
88c26d5e 1831 my $ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
708ba714 1832 push @cmd, "-m set --match-set ${ipset_chain} src";
e523d2bb
DM
1833 } else {
1834 die "no such ipset '$name'\n";
1835 }
44be8ceb
DM
1836 } else {
1837 die "invalid security group name '$source'\n";
1838 }
1839 } elsif ($source =~ m/^${ip_alias_pattern}$/){
81d574a7 1840 my $alias = lc($source);
04f5088f 1841 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
e523d2bb
DM
1842 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1843 die "no such alias '$source'\n" if !$e;
81d574a7 1844 push @cmd, "-s $e->{cidr}";
ac8242cc 1845 } elsif ($source =~ m/\-/){
ba791b1f 1846 push @cmd, "-m iprange --src-range $source";
cbb5d6f3 1847 } else {
ba791b1f
AD
1848 push @cmd, "-s $source";
1849 }
1850 }
1851
cbb5d6f3 1852 if ($dest) {
44be8ceb 1853 if ($dest =~ m/^\+/) {
4dfe04e6 1854 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
e523d2bb
DM
1855 my $name = $1;
1856 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
88c26d5e 1857 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
ac4580a0 1858 push @cmd, "-m set --match-set ${ipset_chain} dst";
e523d2bb 1859 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
88c26d5e 1860 my $ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
708ba714 1861 push @cmd, "-m set --match-set ${ipset_chain} dst";
e523d2bb
DM
1862 } else {
1863 die "no such ipset '$name'\n";
1864 }
44be8ceb
DM
1865 } else {
1866 die "invalid security group name '$dest'\n";
1867 }
1868 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
51b40846 1869 my $alias = lc($dest);
04f5088f 1870 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
e523d2bb
DM
1871 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1872 die "no such alias '$dest'\n" if !$e;
81d574a7 1873 push @cmd, "-d $e->{cidr}";
cbb5d6f3 1874 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
ba791b1f 1875 push @cmd, "-m iprange --dst-range $dest";
cbb5d6f3 1876 } else {
d6d2a385 1877 push @cmd, "-d $dest";
ba791b1f
AD
1878 }
1879 }
4b586518 1880
95e35949
WB
1881 if (my $proto = $rule->{proto}) {
1882 push @cmd, "-p $proto";
e3a1d391 1883
181390b0 1884 my $multiport = 0;
e5076eee
DM
1885 $multiport++ if $nbdport > 1;
1886 $multiport++ if $nbsport > 1;
e3a1d391 1887
41524a58 1888 push @cmd, "--match multiport" if $multiport;
4b586518 1889
cbb5d6f3 1890 die "multiport: option '--sports' cannot be used together with '--dports'\n"
181390b0
DM
1891 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1892
1893 if ($rule->{dport}) {
95e35949 1894 if ($proto eq 'icmp') {
181390b0 1895 # Note: we use dport to store --icmp-type
9bd7a4b3
WB
1896 die "unknown icmp-type '$rule->{dport}'\n"
1897 if $rule->{dport} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport}});
41524a58 1898 push @cmd, "-m icmp --icmp-type $rule->{dport}";
95e35949 1899 } elsif ($proto eq 'icmpv6') {
041b9277 1900 # Note: we use dport to store --icmpv6-type
9bd7a4b3
WB
1901 die "unknown icmpv6-type '$rule->{dport}'\n"
1902 if $rule->{dport} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport}});
041b9277 1903 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
48e3963e
WB
1904 } elsif (!$PROTOCOLS_WITH_PORTS->{$proto}) {
1905 die "protocol $proto does not have ports\n";
181390b0 1906 } else {
e5076eee 1907 if ($nbdport > 1) {
181390b0 1908 if ($multiport == 2) {
41524a58 1909 push @cmd, "--ports $rule->{dport}";
181390b0 1910 } else {
41524a58 1911 push @cmd, "--dports $rule->{dport}";
181390b0 1912 }
e3a1d391 1913 } else {
41524a58 1914 push @cmd, "--dport $rule->{dport}";
e3a1d391 1915 }
4b586518
DM
1916 }
1917 }
4b586518 1918
181390b0 1919 if ($rule->{sport}) {
48e3963e
WB
1920 die "protocol $proto does not have ports\n"
1921 if !$PROTOCOLS_WITH_PORTS->{$proto};
e5076eee 1922 if ($nbsport > 1) {
41524a58 1923 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
181390b0 1924 } else {
41524a58 1925 push @cmd, "--sport $rule->{sport}";
181390b0 1926 }
4b586518 1927 }
181390b0 1928 } elsif ($rule->{dport} || $rule->{sport}) {
93d96f83
DM
1929 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1930 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
4b586518
DM
1931 }
1932
41524a58 1933 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
4e6112f9 1934
1e9c5070
TW
1935 return scalar(@cmd) ? join(' ', @cmd) : undef;
1936}
1937
1938sub ruleset_generate_action {
1939 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1940
044409e5
TW
1941 return $rule->{target} if defined $rule->{target};
1942
1e9c5070
TW
1943 my @cmd = ();
1944
4e6112f9 1945 if (my $action = $rule->{action}) {
cbb5d6f3 1946 $action = $actions->{$action} if defined($actions->{$action});
4e6112f9 1947 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
41524a58 1948 push @cmd, $goto ? "-g $action" : "-j $action";
181390b0 1949 }
3a616aa0 1950
eba0fb64
DM
1951 return scalar(@cmd) ? join(' ', @cmd) : undef;
1952}
1953
1e9c5070
TW
1954sub ruleset_generate_cmdstr {
1955 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1956 my $match = ruleset_generate_match($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf);
1957 my $action = ruleset_generate_action($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf);
1958
1959 return undef if !(defined($match) or defined($action));
1960 my $ret = defined($match) ? $match : "";
1961 $ret = "$ret $action" if defined($action);
1962 return $ret;
1963}
1964
eba0fb64 1965sub ruleset_generate_rule {
88c26d5e 1966 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
eba0fb64 1967
e5076eee
DM
1968 my $rules;
1969
1970 if ($rule->{macro}) {
35d1d6da 1971 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
e5076eee
DM
1972 } else {
1973 $rules = [ $rule ];
1974 }
1975
d4091b82
DM
1976 # update all or nothing
1977
044409e5 1978 # fixme: lots of temporary ugliness
1e9c5070
TW
1979 my @mstrs = ();
1980 my @astrs = ();
044409e5
TW
1981 my @logging = ();
1982 my @logmsg = ();
cbb5d6f3 1983 foreach my $tmp (@$rules) {
1e9c5070
TW
1984 my $m = ruleset_generate_match($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf);
1985 my $a = ruleset_generate_action($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf);
1986 if (defined $m or defined $a) {
1987 push @mstrs, defined($m) ? $m : "";
1988 push @astrs, defined($a) ? $a : "";
044409e5
TW
1989 push @logging, $tmp->{log};
1990 push @logmsg, $tmp->{logmsg};
e5076eee 1991 }
41524a58 1992 }
d4091b82 1993
1e9c5070 1994 for my $i (0 .. $#mstrs) {
044409e5 1995 ruleset_addrule($ruleset, $chain, $mstrs[$i], $astrs[$i], $logging[$i], $logmsg[$i]);
d4091b82 1996 }
3fa83edf 1997}
0f168d7b 1998
eba0fb64 1999sub ruleset_generate_rule_insert {
88c26d5e 2000 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
eba0fb64 2001
e5076eee
DM
2002 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
2003
1e9c5070
TW
2004 my $match = ruleset_generate_match($ruleset, $chain, $ipversion, $rule, $actions, $goto);
2005 my $action = ruleset_generate_action($ruleset, $chain, $ipversion, $rule, $actions, $goto);
2006 if (defined $match && defined $action) {
2007 ruleset_insertrule($ruleset, $chain, $match, $action);
eba0fb64
DM
2008 }
2009}
3fa83edf
DM
2010
2011sub ruleset_create_chain {
2012 my ($ruleset, $chain) = @_;
3a616aa0 2013
d050c724 2014 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
782c4cde 2015 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
d050c724 2016
3fa83edf
DM
2017 die "chain '$chain' already exists\n" if $ruleset->{$chain};
2018
2019 $ruleset->{$chain} = [];
3a616aa0
AD
2020}
2021
3fa83edf
DM
2022sub ruleset_chain_exist {
2023 my ($ruleset, $chain) = @_;
3a616aa0 2024
3fa83edf
DM
2025 return $ruleset->{$chain} ? 1 : undef;
2026}
3a616aa0 2027
1e9c5070 2028sub ruleset_addrule {
7f7930f8 2029 my ($ruleset, $chain, $match, $action, $log, $logmsg, $vmid) = @_;
1e9c5070
TW
2030
2031 die "no such chain '$chain'\n" if !$ruleset->{$chain};
2032
7f7930f8
TW
2033 if (defined($log) && $log) {
2034 my $logaction = get_log_rule_base($chain, $vmid, $logmsg, $log);
2035 push @{$ruleset->{$chain}}, "-A $chain $match $logaction";
2036 }
1e9c5070
TW
2037 push @{$ruleset->{$chain}}, "-A $chain $match $action";
2038}
2039
3fa83edf 2040sub ruleset_insertrule {
1e9c5070 2041 my ($ruleset, $chain, $match, $action, $log) = @_;
3a616aa0 2042
3fa83edf 2043 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 2044
1e9c5070 2045 unshift @{$ruleset->{$chain}}, "-A $chain $match $action";
3fa83edf 2046}
3a616aa0 2047
782c4cde
DM
2048sub get_log_rule_base {
2049 my ($chain, $vmid, $msg, $loglevel) = @_;
cbb5d6f3 2050
782c4cde 2051 $vmid = 0 if !defined($vmid);
7f7930f8 2052 $msg = "" if !defined($msg);
782c4cde 2053
cbb5d6f3 2054 # Note: we use special format for prefix to pass further
7f7930f8 2055 # info to log daemon (VMID, LOGLEVEL and CHAIN)
782c4cde
DM
2056
2057 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
2058}
2059
ead850e8 2060sub ruleset_add_chain_policy {
88c26d5e 2061 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
ead850e8
DM
2062
2063 if ($policy eq 'ACCEPT') {
2064
88c26d5e 2065 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
ead850e8
DM
2066 { ACCEPT => $accept_action});
2067
2068 } elsif ($policy eq 'DROP') {
2069
1e9c5070 2070 ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Drop");
ead850e8 2071
7f7930f8 2072 ruleset_addrule($ruleset, $chain, "", "-j DROP", $loglevel, "policy $policy: ", $vmid);
ead850e8 2073 } elsif ($policy eq 'REJECT') {
1e9c5070 2074 ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Reject");
ead850e8 2075
7f7930f8 2076 ruleset_addrule($ruleset, $chain, "", "-g PVEFW-reject", $loglevel, "policy $policy:", $vmid);
ead850e8
DM
2077 } else {
2078 # should not happen
2079 die "internal error: unknown policy '$policy'";
2080 }
2081}
2082
a83abe93 2083sub ruleset_chain_add_ndp {
e8415920 2084 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
a83abe93
WB
2085 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
2086
1e9c5070 2087 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-solicitation", $accept);
d7aa51ac 2088 if ($direction ne 'OUT' || $options->{radv}) {
1e9c5070 2089 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-advertisement", $accept);
d7aa51ac 2090 }
1e9c5070
TW
2091 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type neighbor-solicitation", $accept);
2092 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type neighbor-advertisement", $accept);
a83abe93
WB
2093}
2094
e2943485
DM
2095sub ruleset_chain_add_conn_filters {
2096 my ($ruleset, $chain, $accept) = @_;
2097
1e9c5070
TW
2098 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID", "-j DROP");
2099 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED", "-j $accept");
e2943485
DM
2100}
2101
2102sub ruleset_chain_add_input_filters {
88c26d5e 2103 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2428e394
AD
2104
2105 if ($cluster_conf->{ipset}->{blacklist}){
b5831a0d
AD
2106 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
2107 ruleset_create_chain($ruleset, "PVEFW-blacklist");
7f7930f8 2108 ruleset_addrule($ruleset, "PVEFW-blacklist", "", "-j DROP", $loglevel, "DROP: ");
b5831a0d 2109 }
88c26d5e 2110 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
1e9c5070 2111 ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src", "-j PVEFW-blacklist");
2428e394 2112 }
e2943485
DM
2113
2114 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
5b5c42b1 2115 if ($ipversion == 4) {
1e9c5070 2116 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW", "-j PVEFW-smurfs");
5b5c42b1 2117 }
e2943485
DM
2118 }
2119
2120 if ($options->{tcpflags}) {
1e9c5070 2121 ruleset_addrule($ruleset, $chain, "-p tcp", "-j PVEFW-tcpflags");
e2943485
DM
2122 }
2123}
2124
9e15114a 2125sub ruleset_create_vm_chain {
88c26d5e 2126 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
3a616aa0 2127
9e15114a 2128 ruleset_create_chain($ruleset, $chain);
b47ecc88 2129 my $accept = generate_nfqueue($options);
3a616aa0 2130
ce15d90b 2131 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
dcafc5fb
WB
2132 if ($ipversion == 4) {
2133 if ($direction eq 'OUT') {
2134 ruleset_generate_rule($ruleset, $chain, $ipversion,
2135 { action => 'PVEFW-SET-ACCEPT-MARK',
2136 proto => 'udp', sport => 68, dport => 67 });
2137 } else {
2138 ruleset_generate_rule($ruleset, $chain, $ipversion,
2139 { action => 'ACCEPT',
2140 proto => 'udp', sport => 67, dport => 68 });
2141 }
2142 } elsif ($ipversion == 6) {
2143 if ($direction eq 'OUT') {
2144 ruleset_generate_rule($ruleset, $chain, $ipversion,
2145 { action => 'PVEFW-SET-ACCEPT-MARK',
2146 proto => 'udp', sport => 546, dport => 547 });
2147 } else {
2148 ruleset_generate_rule($ruleset, $chain, $ipversion,
2149 { action => 'ACCEPT',
2150 proto => 'udp', sport => 547, dport => 546 });
2151 }
76a2d1e7 2152 }
dcafc5fb 2153
ce15d90b
DM
2154 }
2155
b21aca2c
DM
2156 if ($direction eq 'OUT') {
2157 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1e9c5070 2158 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr", "-j DROP");
b21aca2c 2159 }
d7aa51ac 2160 if ($ipversion == 6 && !$options->{radv}) {
1e9c5070 2161 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-advertisement", "-j DROP");
d7aa51ac 2162 }
808d711d 2163 if ($ipfilter_ipset) {
1e9c5070 2164 ruleset_addrule($ruleset, $chain, "-m set ! --match-set $ipfilter_ipset src", "-j DROP");
808d711d 2165 }
1e9c5070 2166 ruleset_addrule($ruleset, $chain, "", "-j MARK --set-mark $FWACCEPTMARK_OFF"); # clear mark
c29f55c9 2167 }
e8415920
WB
2168
2169 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j $accept";
2170 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
9e15114a
DM
2171}
2172
4bc6b5ac 2173sub ruleset_add_group_rule {
aedde2c2 2174 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
4bc6b5ac
DM
2175
2176 my $group = $rule->{action};
2177 my $group_chain = "GROUP-$group-$direction";
2178 if(!ruleset_chain_exist($ruleset, $group_chain)){
aedde2c2 2179 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
4bc6b5ac 2180 }
bfc488f6 2181
f8b12fff 2182 if ($direction eq 'OUT' && $rule->{iface_out}) {
1e9c5070 2183 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out}", "-j $group_chain");
f8b12fff 2184 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1e9c5070 2185 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in}", "-j $group_chain");
4bc6b5ac 2186 } else {
1e9c5070 2187 ruleset_addrule($ruleset, $chain, "", "-j $group_chain");
4bc6b5ac
DM
2188 }
2189
1e9c5070 2190 ruleset_addrule($ruleset, $chain, "-m mark --mark $FWACCEPTMARK_ON", "-j $action");
4bc6b5ac
DM
2191}
2192
9e15114a 2193sub ruleset_generate_vm_rules {
84870b1a 2194 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
9e15114a
DM
2195
2196 my $lc_direction = lc($direction);
c29f55c9 2197
6b8ca015
DM
2198 my $in_accept = generate_nfqueue($options);
2199
92e976b3
DM
2200 foreach my $rule (@$rules) {
2201 next if $rule->{iface} && $rule->{iface} ne $netid;
b7ab6989 2202 next if !$rule->{enable} || $rule->{errors};
006490cb 2203 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
84870b1a 2204
92e976b3 2205 if ($rule->{type} eq 'group') {
4bc6b5ac 2206 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
aedde2c2 2207 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
92e976b3
DM
2208 } else {
2209 next if $rule->{type} ne $lc_direction;
921dfb33
DM
2210 eval {
2211 if ($direction eq 'OUT') {
88c26d5e 2212 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
e34d0e58 2213 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
e523d2bb 2214 undef, $cluster_conf, $vmfw_conf);
921dfb33 2215 } else {
88c26d5e 2216 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
e34d0e58 2217 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
e523d2bb 2218 undef, $cluster_conf, $vmfw_conf);
921dfb33
DM
2219 }
2220 };
2221 warn $@ if $@;
4e6112f9 2222 }
3a616aa0 2223 }
9e15114a
DM
2224}
2225
b47ecc88
AD
2226sub generate_nfqueue {
2227 my ($options) = @_;
2228
73089769
DM
2229 if ($options->{ips}) {
2230 my $action = "NFQUEUE";
2231 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2232 if (defined($3) && defined($1)) {
b47ecc88 2233 $action .= " --queue-balance $1:$3";
73089769 2234 } elsif (defined($1)) {
b47ecc88
AD
2235 $action .= " --queue-num $1";
2236 }
2237 }
8dc92812 2238 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
73089769
DM
2239 return $action;
2240 } else {
2241 return "ACCEPT";
b47ecc88 2242 }
b47ecc88
AD
2243}
2244
da6fc60b 2245sub ruleset_generate_vm_ipsrules {
a01c32c7 2246 my ($ruleset, $options, $direction, $iface) = @_;
da6fc60b
AD
2247
2248 if ($options->{ips} && $direction eq 'IN') {
2249 my $nfqueue = generate_nfqueue($options);
2250
a01c32c7 2251 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
da6fc60b
AD
2252 ruleset_create_chain($ruleset, "PVEFW-IPS");
2253 }
2254
1e9c5070 2255 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged", "-j $nfqueue");
da6fc60b
AD
2256 }
2257}
2258
9e15114a 2259sub generate_tap_rules_direction {
84870b1a 2260 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
9e15114a
DM
2261
2262 my $lc_direction = lc($direction);
2263
2264 my $rules = $vmfw_conf->{rules};
2265
2266 my $options = $vmfw_conf->{options};
2267 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
2268
2269 my $tapchain = "$iface-$direction";
2270
b692f42c 2271 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
88c26d5e 2272 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
74601077 2273 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
808d711d 2274
a34cfdd0 2275 # create chain with mac and ip filter
88c26d5e 2276 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
9e15114a 2277
a34cfdd0 2278 if ($options->{enable}) {
84870b1a 2279 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
3a616aa0 2280
a34cfdd0 2281 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
da6fc60b 2282
a34cfdd0
DM
2283 # implement policy
2284 my $policy;
ccae0b50 2285
a34cfdd0
DM
2286 if ($direction eq 'OUT') {
2287 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2288 } else {
72f63fde 2289 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
a34cfdd0 2290 }
ccae0b50 2291
a34cfdd0
DM
2292 my $accept = generate_nfqueue($options);
2293 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
88c26d5e 2294 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
a34cfdd0
DM
2295 } else {
2296 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : 'ACCEPT';
88c26d5e 2297 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
a34cfdd0 2298 }
3a616aa0 2299
3fa83edf 2300 # plug the tap chain to bridge chain
3cc81077 2301 if ($direction eq 'IN') {
a01c32c7 2302 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
1e9c5070 2303 "-m physdev --physdev-is-bridged --physdev-out $iface", "-j $tapchain");
3cc81077 2304 } else {
a01c32c7 2305 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
1e9c5070 2306 "-m physdev --physdev-is-bridged --physdev-in $iface", "-j $tapchain");
3cc81077 2307 }
3a616aa0
AD
2308}
2309
d18c1e2b 2310sub enable_host_firewall {
aedde2c2 2311 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
0bd5f137 2312
92e976b3 2313 my $options = $hostfw_conf->{options};
63324b09 2314 my $cluster_options = $cluster_conf->{options};
92e976b3 2315 my $rules = $hostfw_conf->{rules};
35f0c37e 2316 my $cluster_rules = $cluster_conf->{rules};
178a63be 2317
3fa83edf 2318 # host inbound firewall
dec84fcd
DM
2319 my $chain = "PVEFW-HOST-IN";
2320 ruleset_create_chain($ruleset, $chain);
0bd5f137 2321
178a63be
DM
2322 my $loglevel = get_option_log_level($options, "log_level_in");
2323
1e9c5070 2324 ruleset_addrule($ruleset, $chain, "-i lo", "-j ACCEPT");
4ac863a6 2325
e2943485 2326 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
e8415920 2327 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
88c26d5e 2328 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
fb424a00 2329
23e888f8
DM
2330 # we use RETURN because we need to check also tap rules
2331 my $accept_action = 'RETURN';
2332
1e9c5070 2333 ruleset_addrule($ruleset, $chain, "-p igmp", "-j $accept_action"); # important for multicast
cc8dc02f 2334
35f0c37e
DM
2335 # add host rules first, so that cluster wide rules can be overwritten
2336 foreach my $rule (@$rules, @$cluster_rules) {
5383df39 2337 next if !$rule->{enable} || $rule->{errors};
35d1d6da 2338 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
bfc488f6 2339
f8b12fff 2340 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
5383df39 2341
1a9978ed
DM
2342 eval {
2343 if ($rule->{type} eq 'group') {
aedde2c2 2344 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
1a9978ed 2345 } elsif ($rule->{type} eq 'in') {
88c26d5e
DM
2346 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2347 { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
e523d2bb 2348 undef, $cluster_conf, $hostfw_conf);
1a9978ed
DM
2349 }
2350 };
2351 warn $@ if $@;
f8b12fff 2352 delete $rule->{iface_in};
0bd5f137 2353 }
eb399cef
DM
2354
2355 # allow standard traffic for management ipset (includes cluster network)
88c26d5e 2356 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management", $ipversion);
708ba714 2357 my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src";
1e9c5070
TW
2358 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006", "-j $accept_action"); # PVE API
2359 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999", "-j $accept_action"); # PVE VNC Console
2360 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128", "-j $accept_action"); # SPICE Proxy
2361 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22", "-j $accept_action"); # SSH
bfc488f6 2362
afcd29b3
DM
2363 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2364 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
3bc79f87 2365
eb399cef 2366 # corosync
35d1d6da 2367 if ($localnet && ($ipversion == $localnet_ver)) {
1e9c5070
TW
2368 my $corosync_rule = "-p udp --dport 5404:5405";
2369 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule", "-j $accept_action");
2370 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule", "-j $accept_action");
3bc79f87 2371 }
0bd5f137 2372
23e888f8 2373 # implement input policy
63324b09 2374 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
88c26d5e 2375 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
0bd5f137 2376
3fa83edf 2377 # host outbound firewall
aadd745e 2378 $chain = "PVEFW-HOST-OUT";
dec84fcd
DM
2379 ruleset_create_chain($ruleset, $chain);
2380
178a63be
DM
2381 $loglevel = get_option_log_level($options, "log_level_out");
2382
1e9c5070 2383 ruleset_addrule($ruleset, $chain, "-o lo", "-j ACCEPT");
e2943485
DM
2384
2385 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2386
23e888f8
DM
2387 # we use RETURN because we may want to check other thigs later
2388 $accept_action = 'RETURN';
e8415920 2389 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j $accept_action");
23e888f8 2390
1e9c5070 2391 ruleset_addrule($ruleset, $chain, "-p igmp", "-j $accept_action"); # important for multicast
cc8dc02f 2392
35f0c37e
DM
2393 # add host rules first, so that cluster wide rules can be overwritten
2394 foreach my $rule (@$rules, @$cluster_rules) {
5383df39 2395 next if !$rule->{enable} || $rule->{errors};
35d1d6da 2396 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
5383df39 2397
f8b12fff 2398 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1a9978ed
DM
2399 eval {
2400 if ($rule->{type} eq 'group') {
aedde2c2 2401 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
1a9978ed 2402 } elsif ($rule->{type} eq 'out') {
88c26d5e
DM
2403 ruleset_generate_rule($ruleset, $chain, $ipversion,
2404 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
e523d2bb 2405 undef, $cluster_conf, $hostfw_conf);
1a9978ed
DM
2406 }
2407 };
2408 warn $@ if $@;
f8b12fff 2409 delete $rule->{iface_out};
0bd5f137
AD
2410 }
2411
3bc79f87 2412 # allow standard traffic on cluster network
35d1d6da 2413 if ($localnet && ($ipversion == $localnet_ver)) {
1e9c5070
TW
2414 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006", "-j $accept_action"); # PVE API
2415 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22", "-j $accept_action"); # SSH
2416 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999", "-j $accept_action"); # PVE VNC Console
2417 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128", "-j $accept_action"); # SPICE Proxy
bfc488f6 2418
1e9c5070
TW
2419 my $corosync_rule = "-p udp --dport 5404:5405";
2420 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule", "-j $accept_action");
2421 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule", "-j $accept_action");
3bc79f87
DM
2422 }
2423
23e888f8 2424 # implement output policy
63324b09 2425 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
88c26d5e 2426 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
6158271d 2427
1e9c5070
TW
2428 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "", "-j PVEFW-HOST-OUT");
2429 ruleset_addrule($ruleset, "PVEFW-INPUT", "", "-j PVEFW-HOST-IN");
9d31b418
AD
2430}
2431
2432sub generate_group_rules {
aedde2c2 2433 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
9d31b418 2434
c6f5cc88 2435 my $rules = $cluster_conf->{groups}->{$group};
6158271d 2436
b4deedab
DM
2437 if (!$rules) {
2438 warn "no such security group '$group'\n";
2439 $rules = []; # create empty chain
2440 }
2441
3fa83edf 2442 my $chain = "GROUP-${group}-IN";
9d31b418 2443
3fa83edf 2444 ruleset_create_chain($ruleset, $chain);
1e9c5070 2445 ruleset_addrule($ruleset, $chain, "", "-j MARK --set-mark $FWACCEPTMARK_OFF"); # clear mark
9d31b418 2446
92e976b3
DM
2447 foreach my $rule (@$rules) {
2448 next if $rule->{type} ne 'in';
aedde2c2 2449 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
88c26d5e
DM
2450 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2451 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
2452 undef, $cluster_conf);
9d31b418
AD
2453 }
2454
3fa83edf 2455 $chain = "GROUP-${group}-OUT";
9d31b418 2456
3fa83edf 2457 ruleset_create_chain($ruleset, $chain);
1e9c5070 2458 ruleset_addrule($ruleset, $chain, "", "-j MARK --set-mark $FWACCEPTMARK_OFF"); # clear mark
9d31b418 2459
92e976b3
DM
2460 foreach my $rule (@$rules) {
2461 next if $rule->{type} ne 'out';
aedde2c2 2462 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
92e976b3
DM
2463 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2464 # check also other tap rules later
88c26d5e
DM
2465 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2466 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" },
2467 undef, $cluster_conf);
9d31b418 2468 }
9d31b418
AD
2469}
2470
51bae274
DM
2471my $MAX_NETS = 32;
2472my $valid_netdev_names = {};
2473for (my $i = 0; $i < $MAX_NETS; $i++) {
2474 $valid_netdev_names->{"net$i"} = 1;
2475}
5e1267a5 2476
fe3d79b4
WB
2477sub get_mark_values {
2478 my ($value, $mask) = @_;
2479 $value = hex($value) if $value =~ /^0x/;
2480 $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
2481 $mask = 0xffffffff if !defined($mask);
2482 return ($value, $mask);
2483}
2484
51bae274 2485sub parse_fw_rule {
a523e057 2486 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
5e1267a5 2487
d4cda423
DM
2488 my $orig_line = $line;
2489
6d9246e7
DM
2490 my $rule = {};
2491
11bac5c2 2492 # we can add single line comments to the end of the rule
6d9246e7
DM
2493 if ($line =~ s/#\s*(.*?)\s*$//) {
2494 $rule->{comment} = decode('utf8', $1);
2495 }
11bac5c2
DM
2496
2497 # we can disable a rule when prefixed with '|'
ea9e5116 2498
6d9246e7 2499 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
51bae274 2500
dba740a9
DM
2501 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2502 die "unable to parse rule: $line\n";
6d9246e7
DM
2503
2504 $rule->{type} = lc($1);
2505 $rule->{action} = $2;
2506
2507 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2508 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2509 $rule->{macro} = $1;
2510 $rule->{action} = $2;
92e976b3 2511 }
51bae274
DM
2512 }
2513
dba740a9
DM
2514 while (length($line)) {
2515 if ($line =~ s/^-i (\S+)\s*//) {
6d9246e7 2516 $rule->{iface} = $1;
dba740a9
DM
2517 next;
2518 }
51bae274 2519
6d9246e7 2520 last if $rule->{type} eq 'group';
51bae274 2521
dba740a9 2522 if ($line =~ s/^-p (\S+)\s*//) {
6d9246e7 2523 $rule->{proto} = $1;
dba740a9
DM
2524 next;
2525 }
6d9246e7 2526
dba740a9 2527 if ($line =~ s/^-dport (\S+)\s*//) {
6d9246e7 2528 $rule->{dport} = $1;
dba740a9
DM
2529 next;
2530 }
6d9246e7 2531
dba740a9 2532 if ($line =~ s/^-sport (\S+)\s*//) {
6d9246e7 2533 $rule->{sport} = $1;
dba740a9
DM
2534 next;
2535 }
2536 if ($line =~ s/^-source (\S+)\s*//) {
6d9246e7 2537 $rule->{source} = $1;
dba740a9
DM
2538 next;
2539 }
2540 if ($line =~ s/^-dest (\S+)\s*//) {
6d9246e7 2541 $rule->{dest} = $1;
dba740a9
DM
2542 next;
2543 }
51bae274 2544
dba740a9
DM
2545 last;
2546 }
ba791b1f 2547
dba740a9 2548 die "unable to parse rule parameters: $line\n" if length($line);
51bae274 2549
a523e057 2550 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
eedcb564
WB
2551 if ($rule->{errors}) {
2552 # The verbose flag really means we're running from the CLI and want
2553 # output on the console - in the other case we really want such errors
2554 # to go into the syslog instead.
2555 my $log = $verbose ? sub { warn @_ } : sub { syslog(err => @_) };
2556 $log->("$prefix - errors in rule parameters: $orig_line\n");
d4cda423 2557 foreach my $p (keys %{$rule->{errors}}) {
eedcb564 2558 $log->(" $p: $rule->{errors}->{$p}\n");
d4cda423
DM
2559 }
2560 }
6d9246e7
DM
2561
2562 return $rule;
51bae274
DM
2563}
2564
2d404ffc 2565sub parse_vmfw_option {
85c6eaed
DM
2566 my ($line) = @_;
2567
2568 my ($opt, $value);
2569
178a63be
DM
2570 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2571
74601077 2572 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
9c6b6efd
DM
2573 $opt = lc($1);
2574 $value = int($2);
178a63be
DM
2575 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2576 $opt = lc($1);
2577 $value = $2 ? lc($3) : '';
72f63fde 2578 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
85c6eaed
DM
2579 $opt = lc($1);
2580 $value = uc($3);
b47ecc88
AD
2581 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2582 $opt = lc($1);
2583 $value = $2;
9c6b6efd 2584 } else {
85c6eaed
DM
2585 die "can't parse option '$line'\n"
2586 }
2587
2588 return ($opt, $value);
2589}
2590
2d404ffc
DM
2591sub parse_hostfw_option {
2592 my ($line) = @_;
2593
2594 my ($opt, $value);
2595
2596 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2597
a83abe93 2598 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2d404ffc
DM
2599 $opt = lc($1);
2600 $value = int($2);
178a63be 2601 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2d404ffc
DM
2602 $opt = lc($1);
2603 $value = $2 ? lc($3) : '';
28c082a1 2604 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
490cdead
DM
2605 $opt = lc($1);
2606 $value = int($2);
2d404ffc 2607 } else {
2d404ffc
DM
2608 die "can't parse option '$line'\n"
2609 }
2610
2611 return ($opt, $value);
2612}
2613
c6f5cc88
DM
2614sub parse_clusterfw_option {
2615 my ($line) = @_;
2616
2617 my ($opt, $value);
2618
72d055fc 2619 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
c6f5cc88
DM
2620 $opt = lc($1);
2621 $value = int($2);
72d055fc
AG
2622 if (($value > 1) && ((time() - $value) > 60)) {
2623 $value = 0
2624 }
63324b09
DM
2625 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2626 $opt = lc($1);
2627 $value = uc($3);
c6f5cc88 2628 } else {
c6f5cc88
DM
2629 die "can't parse option '$line'\n"
2630 }
2631
2632 return ($opt, $value);
2633}
2634
6c221576
DM
2635sub resolve_alias {
2636 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2637
6d959e3f 2638 my $alias = lc($cidr);
04f5088f 2639 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
6d959e3f 2640 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
6c221576 2641
6d959e3f
DM
2642 die "no such alias '$cidr'\n" if !$e;;
2643
2644 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
6c221576
DM
2645}
2646
ae029a88
DM
2647sub parse_ip_or_cidr {
2648 my ($cidr) = @_;
2649
2650 my $ipversion;
2651
2652 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2653 $cidr =~ s|/128$||;
2654 $ipversion = 6;
2655 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2656 $cidr =~ s|/32$||;
2657 $ipversion = 4;
2658 } else {
2659 die "value does not look like a valid IP address or CIDR network\n";
2660 }
2661
2662 return wantarray ? ($cidr, $ipversion) : $cidr;
2663}
2664
e76a9f53 2665sub parse_alias {
92e1209b
AD
2666 my ($line) = @_;
2667
81d574a7
DM
2668 # we can add single line comments to the end of the line
2669 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2670
92e1209b 2671 if ($line =~ m/^(\S+)\s(\S+)$/) {
81d574a7 2672 my ($name, $cidr) = ($1, $2);
ae029a88
DM
2673 my $ipversion;
2674
2675 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2676
81d574a7
DM
2677 my $data = {
2678 name => $name,
2679 cidr => $cidr,
70e524eb 2680 ipversion => $ipversion,
81d574a7
DM
2681 };
2682 $data->{comment} = $comment if $comment;
2683 return $data;
92e1209b
AD
2684 }
2685
81d574a7 2686 return undef;
92e1209b
AD
2687}
2688
e5cd1ee0 2689sub generic_fw_config_parser {
1210ae94 2690 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
5e1267a5 2691
51bae274
DM
2692 my $section;
2693 my $group;
2694
1210ae94 2695 my $res = $empty_conf;
6158271d 2696
51bae274
DM
2697 while (defined(my $line = <$fh>)) {
2698 next if $line =~ m/^#/;
2699 next if $line =~ m/^\s*$/;
2700
c8c534f7
DM
2701 chomp $line;
2702
961b4928
DM
2703 my $linenr = $fh->input_line_number();
2704 my $prefix = "$filename (line $linenr)";
2705
1210ae94 2706 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
c6f5cc88
DM
2707 $section = 'options';
2708 next;
2709 }
2710
1210ae94 2711 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
92e1209b
AD
2712 $section = 'aliases';
2713 next;
2714 }
2715
1210ae94 2716 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
c6f5cc88 2717 $section = 'groups';
92e976b3 2718 $group = lc($1);
0d22acb3 2719 my $comment = $2;
351052d1
DM
2720 eval {
2721 die "security group name too long\n" if length($group) > $max_group_name_length;
2722 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2723 };
2724 if (my $err = $@) {
2725 ($section, $group, $comment) = undef;
2726 warn "$prefix: $err";
2727 next;
2728 }
2729
c85c87f9 2730 $res->{$section}->{$group} = [];
649e4d57
DM
2731 $res->{group_comments}->{$group} = decode('utf8', $comment)
2732 if $comment;
51bae274
DM
2733 next;
2734 }
34cdedfa 2735
1210ae94 2736 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
c6f5cc88
DM
2737 $section = 'rules';
2738 next;
2739 }
cbb5d6f3 2740
1210ae94 2741 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
34cdedfa
AD
2742 $section = 'ipset';
2743 $group = lc($1);
d72c631c 2744 my $comment = $2;
351052d1
DM
2745 eval {
2746 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2747 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2748 };
2749 if (my $err = $@) {
2750 ($section, $group, $comment) = undef;
2751 warn "$prefix: $err";
2752 next;
2753 }
2754
c85c87f9 2755 $res->{$section}->{$group} = [];
e34d0e58 2756 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
649e4d57 2757 if $comment;
34cdedfa
AD
2758 next;
2759 }
2760
c6f5cc88 2761 if (!$section) {
cbb5d6f3 2762 warn "$prefix: skip line - no section\n";
51bae274
DM
2763 next;
2764 }
2765
c6f5cc88
DM
2766 if ($section eq 'options') {
2767 eval {
1210ae94
DM
2768 my ($opt, $value);
2769 if ($rule_env eq 'cluster') {
2770 ($opt, $value) = parse_clusterfw_option($line);
2771 } elsif ($rule_env eq 'host') {
2772 ($opt, $value) = parse_hostfw_option($line);
2773 } else {
2774 ($opt, $value) = parse_vmfw_option($line);
2775 }
c6f5cc88
DM
2776 $res->{options}->{$opt} = $value;
2777 };
2778 warn "$prefix: $@" if $@;
92e1209b
AD
2779 } elsif ($section eq 'aliases') {
2780 eval {
e76a9f53 2781 my $data = parse_alias($line);
81d574a7 2782 $res->{aliases}->{lc($data->{name})} = $data;
92e1209b
AD
2783 };
2784 warn "$prefix: $@" if $@;
c6f5cc88
DM
2785 } elsif ($section eq 'rules') {
2786 my $rule;
1210ae94 2787 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
c6f5cc88
DM
2788 if (my $err = $@) {
2789 warn "$prefix: $err";
2790 next;
2791 }
2792 push @{$res->{$section}}, $rule;
2793 } elsif ($section eq 'groups') {
34cdedfa 2794 my $rule;
1210ae94 2795 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); };
34cdedfa
AD
2796 if (my $err = $@) {
2797 warn "$prefix: $err";
2798 next;
2799 }
3f95d14a 2800 push @{$res->{$section}->{$group}}, $rule;
3f95d14a 2801 } elsif ($section eq 'ipset') {
9d6f90e6
DM
2802 # we can add single line comments to the end of the rule
2803 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2804
30f1b100 2805 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2a052ee3 2806 my $nomatch = $1;
9d6f90e6 2807 my $cidr = $2;
d46b1ef6
DM
2808 my $errors;
2809
2810 if ($nomatch && !$feature_ipset_nomatch) {
2811 $errors->{nomatch} = "nomatch not supported by kernel";
2812 }
2a052ee3 2813
4803b296
DM
2814 eval {
2815 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2816 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2817 } else {
ae029a88 2818 $cidr = parse_ip_or_cidr($cidr);
92e1209b 2819 }
4803b296
DM
2820 };
2821 if (my $err = $@) {
c8c534f7 2822 chomp $err;
d46b1ef6 2823 $errors->{cidr} = $err;
2a052ee3 2824 }
2a052ee3 2825
b14db52f
WB
2826 if ($cidr =~ m!/0+$!) {
2827 $errors->{cidr} = "a zero prefix is not allowed in ipset entries\n";
2828 }
2829
e34d0e58 2830 my $entry = { cidr => $cidr };
9d6f90e6
DM
2831 $entry->{nomatch} = 1 if $nomatch;
2832 $entry->{comment} = $comment if $comment;
d46b1ef6 2833 $entry->{errors} = $errors if $errors;
e34d0e58 2834
c8c534f7 2835 if ($verbose && $errors) {
9a3061c7 2836 warn "$prefix - errors in ipset '$group': $line\n";
c8c534f7
DM
2837 foreach my $p (keys %{$errors}) {
2838 warn " $p: $errors->{$p}\n";
2839 }
2840 }
2841
9d6f90e6 2842 push @{$res->{$section}->{$group}}, $entry;
1210ae94
DM
2843 } else {
2844 warn "$prefix: skip line - unknown section\n";
2845 next;
51bae274 2846 }
5e1267a5
DM
2847 }
2848
2849 return $res;
2850}
2851
e5cd1ee0 2852sub parse_hostfw_config {
1210ae94
DM
2853 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2854
2855 my $empty_conf = { rules => [], options => {}};
2856
e5cd1ee0 2857 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host');
1210ae94
DM
2858}
2859
e5cd1ee0 2860sub parse_vmfw_config {
1210ae94
DM
2861 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2862
2863 my $empty_conf = {
2864 rules => [],
2865 options => {},
2866 aliases => {},
2867 ipset => {} ,
2868 ipset_comments => {},
2869 };
2870
e5cd1ee0 2871 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
1210ae94
DM
2872}
2873
e5cd1ee0 2874sub parse_clusterfw_config {
1210ae94
DM
2875 my ($filename, $fh, $verbose) = @_;
2876
2877 my $section;
2878 my $group;
2879
2880 my $empty_conf = {
2881 rules => [],
2882 options => {},
2883 aliases => {},
2884 groups => {},
2885 group_comments => {},
2886 ipset => {} ,
2887 ipset_comments => {},
2888 };
2889
e5cd1ee0 2890 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster');
1210ae94
DM
2891}
2892
06320eb0
DM
2893sub run_locked {
2894 my ($code, @param) = @_;
2895
2896 my $timeout = 10;
2897
2898 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2899
2900 die $@ if $@;
2901
2902 return $res;
2903}
2904
5e1267a5
DM
2905sub read_local_vm_config {
2906
5e1267a5 2907 my $qemu = {};
3b4882dc 2908 my $lxc = {};
5e1267a5 2909
fdefeeab 2910 my $vmdata = { qemu => $qemu, lxc => $lxc };
5e1267a5 2911
c8301d63
DM
2912 my $vmlist = PVE::Cluster::get_vmlist();
2913 return $vmdata if !$vmlist || !$vmlist->{ids};
2914 my $ids = $vmlist->{ids};
2915
2916 foreach my $vmid (keys %$ids) {
2917 next if !$vmid; # skip VE0
2918 my $d = $ids->{$vmid};
2919 next if !$d->{node} || $d->{node} ne $nodename;
2920 next if !$d->{type};
fdefeeab 2921 if ($d->{type} eq 'qemu') {
d9fee004 2922 if ($have_qemu_server) {
b5a16dd3 2923 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
d9fee004
DM
2924 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2925 $qemu->{$vmid} = $conf;
2926 }
c8301d63 2927 }
3b4882dc
AG
2928 } elsif ($d->{type} eq 'lxc') {
2929 if ($have_lxc) {
a7c85d56 2930 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
3b4882dc
AG
2931 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2932 $lxc->{$vmid} = $conf;
2933 }
2934 }
2935 }
5e1267a5 2936 }
d9fee004 2937
5e1267a5
DM
2938 return $vmdata;
2939};
2940
e7b35711 2941sub load_vmfw_conf {
a523e057 2942 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
e7b35711
DM
2943
2944 my $vmfw_conf = {};
2945
21053409 2946 $dir = $pvefw_conf_dir if !defined($dir);
8aef5177
DM
2947
2948 my $filename = "$dir/$vmid.fw";
e7b35711 2949 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 2950 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
708ba714 2951 $vmfw_conf->{vmid} = $vmid;
e7b35711
DM
2952 }
2953
2954 return $vmfw_conf;
2955}
2956
464f933e 2957my $format_rules = sub {
dba740a9 2958 my ($rules, $allow_iface) = @_;
464f933e
DM
2959
2960 my $raw = '';
2961
2962 foreach my $rule (@$rules) {
c14dacdf 2963 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
464f933e
DM
2964 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2965 $raw .= uc($rule->{type});
7ca36671
DM
2966 if ($rule->{macro}) {
2967 $raw .= " $rule->{macro}($rule->{action})";
2968 } else {
2969 $raw .= " " . $rule->{action};
2970 }
dba740a9
DM
2971 if ($allow_iface && $rule->{iface}) {
2972 $raw .= " -i $rule->{iface}";
2973 }
c14dacdf
DM
2974
2975 if ($rule->{type} ne 'group') {
dba740a9
DM
2976 $raw .= " -source $rule->{source}" if $rule->{source};
2977 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2978 $raw .= " -p $rule->{proto}" if $rule->{proto};
2979 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2980 $raw .= " -sport $rule->{sport}" if $rule->{sport};
c14dacdf
DM
2981 }
2982
cbb5d6f3 2983 $raw .= " # " . encode('utf8', $rule->{comment})
464f933e
DM
2984 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2985 $raw .= "\n";
2986 } else {
c14dacdf 2987 die "unknown rule type '$rule->{type}'";
464f933e
DM
2988 }
2989 }
2990
2991 return $raw;
2992};
2993
2994my $format_options = sub {
68c90e21
DM
2995 my ($options) = @_;
2996
2997 my $raw = '';
464f933e
DM
2998
2999 $raw .= "[OPTIONS]\n\n";
3000 foreach my $opt (keys %$options) {
3001 $raw .= "$opt: $options->{$opt}\n";
3002 }
3003 $raw .= "\n";
68c90e21
DM
3004
3005 return $raw;
464f933e
DM
3006};
3007
0d5f0a0f
DM
3008my $format_aliases = sub {
3009 my ($aliases) = @_;
3010
3011 my $raw = '';
3012
3013 $raw .= "[ALIASES]\n\n";
3014 foreach my $k (keys %$aliases) {
81d574a7
DM
3015 my $e = $aliases->{$k};
3016 $raw .= "$e->{name} $e->{cidr}";
3017 $raw .= " # " . encode('utf8', $e->{comment})
3018 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
3019 $raw .= "\n";
0d5f0a0f
DM
3020 }
3021 $raw .= "\n";
3022
3023 return $raw;
3024};
3025
1210ae94
DM
3026my $format_ipsets = sub {
3027 my ($fw_conf) = @_;
3028
9d6f90e6
DM
3029 my $raw = '';
3030
1210ae94
DM
3031 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
3032 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
3033 my $utf8comment = encode('utf8', $comment);
3034 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
3035 } else {
3036 $raw .= "[IPSET $ipset]\n\n";
3037 }
3038 my $options = $fw_conf->{ipset}->{$ipset};
6e299ae3 3039
1210ae94
DM
3040 my $nethash = {};
3041 foreach my $entry (@$options) {
3042 $nethash->{$entry->{cidr}} = $entry;
3043 }
3044
3045 foreach my $cidr (sort keys %$nethash) {
3046 my $entry = $nethash->{$cidr};
3047 my $line = $entry->{nomatch} ? '!' : '';
3048 $line .= $entry->{cidr};
3049 $line .= " # " . encode('utf8', $entry->{comment})
3050 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
3051 $raw .= "$line\n";
3052 }
3053
3054 $raw .= "\n";
9d6f90e6 3055 }
e34d0e58 3056
9d6f90e6
DM
3057 return $raw;
3058};
3059
464f933e
DM
3060sub save_vmfw_conf {
3061 my ($vmid, $vmfw_conf) = @_;
3062
3063 my $raw = '';
3064
3065 my $options = $vmfw_conf->{options};
89ea63c8 3066 $raw .= &$format_options($options) if $options && scalar(keys %$options);
cbb5d6f3 3067
e76a9f53 3068 my $aliases = $vmfw_conf->{aliases};
89ea63c8 3069 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
e76a9f53 3070
89ea63c8 3071 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
1210ae94 3072
8824b2f0 3073 my $rules = $vmfw_conf->{rules} || [];
89ea63c8 3074 if ($rules && scalar(@$rules)) {
464f933e
DM
3075 $raw .= "[RULES]\n\n";
3076 $raw .= &$format_rules($rules, 1);
3077 $raw .= "\n";
3078 }
3079
21053409 3080 my $filename = "$pvefw_conf_dir/$vmid.fw";
c32e04e6
FG
3081 if ($raw) {
3082 mkdir $pvefw_conf_dir;
3083 PVE::Tools::file_set_contents($filename, $raw);
3084 } else {
3085 unlink $filename;
3086 }
464f933e
DM
3087}
3088
edee9035
AG
3089sub remove_vmfw_conf {
3090 my ($vmid) = @_;
3091
3092 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
3093
3094 unlink $vmfw_conffile;
3095}
3096
5471ff7c
AG
3097sub clone_vmfw_conf {
3098 my ($vmid, $newid) = @_;
3099
3100 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
3101 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
3102
3103 if (-f $clonevm_conffile) {
3104 unlink $clonevm_conffile;
3105 }
3106 if (-f $sourcevm_conffile) {
3107 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
3108 PVE::Tools::file_set_contents($clonevm_conffile, $data);
3109 }
3110}
3111
6fc63ffd 3112sub read_vm_firewall_configs {
a523e057 3113 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
8aef5177 3114
6fc63ffd 3115 my $vmfw_configs = {};
c8301d63 3116
b6b8e6ad 3117 foreach my $vmid (keys %{$vmdata->{qemu}}) {
a523e057 3118 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose);
b6b8e6ad
DM
3119 next if !$vmfw_conf->{options}; # skip if file does not exists
3120 $vmfw_configs->{$vmid} = $vmfw_conf;
3121 }
3b4882dc
AG
3122 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3123 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose);
3124 next if !$vmfw_conf->{options}; # skip if file does not exists
3125 $vmfw_configs->{$vmid} = $vmfw_conf;
3126 }
5e1267a5 3127
6fc63ffd 3128 return $vmfw_configs;
5e1267a5
DM
3129}
3130
2d404ffc
DM
3131sub get_option_log_level {
3132 my ($options, $k) = @_;
3133
3134 my $v = $options->{$k};
178a63be 3135 $v = $default_log_level if !defined($v);
2d404ffc
DM
3136
3137 return undef if $v eq '' || $v eq 'nolog';
3138
3139 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
3140
3141 return $v if ($v >= 0) && ($v <= 7);
3142
3143 warn "unknown log level ($k = '$v')\n";
3144
3145 return undef;
3146}
3147
d8f2505e 3148sub generate_std_chains {
db8a955f
DM
3149 my ($ruleset, $options, $ipversion) = @_;
3150
3151 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
cbb5d6f3 3152
2d404ffc 3153 my $loglevel = get_option_log_level($options, 'smurf_log_level');
044409e5
TW
3154 my $chain = 'PVEFW-smurflog';
3155 if ( $std_chains->{$chain} ) {
3156 foreach my $r (@{$std_chains->{$chain}}) {
3157 $r->{log} = $loglevel;
3158 }
db8a955f 3159 }
2d404ffc
DM
3160
3161 # same as shorewall logflags action.
3162 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
782c4cde 3163 $chain = 'PVEFW-logflags';
044409e5
TW
3164 if ( $std_chains->{$chain} ) {
3165 foreach my $r (@{$std_chains->{$chain}}) {
3166 $r->{log} = $loglevel;
3167 }
3168 }
d8f2505e 3169
db8a955f 3170 foreach my $chain (keys %$std_chains) {
d8f2505e 3171 ruleset_create_chain($ruleset, $chain);
db8a955f 3172 foreach my $rule (@{$std_chains->{$chain}}) {
d8f2505e 3173 if (ref($rule)) {
88c26d5e 3174 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
d8f2505e 3175 } else {
044409e5 3176 die "rule $rule as string - should not happen";
d8f2505e
DM
3177 }
3178 }
3179 }
3180}
3181
34cdedfa 3182sub generate_ipset_chains {
74601077 3183 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
34cdedfa 3184
74601077 3185 foreach my $ipset (keys %{$ipsets}) {
34cdedfa 3186
74601077 3187 my $options = $ipsets->{$ipset};
34cdedfa 3188
ebf72e49
WB
3189 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
3190 if (my $ips = $device_ips->{$1}) {
3191 $options = [@$options, @$ips];
3192 }
3193 }
3194
88c26d5e
DM
3195 # remove duplicates
3196 my $nethash = {};
3197 foreach my $entry (@$options) {
3198 next if $entry->{errors}; # skip entries with errors
3199 eval {
3200 my ($cidr, $ver);
3201 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3202 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3203 } else {
3204 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3205 }
3206 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3207 if ($ver == 6) {
e0a9139f
WB
3208 # ip_compress_address takes an address only, no CIDR
3209 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3210 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3211 $cidr .= $prefix_len if defined($prefix_len);
88c26d5e
DM
3212 $cidr =~ s|/128$||;
3213 } else {
3214 $cidr =~ s|/32$||;
3215 }
34cdedfa 3216
88c26d5e
DM
3217 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3218 };
3219 warn $@ if $@;
3220 }
6d959e3f 3221
88c26d5e
DM
3222 foreach my $ipversion (4, 6) {
3223 my $data = $nethash->{$ipversion};
30f1b100 3224
88c26d5e 3225 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
6d959e3f 3226
88c26d5e
DM
3227 my $hashsize = scalar(@$options);
3228 if ($hashsize <= 64) {
3229 $hashsize = 64;
3230 } else {
3231 $hashsize = round_powerof2($hashsize);
3232 }
6d959e3f 3233
88c26d5e 3234 my $family = $ipversion == "6" ? "inet6" : "inet";
30f1b100 3235
88c26d5e 3236 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
6d959e3f 3237
88c26d5e
DM
3238 foreach my $cidr (sort keys %$data) {
3239 my $entry = $data->{$cidr};
6d959e3f 3240
88c26d5e
DM
3241 my $cmd = "add $name $cidr";
3242 if ($entry->{nomatch}) {
3243 if ($feature_ipset_nomatch) {
3244 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3245 } else {
3246 warn "ignore !$cidr - nomatch not supported by kernel\n";
3247 }
6d959e3f 3248 } else {
88c26d5e 3249 push @{$ipset_ruleset->{$name}}, $cmd;
6d959e3f 3250 }
9d6f90e6 3251 }
9d6f90e6 3252 }
34cdedfa 3253 }
2a052ee3
AD
3254}
3255
3256sub round_powerof2 {
dd7a13fd 3257 my ($int) = @_;
2a052ee3 3258
dd7a13fd
DM
3259 $int--;
3260 $int |= $int >> $_ foreach (1,2,4,8,16);
3261 return ++$int;
34cdedfa
AD
3262}
3263
fca39c2c 3264sub load_clusterfw_conf {
d4cda423 3265 my ($filename, $verbose) = @_;
8aef5177
DM
3266
3267 $filename = $clusterfw_conf_filename if !defined($filename);
530c005e 3268
fca39c2c 3269 my $cluster_conf = {};
8aef5177 3270 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 3271 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
51bae274 3272 }
5e1267a5 3273
fca39c2c 3274 return $cluster_conf;
e5d76bde
DM
3275}
3276
fca39c2c
DM
3277sub save_clusterfw_conf {
3278 my ($cluster_conf) = @_;
9c7e0858
DM
3279
3280 my $raw = '';
9c7e0858 3281
c6f5cc88 3282 my $options = $cluster_conf->{options};
89ea63c8 3283 $raw .= &$format_options($options) if $options && scalar(keys %$options);
9c7e0858 3284
0d5f0a0f 3285 my $aliases = $cluster_conf->{aliases};
89ea63c8 3286 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
e34d0e58 3287
89ea63c8 3288 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
1210ae94 3289
c6f5cc88 3290 my $rules = $cluster_conf->{rules};
89ea63c8 3291 if ($rules && scalar(@$rules)) {
c6f5cc88 3292 $raw .= "[RULES]\n\n";
63c91681 3293 $raw .= &$format_rules($rules, 1);
c6f5cc88
DM
3294 $raw .= "\n";
3295 }
3296
89ea63c8
DM
3297 if ($cluster_conf->{groups}) {
3298 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3299 my $rules = $cluster_conf->{groups}->{$group};
3300 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3301 my $utf8comment = encode('utf8', $comment);
3302 $raw .= "[group $group] # $utf8comment\n\n";
3303 } else {
3304 $raw .= "[group $group]\n\n";
3305 }
0d22acb3 3306
89ea63c8
DM
3307 $raw .= &$format_rules($rules, 0);
3308 $raw .= "\n";
3309 }
9c7e0858
DM
3310 }
3311
c32e04e6
FG
3312 if ($raw) {
3313 mkdir $pvefw_conf_dir;
3314 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3315 } else {
3316 unlink $clusterfw_conf_filename;
3317 }
9c7e0858
DM
3318}
3319
8b27beb9 3320sub load_hostfw_conf {
a523e057 3321 my ($cluster_conf, $filename, $verbose) = @_;
8aef5177
DM
3322
3323 $filename = $hostfw_conf_filename if !defined($filename);
8b27beb9
DM
3324
3325 my $hostfw_conf = {};
8aef5177 3326 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 3327 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
8b27beb9
DM
3328 }
3329 return $hostfw_conf;
3330}
3331
63c91681
DM
3332sub save_hostfw_conf {
3333 my ($hostfw_conf) = @_;
3334
3335 my $raw = '';
3336
3337 my $options = $hostfw_conf->{options};
89ea63c8 3338 $raw .= &$format_options($options) if $options && scalar(keys %$options);
cbb5d6f3 3339
63c91681 3340 my $rules = $hostfw_conf->{rules};
89ea63c8 3341 if ($rules && scalar(@$rules)) {
63c91681
DM
3342 $raw .= "[RULES]\n\n";
3343 $raw .= &$format_rules($rules, 1);
3344 $raw .= "\n";
3345 }
3346
c32e04e6
FG
3347 if ($raw) {
3348 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3349 } else {
3350 unlink $hostfw_conf_filename;
3351 }
63c91681
DM
3352}
3353
e5d76bde 3354sub compile {
d4cda423 3355 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3dfa8a7f 3356
8aef5177
DM
3357 my $vmfw_configs;
3358
cfd7cd9c
TW
3359 # fixme: once we read standard chains from config this needs to be put in test/standard cases below
3360 $pve_std_chains = dclone($pve_std_chains_conf);
3361
8aef5177
DM
3362 if ($vmdata) { # test mode
3363 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3364 my $filename = "$testdir/cluster.fw";
d4cda423 3365 $cluster_conf = load_clusterfw_conf($filename, $verbose);
8aef5177
DM
3366
3367 $filename = "$testdir/host.fw";
a523e057 3368 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
8aef5177 3369
a523e057 3370 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
8aef5177 3371 } else { # normal operation
d4cda423 3372 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
8aef5177 3373
a523e057 3374 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
8aef5177
DM
3375
3376 $vmdata = read_local_vm_config();
a523e057 3377 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
8aef5177 3378 }
3dfa8a7f 3379
147dd882 3380 return ({},{},{}) if !$cluster_conf->{options}->{enable};
9268573a 3381
525778d7
DM
3382 my $localnet;
3383 if ($cluster_conf->{aliases}->{local_network}) {
3384 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3385 } else {
afcd29b3
DM
3386 my $localnet_ver;
3387 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3388
3389 $cluster_conf->{aliases}->{local_network} = {
3390 name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
525778d7
DM
3391 }
3392
3393 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
bfc488f6 3394
147dd882
WB
3395 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3396 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3397 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3398
3399 return ($ruleset, $ipset_ruleset, $rulesetv6);
3400}
3401
3402sub compile_iptables_filter {
3403 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
085fd492 3404
3fa83edf
DM
3405 my $ruleset = {};
3406
dec84fcd
DM
3407 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3408 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
5b1df9a0 3409
fadb13dd 3410 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
e34d0e58 3411
8b27beb9 3412 my $hostfw_options = $hostfw_conf->{options} || {};
fadb13dd 3413
88733a74
AD
3414 # fixme: what log level should we use here?
3415 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3416
097820b0 3417 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
88733a74 3418
e2943485 3419 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
88c26d5e 3420 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
e2943485 3421
1e9c5070 3422 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+", "-j PVEFW-FWBR-IN");
e2943485
DM
3423
3424 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
1e9c5070 3425 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+", "-j PVEFW-FWBR-OUT");
e2943485 3426
db8a955f 3427 generate_std_chains($ruleset, $hostfw_options, $ipversion);
fadb13dd 3428
6d2ab017 3429 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2d404ffc 3430
35d1d6da 3431 if ($hostfw_enable) {
aedde2c2 3432 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
1a9978ed
DM
3433 warn $@ if $@; # just to be sure - should not happen
3434 }
3fa83edf 3435
6158271d 3436 # generate firewall rules for QEMU VMs
0a0ba19e 3437 foreach my $vmid (sort keys %{$vmdata->{qemu}}) {
1a9978ed
DM
3438 eval {
3439 my $conf = $vmdata->{qemu}->{$vmid};
3440 my $vmfw_conf = $vmfw_configs->{$vmid};
3441 return if !$vmfw_conf;
1a9978ed 3442
0a0ba19e 3443 foreach my $netid (sort keys %$conf) {
1a9978ed
DM
3444 next if $netid !~ m/^net(\d+)$/;
3445 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3446 next if !$net->{firewall};
3447 my $iface = "tap${vmid}i$1";
3448
3449 my $macaddr = $net->{macaddr};
3450 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
84870b1a 3451 $vmfw_conf, $vmid, 'IN', $ipversion);
1a9978ed 3452 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
84870b1a 3453 $vmfw_conf, $vmid, 'OUT', $ipversion);
1a9978ed
DM
3454 }
3455 };
3456 warn $@ if $@; # just to be sure - should not happen
3fa83edf 3457 }
c8301d63 3458
3b4882dc 3459 # generate firewall rules for LXC containers
0a0ba19e 3460 foreach my $vmid (sort keys %{$vmdata->{lxc}}) {
3b4882dc
AG
3461 eval {
3462 my $conf = $vmdata->{lxc}->{$vmid};
3463 my $vmfw_conf = $vmfw_configs->{$vmid};
3464 return if !$vmfw_conf;
3465
3b4882dc 3466 if ($vmfw_conf->{options}->{enable}) {
0a0ba19e 3467 foreach my $netid (sort keys %$conf) {
3b4882dc 3468 next if $netid !~ m/^net(\d+)$/;
a7c85d56 3469 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3b4882dc
AG
3470 next if !$net->{firewall};
3471 my $iface = "veth${vmid}i$1";
3472 my $macaddr = $net->{hwaddr};
3473 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3474 $vmfw_conf, $vmid, 'IN', $ipversion);
3475 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3476 $vmfw_conf, $vmid, 'OUT', $ipversion);
3477 }
3478 }
3479 };
3480 warn $@ if $@; # just to be sure - should not happen
3481 }
3482
097820b0 3483 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
1e9c5070 3484 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED", "-j PVEFW-IPS");
097820b0
AD
3485 }
3486
147dd882
WB
3487 return $ruleset;
3488}
3489
ebf72e49
WB
3490sub mac_to_linklocal {
3491 my ($macaddr) = @_;
3492 my @parts = split(/:/, $macaddr);
3493 # The standard link local address uses the fe80::/64 prefix with the
3494 # modified EUI-64 identifier derived from the MAC address by flipping the
3495 # universal/local bit and inserting FF:FE in the middle.
3496 # See RFC 4291.
3497 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3498 my @meui64 = (@parts[0,1,2], 'ff', 'fe', @parts[3,4,5]);
3499 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3500}
3501
147dd882
WB
3502sub compile_ipsets {
3503 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3504
3505 my $localnet;
3506 if ($cluster_conf->{aliases}->{local_network}) {
3507 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3508 } else {
3509 my $localnet_ver;
3510 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3511
3512 $cluster_conf->{aliases}->{local_network} = {
3513 name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
3514 }
3515
3516 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3517
3518
3519 my $ipset_ruleset = {};
3520
3521 # generate ipsets for QEMU VMs
3522 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3523 eval {
3524 my $conf = $vmdata->{qemu}->{$vmid};
3525 my $vmfw_conf = $vmfw_configs->{$vmid};
3526 return if !$vmfw_conf;
3527
74601077
WB
3528 # When the 'ipfilter' option is enabled every device for which there
3529 # is no 'ipfilter-netX' ipset defiend gets an implicit empty default
3530 # ipset.
3531 # The reason is that ipfilter ipsets are always filled with standard
3532 # IPv6 link-local filters.
3533 my $ipsets = $vmfw_conf->{ipset};
3534 my $implicit_sets = {};
3535
ebf72e49
WB
3536 my $device_ips = {};
3537 foreach my $netid (keys %$conf) {
3538 next if $netid !~ m/^net(\d+)$/;
3539 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3540 next if !$net->{firewall};
3541
74601077
WB
3542 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3543 $implicit_sets->{"ipfilter-$netid"} = [];
3544 }
3545
ebf72e49
WB
3546 my $macaddr = $net->{macaddr};
3547 my $linklocal = mac_to_linklocal($macaddr);
3548 $device_ips->{$netid} = [
3549 { cidr => $linklocal },
3550 { cidr => 'fe80::/10', nomatch => 1 }
3551 ];
3552 }
3553
74601077
WB
3554 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3555 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
147dd882
WB
3556 };
3557 warn $@ if $@; # just to be sure - should not happen
3558 }
3559
3560 # generate firewall rules for LXC containers
3561 foreach my $vmid (keys %{$vmdata->{lxc}}) {
aa229652
WB
3562 eval {
3563 my $conf = $vmdata->{lxc}->{$vmid};
3564 my $vmfw_conf = $vmfw_configs->{$vmid};
3565 return if !$vmfw_conf;
147dd882 3566
74601077
WB
3567 # When the 'ipfilter' option is enabled every device for which there
3568 # is no 'ipfilter-netX' ipset defiend gets an implicit empty default
3569 # ipset.
3570 # The reason is that ipfilter ipsets are always filled with standard
383fe679
WB
3571 # IPv6 link-local filters, as well as the IP addresses configured
3572 # for the container.
74601077
WB
3573 my $ipsets = $vmfw_conf->{ipset};
3574 my $implicit_sets = {};
3575
ebf72e49
WB
3576 my $device_ips = {};
3577 foreach my $netid (keys %$conf) {
3578 next if $netid !~ m/^net(\d+)$/;
a7c85d56 3579 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
ebf72e49
WB
3580 next if !$net->{firewall};
3581
74601077
WB
3582 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3583 $implicit_sets->{"ipfilter-$netid"} = [];
3584 }
3585
ebf72e49
WB
3586 my $macaddr = $net->{hwaddr};
3587 my $linklocal = mac_to_linklocal($macaddr);
383fe679 3588 my $set = $device_ips->{$netid} = [
ebf72e49
WB
3589 { cidr => $linklocal },
3590 { cidr => 'fe80::/10', nomatch => 1 }
3591 ];
37ef1ce1 3592 if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
383fe679
WB
3593 push @$set, { cidr => $1 };
3594 }
37ef1ce1 3595 if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
383fe679
WB
3596 push @$set, { cidr => $1 };
3597 }
ebf72e49
WB
3598 }
3599
74601077
WB
3600 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3601 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
aa229652
WB
3602 };
3603 warn $@ if $@; # just to be sure - should not happen
147dd882
WB
3604 }
3605
74601077 3606 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
27083984 3607
147dd882 3608 return $ipset_ruleset;
3fa83edf
DM
3609}
3610
3611sub get_ruleset_status {
4bd0a9c4 3612 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3fa83edf
DM
3613
3614 my $statushash = {};
3615
3616 foreach my $chain (sort keys %$ruleset) {
4bd0a9c4 3617 my $sig = &$digest_fn($ruleset->{$chain});
9bf7d929 3618
3fa83edf
DM
3619 $statushash->{$chain}->{sig} = $sig;
3620
3621 my $oldsig = $active_chains->{$chain};
3622 if (!defined($oldsig)) {
3623 $statushash->{$chain}->{action} = 'create';
3624 } else {
3625 if ($oldsig eq $sig) {
3626 $statushash->{$chain}->{action} = 'exists';
3627 } else {
3628 $statushash->{$chain}->{action} = 'update';
3629 }
3630 }
3631 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3632 foreach my $cmd (@{$ruleset->{$chain}}) {
3633 print "\t$cmd\n" if $verbose;
3634 }
3635 }
3636
3637 foreach my $chain (sort keys %$active_chains) {
3638 if (!defined($ruleset->{$chain})) {
3639 my $sig = $active_chains->{$chain};
3640 $statushash->{$chain}->{action} = 'delete';
3641 $statushash->{$chain}->{sig} = $sig;
3642 print "delete $chain ($sig)\n" if $verbose;
3643 }
6158271d 3644 }
2a052ee3 3645
3fa83edf
DM
3646 return $statushash;
3647}
3648
3fa83edf
DM
3649sub print_sig_rule {
3650 my ($chain, $sig) = @_;
3651
09d5f68e
DM
3652 # We just use this to store a SHA1 checksum used to detect changes
3653 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
b6360c3f
DM
3654}
3655
df7cb349 3656sub get_ruleset_cmdlist {
17da5c0f 3657 my ($ruleset, $verbose, $iptablescmd) = @_;
3fa83edf 3658
3fa83edf 3659 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
cbb5d6f3 3660
17da5c0f 3661 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
4bd0a9c4 3662 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3fa83edf
DM
3663
3664 # create missing chains first
3665 foreach my $chain (sort keys %$ruleset) {
3666 my $stat = $statushash->{$chain};
3667 die "internal error" if !$stat;
3668 next if $stat->{action} ne 'create';
886aba9c 3669
3fa83edf
DM
3670 $cmdlist .= ":$chain - [0:0]\n";
3671 }
3672
4bd0a9c4 3673 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
55fad3b7
DM
3674 my $chain = "PVEFW-$h";
3675 if ($ruleset->{$chain} && !$hooks->{$h}) {
3676 $cmdlist .= "-A $h -j $chain\n";
4bd0a9c4 3677 }
3fa83edf
DM
3678 }
3679
3680 foreach my $chain (sort keys %$ruleset) {
3681 my $stat = $statushash->{$chain};
3682 die "internal error" if !$stat;
3683
3684 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
3685 $cmdlist .= "-F $chain\n";
3686 foreach my $cmd (@{$ruleset->{$chain}}) {
3687 $cmdlist .= "$cmd\n";
3688 }
3689 $cmdlist .= print_sig_rule($chain, $stat->{sig});
3690 } elsif ($stat->{action} eq 'delete') {
f5d28682 3691 die "internal error"; # this should not happen
3fa83edf
DM
3692 } elsif ($stat->{action} eq 'exists') {
3693 # do nothing
3694 } else {
3695 die "internal error - unknown status '$stat->{action}'";
3696 }
3697 }
3698
f5d28682
DM
3699 foreach my $chain (keys %$statushash) {
3700 next if $statushash->{$chain}->{action} ne 'delete';
3701 $cmdlist .= "-F $chain\n";
3702 }
3703 foreach my $chain (keys %$statushash) {
3704 next if $statushash->{$chain}->{action} ne 'delete';
fadb13dd
DM
3705 next if $chain eq 'PVEFW-INPUT';
3706 next if $chain eq 'PVEFW-OUTPUT';
3707 next if $chain eq 'PVEFW-FORWARD';
f5d28682
DM
3708 $cmdlist .= "-X $chain\n";
3709 }
3710
3f95d14a 3711 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
4bd0a9c4 3712
3fa83edf
DM
3713 $cmdlist .= "COMMIT\n";
3714
3f95d14a 3715 return wantarray ? ($cmdlist, $changes) : $cmdlist;
6b9f68a2
DM
3716}
3717
34cdedfa 3718sub get_ipset_cmdlist {
dd7a13fd 3719 my ($ruleset, $verbose) = @_;
34cdedfa
AD
3720
3721 my $cmdlist = "";
3722
dd7a13fd
DM
3723 my $delete_cmdlist = "";
3724
4bd0a9c4
DM
3725 my $active_chains = ipset_get_chains();
3726 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
34cdedfa 3727
e34d0e58 3728 # remove stale _swap chains
30f1b100
DM
3729 foreach my $chain (keys %$active_chains) {
3730 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3731 $cmdlist .= "destroy $chain\n";
3732 }
3733 }
3734
c69cf614 3735 foreach my $chain (keys %$ruleset) {
c69cf614
DM
3736 my $stat = $statushash->{$chain};
3737 die "internal error" if !$stat;
3738
3739 if ($stat->{action} eq 'create') {
3740 foreach my $cmd (@{$ruleset->{$chain}}) {
3741 $cmdlist .= "$cmd\n";
3742 }
3743 }
3744 }
3745
3746 foreach my $chain (keys %$ruleset) {
6d959e3f
DM
3747 my $stat = $statushash->{$chain};
3748 die "internal error" if !$stat;
34cdedfa 3749
dd7a13fd
DM
3750 if ($stat->{action} eq 'update') {
3751 my $chain_swap = $chain."_swap";
cbb5d6f3 3752
dd7a13fd
DM
3753 foreach my $cmd (@{$ruleset->{$chain}}) {
3754 $cmd =~ s/$chain/$chain_swap/;
3755 $cmdlist .= "$cmd\n";
34cdedfa 3756 }
dd7a13fd
DM
3757 $cmdlist .= "swap $chain_swap $chain\n";
3758 $cmdlist .= "flush $chain_swap\n";
3759 $cmdlist .= "destroy $chain_swap\n";
2a052ee3 3760 }
dd7a13fd 3761 }
3f95d14a 3762
88c26d5e 3763 # the remove unused chains
c69cf614 3764 foreach my $chain (keys %$statushash) {
dd7a13fd 3765 next if $statushash->{$chain}->{action} ne 'delete';
2a052ee3 3766
dd7a13fd
DM
3767 $delete_cmdlist .= "flush $chain\n";
3768 $delete_cmdlist .= "destroy $chain\n";
34cdedfa
AD
3769 }
3770
dd7a13fd 3771 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
cbb5d6f3 3772
dd7a13fd 3773 return ($cmdlist, $delete_cmdlist, $changes);
34cdedfa
AD
3774}
3775
6b9f68a2 3776sub apply_ruleset {
17da5c0f 3777 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
6b9f68a2
DM
3778
3779 enable_bridge_firewall();
3780
cbb5d6f3 3781 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
9a462317 3782 get_ipset_cmdlist($ipset_ruleset, $verbose);
6b9f68a2 3783
81a0bf43 3784 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
17da5c0f 3785 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
2a052ee3 3786
81a0bf43
DM
3787 if ($verbose) {
3788 if ($ipset_changes) {
3789 print "ipset changes:\n";
3790 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3791 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3792 }
3f95d14a 3793
81a0bf43
DM
3794 if ($changes) {
3795 print "iptables changes:\n";
3796 print $cmdlist;
3797 }
17da5c0f
AD
3798
3799 if ($changesv6) {
3800 print "ip6tables changes:\n";
3801 print $cmdlistv6;
3802 }
81a0bf43 3803 }
3fa83edf 3804
259db1e6
DM
3805 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3806 PVE::Tools::file_set_contents($tmpfile, $ipset_create_cmdlist || '');
3807
2a052ee3 3808 ipset_restore_cmdlist($ipset_create_cmdlist);
34cdedfa 3809
259db1e6
DM
3810 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3811 PVE::Tools::file_set_contents($tmpfile, $cmdlist || '');
3812
3fa83edf 3813 iptables_restore_cmdlist($cmdlist);
259db1e6
DM
3814
3815 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3816 PVE::Tools::file_set_contents($tmpfile, $cmdlistv6 || '');
3817
17da5c0f 3818 ip6tables_restore_cmdlist($cmdlistv6);
3fa83edf 3819
259db1e6
DM
3820 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3821 PVE::Tools::file_set_contents($tmpfile, $ipset_delete_cmdlist || '');
3822
dd7a13fd 3823 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2a052ee3 3824
6158271d 3825 # test: re-read status and check if everything is up to date
4bd0a9c4 3826 my $active_chains = iptables_get_chains();
81a0bf43 3827 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3fa83edf
DM
3828
3829 my $errors;
3830 foreach my $chain (sort keys %$ruleset) {
3831 my $stat = $statushash->{$chain};
3832 if ($stat->{action} ne 'exists') {
3833 warn "unable to update chain '$chain'\n";
3834 $errors = 1;
3835 }
3836 }
b6360c3f 3837
17da5c0f
AD
3838 my $active_chainsv6 = iptables_get_chains("ip6tables");
3839 my $statushashv6 = get_ruleset_status($rulesetv6, $active_chainsv6, \&iptables_chain_digest, 0);
3840
3841 foreach my $chain (sort keys %$rulesetv6) {
3842 my $stat = $statushashv6->{$chain};
3843 if ($stat->{action} ne 'exists') {
3844 warn "unable to update chain '$chain'\n";
3845 $errors = 1;
3846 }
3847 }
3848
3fa83edf 3849 die "unable to apply firewall changes\n" if $errors;
46a2ac1f
AD
3850
3851 update_nf_conntrack_max($hostfw_conf);
3852
3853 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
3854
b6360c3f
DM
3855}
3856
490cdead
DM
3857sub update_nf_conntrack_max {
3858 my ($hostfw_conf) = @_;
3859
3860 my $max = 65536; # reasonable default
3861
3862 my $options = $hostfw_conf->{options} || {};
3863
3864 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3865 $max = $options->{nf_conntrack_max};
3866 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3867 }
3868
3869 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3870 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3871
3872 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3873
3874 if ($current != $max) {
3875 my $hashsize = int($max/4);
3876 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3877 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3878 }
3879}
3880
28c082a1
AD
3881sub update_nf_conntrack_tcp_timeout_established {
3882 my ($hostfw_conf) = @_;
3883
3884 my $options = $hostfw_conf->{options} || {};
3885
3886 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3887
3888 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3889}
3890
c4a2e5ae
DM
3891sub remove_pvefw_chains {
3892
7b7b2654
AD
3893 PVE::Firewall::remove_pvefw_chains_iptables("iptables");
3894 PVE::Firewall::remove_pvefw_chains_iptables("ip6tables");
3895 PVE::Firewall::remove_pvefw_chains_ipset();
3896
3897}
3898
3899sub remove_pvefw_chains_iptables {
3900 my ($iptablescmd) = @_;
3901
3902 my ($chash, $hooks) = iptables_get_chains($iptablescmd);
c4a2e5ae
DM
3903 my $cmdlist = "*filter\n";
3904
3905 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3906 if ($hooks->{$h}) {
3907 $cmdlist .= "-D $h -j PVEFW-$h\n";
3908 }
3909 }
cbb5d6f3 3910
c4a2e5ae
DM
3911 foreach my $chain (keys %$chash) {
3912 $cmdlist .= "-F $chain\n";
3913 }
3914
3915 foreach my $chain (keys %$chash) {
3916 $cmdlist .= "-X $chain\n";
3917 }
3918 $cmdlist .= "COMMIT\n";
3919
7b7b2654
AD
3920 if($iptablescmd eq "ip6tables") {
3921 ip6tables_restore_cmdlist($cmdlist);
3922 } else {
3923 iptables_restore_cmdlist($cmdlist);
3924 }
3925}
3926
3927sub remove_pvefw_chains_ipset {
55fad3b7
DM
3928
3929 my $ipset_chains = ipset_get_chains();
3930
7b7b2654 3931 my $cmdlist = "";
55fad3b7
DM
3932
3933 foreach my $chain (keys %$ipset_chains) {
88c26d5e
DM
3934 $cmdlist .= "flush $chain\n";
3935 $cmdlist .= "destroy $chain\n";
55fad3b7
DM
3936 }
3937
7b7b2654 3938 ipset_restore_cmdlist($cmdlist) if $cmdlist;
c4a2e5ae
DM
3939}
3940
8b453a09
DM
3941sub init {
3942 my $cluster_conf = load_clusterfw_conf();
3943 my $cluster_options = $cluster_conf->{options};
3944 my $enable = $cluster_options->{enable};
3945
3946 return if !$enable;
3947
3948 # load required modules here
3949}
3950
6b9f68a2 3951sub update {
6b9f68a2 3952 my $code = sub {
3dfa8a7f
DM
3953
3954 my $cluster_conf = load_clusterfw_conf();
3955 my $cluster_options = $cluster_conf->{options};
3956
55fad3b7 3957 if (!$cluster_options->{enable}) {
b22130d3 3958 PVE::Firewall::remove_pvefw_chains();
3dfa8a7f
DM
3959 return;
3960 }
3961
50f9a28d 3962 my $hostfw_conf = load_hostfw_conf($cluster_conf);
3dfa8a7f 3963
638c755a 3964 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile($cluster_conf, $hostfw_conf);
490cdead 3965
17da5c0f 3966 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);
6b9f68a2
DM
3967 };
3968
3969 run_locked($code);
3970}
3971
b6360c3f 39721;