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