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