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