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