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