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