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