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