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