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