]> git.proxmox.com Git - pve-firewall.git/blame - src/PVE/Firewall.pm
allow to read rule with errors
[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 857 $data->{$k} = $v;
6d9246e7
DM
858 # Note: digest ignores refs ($rule->{errors})
859 $sha->add($k, ':', $v, "\n") if !ref($v); ;
5d38d64f
DM
860 }
861 push @$res, $data;
862 }
863
55e686c7 864 my $digest = $sha->hexdigest;
5d38d64f
DM
865
866 foreach my $entry (@$res) {
867 $entry->{digest} = $digest;
868 }
869
870 return wantarray ? ($res, $digest) : $res;
871}
872
9c7e0858
DM
873my $rule_properties = {
874 pos => {
875 description => "Update rule at position <pos>.",
876 type => 'integer',
877 minimum => 0,
878 optional => 1,
879 },
c71e785f 880 digest => get_standard_option('pve-config-digest'),
9c7e0858
DM
881 type => {
882 type => 'string',
883 optional => 1,
884 enum => ['in', 'out', 'group'],
885 },
886 action => {
c14dacdf 887 description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
9c7e0858
DM
888 type => 'string',
889 optional => 1,
44be8ceb 890 pattern => $security_group_name_pattern,
c14dacdf
DM
891 maxLength => 20,
892 minLength => 2,
9c7e0858 893 },
e5076eee
DM
894 macro => {
895 type => 'string',
896 optional => 1,
54cd19a8 897 maxLength => 128,
e5076eee 898 },
54cd19a8 899 iface => get_standard_option('pve-iface', { optional => 1 }),
9c7e0858 900 source => {
54cd19a8 901 type => 'string', format => 'pve-fw-v4addr-spec',
9c7e0858
DM
902 optional => 1,
903 },
904 dest => {
54cd19a8 905 type => 'string', format => 'pve-fw-v4addr-spec',
9c7e0858
DM
906 optional => 1,
907 },
908 proto => {
54cd19a8 909 type => 'string', format => 'pve-fw-protocol-spec',
9c7e0858
DM
910 optional => 1,
911 },
912 enable => {
913 type => 'boolean',
914 optional => 1,
915 },
916 sport => {
54cd19a8 917 type => 'string', format => 'pve-fw-port-spec',
9c7e0858
DM
918 optional => 1,
919 },
920 dport => {
54cd19a8 921 type => 'string', format => 'pve-fw-port-spec',
9c7e0858
DM
922 optional => 1,
923 },
924 comment => {
925 type => 'string',
926 optional => 1,
927 },
928};
929
930sub add_rule_properties {
931 my ($properties) = @_;
932
933 foreach my $k (keys %$rule_properties) {
3655b01f
DM
934 my $h = $rule_properties->{$k};
935 # copy data, so that we can modify later without side effects
936 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
9c7e0858 937 }
cbb5d6f3 938
9c7e0858
DM
939 return $properties;
940}
941
5b7974df
DM
942sub delete_rule_properties {
943 my ($rule, $delete_str) = @_;
e34d0e58 944
5b7974df
DM
945 foreach my $opt (PVE::Tools::split_list($delete_str)) {
946 raise_param_exc({ 'delete' => "no such property ('$opt')"})
947 if !defined($rule_properties->{$opt});
948 raise_param_exc({ 'delete' => "unable to delete required property '$opt'"})
949 if $opt eq 'type' || $opt eq 'action';
950 delete $rule->{$opt};
951 }
952
953 return $rule;
954}
955
9a2745a0
DM
956my $apply_macro = sub {
957 my ($macro_name, $param, $verify) = @_;
958
959 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
960 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
961
962 my $rules = [];
963
964 foreach my $templ (@$macro_rules) {
965 my $rule = {};
966 my $param_used = {};
967 foreach my $k (keys %$templ) {
968 my $v = $templ->{$k};
969 if ($v eq 'PARAM') {
970 $v = $param->{$k};
971 $param_used->{$k} = 1;
972 } elsif ($v eq 'DEST') {
973 $v = $param->{dest};
974 $param_used->{dest} = 1;
975 } elsif ($v eq 'SOURCE') {
976 $v = $param->{source};
977 $param_used->{source} = 1;
978 }
979
980 if (!defined($v)) {
981 my $msg = "missing parameter '$k' in macro '$macro_name'";
e34d0e58 982 raise_param_exc({ macro => $msg }) if $verify;
9a2745a0
DM
983 die "$msg\n";
984 }
985 $rule->{$k} = $v;
986 }
987 foreach my $k (keys %$param) {
988 next if $k eq 'macro';
989 next if !defined($param->{$k});
990 next if $param_used->{$k};
991 if (defined($rule->{$k})) {
992 if ($rule->{$k} ne $param->{$k}) {
993 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
e34d0e58 994 raise_param_exc({ $k => $msg }) if $verify;
9a2745a0
DM
995 die "$msg\n";
996 }
997 } else {
998 $rule->{$k} = $param->{$k};
999 }
1000 }
1001 push @$rules, $rule;
1002 }
1003
1004 return $rules;
1005};
1006
7ca36671 1007sub verify_rule {
6d9246e7 1008 my ($rule, $allow_groups, $noerr) = @_;
7ca36671 1009
6d9246e7
DM
1010 my $errors = {};
1011 my $error_count = 0;
7ca36671 1012
6d9246e7
DM
1013 my $add_error = sub {
1014 my ($param, $msg) = @_;
1015 raise_param_exc({ $param => $msg }) if !$noerr;
1016 $error_count++;
1017 $errors->{$param} = $msg if !$errors->{$param};
1018 };
1019
1020 my $type = $rule->{type};
1021 my $action = $rule->{action};
1022
1023 &$add_error('type', "missing property") if !$type;
1024 &$add_error('action', "missing property") if !$action;
1025
1026 if ($type) {
1027 if ($type eq 'in' || $type eq 'out') {
1028 &$add_error('action', "unknown action '$action'")
1029 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1030 } elsif ($type eq 'group') {
1031 &$add_error('type', "security groups not allowed")
1032 if !$allow_groups;
1033 &$add_error('action', "invalid characters in security group name")
1034 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1035 } else {
1036 &$add_error('type', "unknown rule type '$type'");
1037 }
7ca36671 1038 }
e34d0e58 1039
dba740a9
DM
1040 if ($rule->{iface}) {
1041 eval { PVE::JSONSchema::pve_verify_iface($rule->{iface}); };
6d9246e7 1042 &$add_error('iface', $@) if $@;
dba740a9 1043 }
7ca36671
DM
1044
1045 if ($rule->{macro}) {
6d9246e7
DM
1046 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1047 $rule->{macro} = $preferred_name;
1048 } else {
1049 &$add_error('macro', "unknown macro '$rule->{macro}'");
1050 }
1051 }
1052
1053 if ($rule->{proto}) {
1054 eval { pve_fw_verify_protocol_spec($rule->{proto}); };
1055 &$add_error('proto', $@) if $@;
1056 }
7ca36671
DM
1057
1058 if ($rule->{dport}) {
1059 eval { parse_port_name_number_or_range($rule->{dport}); };
6d9246e7
DM
1060 &$add_error('dport', $@) if $@;
1061 &$add_error('proto', "missing property - 'dport' requires this property")
914f9a50 1062 if !$rule->{proto};
6d9246e7 1063 }
7ca36671
DM
1064
1065 if ($rule->{sport}) {
1066 eval { parse_port_name_number_or_range($rule->{sport}); };
6d9246e7
DM
1067 &$add_error('sport', $@) if $@;
1068 &$add_error('proto', "missing property - 'sport' requires this property")
914f9a50 1069 if !$rule->{proto};
7ca36671
DM
1070 }
1071
1072 if ($rule->{source}) {
1073 eval { parse_address_list($rule->{source}); };
6d9246e7 1074 &$add_error('source', $@) if $@;
7ca36671
DM
1075 }
1076
1077 if ($rule->{dest}) {
1078 eval { parse_address_list($rule->{dest}); };
6d9246e7 1079 &$add_error('dest', $@) if $@;
7ca36671
DM
1080 }
1081
9a2745a0 1082 if ($rule->{macro}) {
6d9246e7
DM
1083 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1084 if (my $err = $@) {
1085 if (ref($err) eq "PVE::Exception" && $err->{errors}) {
1086 my $eh = $err->{errors};
1087 foreach my $p (keys %$eh) {
1088 &$add_error($p, $eh->{$p});
1089 }
1090 } else {
1091 &$add_error('macro', "$err");
1092 }
1093 }
9a2745a0
DM
1094 }
1095
6d9246e7
DM
1096 $rule->{errors} = $errors if $error_count;
1097
7ca36671
DM
1098 return $rule;
1099}
1100
9c7e0858
DM
1101sub copy_rule_data {
1102 my ($rule, $param) = @_;
1103
1104 foreach my $k (keys %$rule_properties) {
1105 if (defined(my $v = $param->{$k})) {
1106 if ($v eq '' || $v eq '-') {
1107 delete $rule->{$k};
1108 } else {
1109 $rule->{$k} = $v;
1110 }
9c7e0858
DM
1111 }
1112 }
7ca36671 1113
9c7e0858
DM
1114 return $rule;
1115}
1116
1117# core functions
780bcc0f
DM
1118my $bridge_firewall_enabled = 0;
1119
1120sub enable_bridge_firewall {
1121
1122 return if $bridge_firewall_enabled; # only once
1123
5f0a912c
DM
1124 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1125 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
780bcc0f 1126
6a8a75db
DM
1127 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1128 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
1129
780bcc0f
DM
1130 $bridge_firewall_enabled = 1;
1131}
1132
8cebfa6f 1133my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
dddd9413 1134
b16e818e
DM
1135sub iptables_restore_cmdlist {
1136 my ($cmdlist) = @_;
3a616aa0 1137
3fa83edf 1138 run_command("/sbin/iptables-restore -n", input => $cmdlist);
3a616aa0
AD
1139}
1140
34cdedfa
AD
1141sub ipset_restore_cmdlist {
1142 my ($cmdlist) = @_;
1143
dd7a13fd 1144 run_command("/usr/sbin/ipset restore", input => $cmdlist);
34cdedfa
AD
1145}
1146
de2a57cd
DM
1147sub iptables_get_chains {
1148
1149 my $res = {};
1150
1151 # check what chains we want to track
1152 my $is_pvefw_chain = sub {
1153 my $name = shift;
1154
dec84fcd
DM
1155 return 1 if $name =~ m/^PVEFW-\S+$/;
1156
de2a57cd 1157 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
954f24b1
DM
1158
1159 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1160
9e15114a
DM
1161 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1162
a01c32c7 1163 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
f50656c2 1164 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
de2a57cd
DM
1165
1166 return undef;
1167 };
1168
1169 my $table = '';
1170
c4a2e5ae
DM
1171 my $hooks = {};
1172
de2a57cd
DM
1173 my $parser = sub {
1174 my $line = shift;
1175
1176 return if $line =~ m/^#/;
1177 return if $line =~ m/^\s*$/;
1178
1179 if ($line =~ m/^\*(\S+)$/) {
1180 $table = $1;
1181 return;
1182 }
1183
1184 return if $table ne 'filter';
1185
1186 if ($line =~ m/^:(\S+)\s/) {
1187 my $chain = $1;
1188 return if !&$is_pvefw_chain($chain);
3fa83edf 1189 $res->{$chain} = "unknown";
09d5f68e 1190 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
3fa83edf 1191 my ($chain, $sig) = ($1, $2);
de2a57cd 1192 return if !&$is_pvefw_chain($chain);
3fa83edf 1193 $res->{$chain} = $sig;
c4a2e5ae
DM
1194 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1195 $hooks->{$1} = 1;
de2a57cd
DM
1196 } else {
1197 # simply ignore the rest
1198 return;
1199 }
1200 };
1201
1202 run_command("/sbin/iptables-save", outfunc => $parser);
1203
c4a2e5ae 1204 return wantarray ? ($res, $hooks) : $res;
de2a57cd
DM
1205}
1206
9bf7d929
DM
1207sub iptables_chain_digest {
1208 my ($rules) = @_;
1209 my $digest = Digest::SHA->new('sha1');
1210 foreach my $rule (@$rules) { # order is important
1211 $digest->add($rule);
1212 }
1213 return $digest->b64digest;
1214}
1215
3f95d14a
DM
1216sub ipset_chain_digest {
1217 my ($rules) = @_;
4bd0a9c4 1218
3f95d14a
DM
1219 my $digest = Digest::SHA->new('sha1');
1220 foreach my $rule (sort @$rules) { # note: sorted
1221 $digest->add($rule);
1222 }
1223 return $digest->b64digest;
1224}
1225
34cdedfa
AD
1226sub ipset_get_chains {
1227
1228 my $res = {};
1229 my $chains = {};
1230
1231 my $parser = sub {
1232 my $line = shift;
1233
1234 return if $line =~ m/^#/;
1235 return if $line =~ m/^\s*$/;
4b96e877 1236 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
81a0bf43
DM
1237 my $chain = $1;
1238 $line =~ s/\s+$//; # delete trailing white space
1239 push @{$chains->{$chain}}, $line;
34cdedfa
AD
1240 } else {
1241 # simply ignore the rest
1242 return;
1243 }
1244 };
1245
3f95d14a 1246 run_command("/usr/sbin/ipset save", outfunc => $parser);
34cdedfa 1247
3f95d14a
DM
1248 # compute digest for each chain
1249 foreach my $chain (keys %$chains) {
1250 $res->{$chain} = ipset_chain_digest($chains->{$chain});
34cdedfa
AD
1251 }
1252
1253 return $res;
1254}
1255
eba0fb64 1256sub ruleset_generate_cmdstr {
ba791b1f 1257 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
3a616aa0 1258
00bb4391 1259 return if defined($rule->{enable}) && !$rule->{enable};
6d9246e7 1260 return if $rule->{errors};
11bac5c2 1261
e5076eee
DM
1262 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1263
1264 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
1265 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
e5076eee 1266
41524a58 1267 my @cmd = ();
3a616aa0 1268
eba0fb64
DM
1269 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1270 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1271
ba791b1f
AD
1272 my $source = $rule->{source};
1273 my $dest = $rule->{dest};
1274
cbb5d6f3 1275 if ($source) {
44be8ceb
DM
1276 if ($source =~ m/^\+/) {
1277 if ($source =~ m/^\+(${security_group_name_pattern})$/) {
1278 die "no such ipset '$1'\n" if !$cluster_conf->{ipset}->{$1};
1279 push @cmd, "-m set --match-set PVEFW-$1 src";
1280 } else {
1281 die "invalid security group name '$source'\n";
1282 }
1283 } elsif ($source =~ m/^${ip_alias_pattern}$/){
81d574a7
DM
1284 my $alias = lc($source);
1285 my $e = $cluster_conf->{aliases}->{$alias};
1286 die "no such alias $source\n" if !$e;
1287 push @cmd, "-s $e->{cidr}";
ac8242cc 1288 } elsif ($source =~ m/\-/){
ba791b1f
AD
1289 push @cmd, "-m iprange --src-range $source";
1290
cbb5d6f3 1291 } else {
ba791b1f
AD
1292 push @cmd, "-s $source";
1293 }
1294 }
1295
cbb5d6f3 1296 if ($dest) {
44be8ceb
DM
1297 if ($dest =~ m/^\+/) {
1298 if ($dest =~ m/^\+(${security_group_name_pattern})$/) {
1299 die "no such ipset '$1'\n" if !$cluster_conf->{ipset}->{$1};
1300 push @cmd, "-m set --match-set PVEFW-$1 dst";
1301 } else {
1302 die "invalid security group name '$dest'\n";
1303 }
1304 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
51b40846 1305 my $alias = lc($dest);
81d574a7
DM
1306 my $e = $cluster_conf->{aliases}->{$alias};
1307 die "no such alias $dest" if !$e;
1308 push @cmd, "-d $e->{cidr}";
cbb5d6f3 1309 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
ba791b1f
AD
1310 push @cmd, "-m iprange --dst-range $dest";
1311
cbb5d6f3 1312 } else {
d6d2a385 1313 push @cmd, "-d $dest";
ba791b1f
AD
1314 }
1315 }
4b586518 1316
181390b0 1317 if ($rule->{proto}) {
41524a58 1318 push @cmd, "-p $rule->{proto}";
e3a1d391 1319
181390b0 1320 my $multiport = 0;
e5076eee
DM
1321 $multiport++ if $nbdport > 1;
1322 $multiport++ if $nbsport > 1;
e3a1d391 1323
41524a58 1324 push @cmd, "--match multiport" if $multiport;
4b586518 1325
cbb5d6f3 1326 die "multiport: option '--sports' cannot be used together with '--dports'\n"
181390b0
DM
1327 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1328
1329 if ($rule->{dport}) {
1330 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
1331 # Note: we use dport to store --icmp-type
1332 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
41524a58 1333 push @cmd, "-m icmp --icmp-type $rule->{dport}";
181390b0 1334 } else {
e5076eee 1335 if ($nbdport > 1) {
181390b0 1336 if ($multiport == 2) {
41524a58 1337 push @cmd, "--ports $rule->{dport}";
181390b0 1338 } else {
41524a58 1339 push @cmd, "--dports $rule->{dport}";
181390b0 1340 }
e3a1d391 1341 } else {
41524a58 1342 push @cmd, "--dport $rule->{dport}";
e3a1d391 1343 }
4b586518
DM
1344 }
1345 }
4b586518 1346
181390b0 1347 if ($rule->{sport}) {
e5076eee 1348 if ($nbsport > 1) {
41524a58 1349 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
181390b0 1350 } else {
41524a58 1351 push @cmd, "--sport $rule->{sport}";
181390b0 1352 }
4b586518 1353 }
181390b0 1354 } elsif ($rule->{dport} || $rule->{sport}) {
93d96f83
DM
1355 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1356 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
4b586518
DM
1357 }
1358
41524a58 1359 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
4e6112f9
DM
1360
1361 if (my $action = $rule->{action}) {
cbb5d6f3 1362 $action = $actions->{$action} if defined($actions->{$action});
4e6112f9 1363 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
41524a58 1364 push @cmd, $goto ? "-g $action" : "-j $action";
181390b0 1365 }
3a616aa0 1366
eba0fb64
DM
1367 return scalar(@cmd) ? join(' ', @cmd) : undef;
1368}
1369
1370sub ruleset_generate_rule {
ba791b1f 1371 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
eba0fb64 1372
e5076eee
DM
1373 my $rules;
1374
1375 if ($rule->{macro}) {
1376 $rules = &$apply_macro($rule->{macro}, $rule);
1377 } else {
1378 $rules = [ $rule ];
1379 }
1380
d4091b82
DM
1381 # update all or nothing
1382
1383 my @cmds = ();
cbb5d6f3 1384 foreach my $tmp (@$rules) {
ba791b1f 1385 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
d4091b82 1386 push @cmds, $cmdstr;
e5076eee 1387 }
41524a58 1388 }
d4091b82
DM
1389
1390 foreach my $cmdstr (@cmds) {
1391 ruleset_addrule($ruleset, $chain, $cmdstr);
1392 }
3fa83edf 1393}
0f168d7b 1394
eba0fb64
DM
1395sub ruleset_generate_rule_insert {
1396 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1397
e5076eee
DM
1398 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1399
eba0fb64
DM
1400 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
1401 ruleset_insertrule($ruleset, $chain, $cmdstr);
1402 }
1403}
3fa83edf
DM
1404
1405sub ruleset_create_chain {
1406 my ($ruleset, $chain) = @_;
3a616aa0 1407
d050c724 1408 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
782c4cde 1409 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
d050c724 1410
3fa83edf
DM
1411 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1412
1413 $ruleset->{$chain} = [];
3a616aa0
AD
1414}
1415
3fa83edf
DM
1416sub ruleset_chain_exist {
1417 my ($ruleset, $chain) = @_;
3a616aa0 1418
3fa83edf
DM
1419 return $ruleset->{$chain} ? 1 : undef;
1420}
3a616aa0 1421
3fa83edf
DM
1422sub ruleset_addrule {
1423 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1424
3fa83edf 1425 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1426
3fa83edf
DM
1427 push @{$ruleset->{$chain}}, "-A $chain $rule";
1428}
3a616aa0 1429
3fa83edf
DM
1430sub ruleset_insertrule {
1431 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1432
3fa83edf 1433 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1434
3fa83edf
DM
1435 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1436}
3a616aa0 1437
782c4cde
DM
1438sub get_log_rule_base {
1439 my ($chain, $vmid, $msg, $loglevel) = @_;
cbb5d6f3 1440
782c4cde
DM
1441 die "internal error - no log level" if !defined($loglevel);
1442
1443 $vmid = 0 if !defined($vmid);
1444
cbb5d6f3 1445 # Note: we use special format for prefix to pass further
782c4cde
DM
1446 # info to log daemon (VMID, LOGVELEL and CHAIN)
1447
1448 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1449}
1450
1451sub ruleset_addlog {
1452 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1453
1454 return if !defined($loglevel);
1455
1456 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1457
1458 $logrule = "$rule $logrule" if defined($rule);
1459
88733a74 1460 ruleset_addrule($ruleset, $chain, $logrule);
782c4cde
DM
1461}
1462
ead850e8 1463sub ruleset_add_chain_policy {
782c4cde 1464 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
ead850e8
DM
1465
1466 if ($policy eq 'ACCEPT') {
1467
1468 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1469 { ACCEPT => $accept_action});
1470
1471 } elsif ($policy eq 'DROP') {
1472
1473 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1474
782c4cde 1475 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1476
1477 ruleset_addrule($ruleset, $chain, "-j DROP");
1478 } elsif ($policy eq 'REJECT') {
1479 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1480
782c4cde 1481 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1482
1483 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1484 } else {
1485 # should not happen
1486 die "internal error: unknown policy '$policy'";
1487 }
1488}
1489
e2943485
DM
1490sub ruleset_chain_add_conn_filters {
1491 my ($ruleset, $chain, $accept) = @_;
1492
1493 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1494 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1495}
1496
1497sub ruleset_chain_add_input_filters {
2428e394
AD
1498 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1499
1500 if ($cluster_conf->{ipset}->{blacklist}){
1501 ruleset_addlog($ruleset, $chain, 0, "DROP: ", $loglevel, "-m set --match-set PVEFW-blacklist src");
1502 ruleset_addrule($ruleset, $chain, "-m set --match-set PVEFW-blacklist src -j DROP");
1503 }
e2943485
DM
1504
1505 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1506 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1507 }
1508
1509 if ($options->{tcpflags}) {
1510 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1511 }
1512}
1513
9e15114a 1514sub ruleset_create_vm_chain {
58638f2c 1515 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
3a616aa0 1516
9e15114a 1517 ruleset_create_chain($ruleset, $chain);
b47ecc88 1518 my $accept = generate_nfqueue($options);
3a616aa0 1519
ce15d90b 1520 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
76a2d1e7 1521 if ($direction eq 'OUT') {
cbb5d6f3 1522 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
0f168d7b 1523 proto => 'udp', sport => 68, dport => 67 });
76a2d1e7 1524 } else {
cbb5d6f3 1525 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
0f168d7b 1526 proto => 'udp', sport => 67, dport => 68 });
76a2d1e7 1527 }
ce15d90b
DM
1528 }
1529
b21aca2c
DM
1530 if ($direction eq 'OUT') {
1531 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
9e15114a 1532 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
b21aca2c 1533 }
9e15114a 1534 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
c29f55c9 1535 }
9e15114a
DM
1536}
1537
4bc6b5ac
DM
1538sub ruleset_add_group_rule {
1539 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1540
1541 my $group = $rule->{action};
1542 my $group_chain = "GROUP-$group-$direction";
1543 if(!ruleset_chain_exist($ruleset, $group_chain)){
1544 generate_group_rules($ruleset, $cluster_conf, $group);
1545 }
f8b12fff
DM
1546
1547 if ($direction eq 'OUT' && $rule->{iface_out}) {
1548 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain");
1549 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1550 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in} -j $group_chain");
4bc6b5ac
DM
1551 } else {
1552 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1553 }
1554
1555 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $action");
1556}
1557
9e15114a 1558sub ruleset_generate_vm_rules {
fca39c2c 1559 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
9e15114a
DM
1560
1561 my $lc_direction = lc($direction);
c29f55c9 1562
6b8ca015
DM
1563 my $in_accept = generate_nfqueue($options);
1564
92e976b3
DM
1565 foreach my $rule (@$rules) {
1566 next if $rule->{iface} && $rule->{iface} ne $netid;
ea9e5116 1567 next if !$rule->{enable};
92e976b3 1568 if ($rule->{type} eq 'group') {
4bc6b5ac
DM
1569 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1570 $direction eq 'OUT' ? 'RETURN' : $in_accept);
92e976b3
DM
1571 } else {
1572 next if $rule->{type} ne $lc_direction;
921dfb33
DM
1573 eval {
1574 if ($direction eq 'OUT') {
1575 ruleset_generate_rule($ruleset, $chain, $rule,
e34d0e58 1576 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
921dfb33
DM
1577 undef, $cluster_conf);
1578 } else {
e34d0e58
DM
1579 ruleset_generate_rule($ruleset, $chain, $rule,
1580 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
921dfb33
DM
1581 undef, $cluster_conf);
1582 }
1583 };
1584 warn $@ if $@;
4e6112f9 1585 }
3a616aa0 1586 }
9e15114a
DM
1587}
1588
b47ecc88
AD
1589sub generate_nfqueue {
1590 my ($options) = @_;
1591
73089769
DM
1592 if ($options->{ips}) {
1593 my $action = "NFQUEUE";
1594 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1595 if (defined($3) && defined($1)) {
b47ecc88 1596 $action .= " --queue-balance $1:$3";
73089769 1597 } elsif (defined($1)) {
b47ecc88
AD
1598 $action .= " --queue-num $1";
1599 }
1600 }
8dc92812 1601 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
73089769
DM
1602 return $action;
1603 } else {
1604 return "ACCEPT";
b47ecc88 1605 }
b47ecc88
AD
1606}
1607
da6fc60b 1608sub ruleset_generate_vm_ipsrules {
a01c32c7 1609 my ($ruleset, $options, $direction, $iface) = @_;
da6fc60b
AD
1610
1611 if ($options->{ips} && $direction eq 'IN') {
1612 my $nfqueue = generate_nfqueue($options);
1613
a01c32c7 1614 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
da6fc60b
AD
1615 ruleset_create_chain($ruleset, "PVEFW-IPS");
1616 }
1617
a01c32c7 1618 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
da6fc60b
AD
1619 }
1620}
1621
9e15114a 1622sub generate_venet_rules_direction {
58638f2c 1623 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
9e15114a 1624
9e15114a
DM
1625 my $lc_direction = lc($direction);
1626
1627 my $rules = $vmfw_conf->{rules};
1628
1629 my $options = $vmfw_conf->{options};
1630 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1631
1632 my $chain = "venet0-$vmid-$direction";
1633
58638f2c 1634 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
9e15114a 1635
fca39c2c 1636 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
9e15114a
DM
1637
1638 # implement policy
1639 my $policy;
1640
1641 if ($direction eq 'OUT') {
1642 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1643 } else {
1644 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1645 }
1646
b47ecc88
AD
1647 my $accept = generate_nfqueue($options);
1648 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1649 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
9e15114a 1650
eba0fb64 1651 if ($direction eq 'OUT') {
41389aed 1652 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT", {
eba0fb64
DM
1653 action => $chain,
1654 source => $ip,
1655 iface_in => 'venet0'});
1656 } else {
41389aed 1657 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN", {
eba0fb64
DM
1658 action => $chain,
1659 dest => $ip,
1660 iface_out => 'venet0'});
1661 }
9e15114a
DM
1662}
1663
1664sub generate_tap_rules_direction {
58638f2c 1665 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
9e15114a
DM
1666
1667 my $lc_direction = lc($direction);
1668
1669 my $rules = $vmfw_conf->{rules};
1670
1671 my $options = $vmfw_conf->{options};
1672 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1673
1674 my $tapchain = "$iface-$direction";
1675
58638f2c 1676 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
9e15114a 1677
fca39c2c 1678 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
3a616aa0 1679
a01c32c7 1680 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
da6fc60b 1681
ccae0b50
DM
1682 # implement policy
1683 my $policy;
1684
1685 if ($direction eq 'OUT') {
72f63fde 1686 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
ccae0b50 1687 } else {
72f63fde 1688 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
ccae0b50
DM
1689 }
1690
b47ecc88
AD
1691 my $accept = generate_nfqueue($options);
1692 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1693 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
3a616aa0 1694
3fa83edf 1695 # plug the tap chain to bridge chain
3cc81077 1696 if ($direction eq 'IN') {
a01c32c7
DM
1697 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
1698 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
3cc81077 1699 } else {
a01c32c7
DM
1700 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
1701 "-m physdev --physdev-is-bridged --physdev-in $iface -j $tapchain");
3cc81077 1702 }
3a616aa0
AD
1703}
1704
d18c1e2b 1705sub enable_host_firewall {
fca39c2c 1706 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
0bd5f137 1707
92e976b3 1708 my $options = $hostfw_conf->{options};
63324b09 1709 my $cluster_options = $cluster_conf->{options};
92e976b3 1710 my $rules = $hostfw_conf->{rules};
35f0c37e 1711 my $cluster_rules = $cluster_conf->{rules};
178a63be 1712
3fa83edf 1713 # host inbound firewall
dec84fcd
DM
1714 my $chain = "PVEFW-HOST-IN";
1715 ruleset_create_chain($ruleset, $chain);
0bd5f137 1716
178a63be
DM
1717 my $loglevel = get_option_log_level($options, "log_level_in");
1718
e2943485 1719 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
4ac863a6 1720
e2943485 1721 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2428e394 1722 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
fb424a00 1723
23e888f8
DM
1724 # we use RETURN because we need to check also tap rules
1725 my $accept_action = 'RETURN';
1726
cc8dc02f
DM
1727 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
1728
35f0c37e
DM
1729 # add host rules first, so that cluster wide rules can be overwritten
1730 foreach my $rule (@$rules, @$cluster_rules) {
f8b12fff 1731 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1a9978ed
DM
1732 eval {
1733 if ($rule->{type} eq 'group') {
1734 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1735 } elsif ($rule->{type} eq 'in') {
1736 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
1737 undef, $cluster_conf);
1738 }
1739 };
1740 warn $@ if $@;
f8b12fff 1741 delete $rule->{iface_in};
0bd5f137 1742 }
eb399cef
DM
1743
1744 # allow standard traffic for management ipset (includes cluster network)
1745 my $mngmntsrc = "-m set --match-set PVEFW-management src";
1746 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006 -j $accept_action"); # PVE API
1747 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
1748 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
1749 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22 -j $accept_action"); # SSH
3bc79f87 1750
525778d7 1751 my $localnet = local_network();
3bc79f87 1752
eb399cef 1753 # corosync
525778d7 1754 if ($localnet) {
c5191f57 1755 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
525778d7
DM
1756 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule");
1757 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule");
3bc79f87 1758 }
0bd5f137 1759
23e888f8 1760 # implement input policy
63324b09 1761 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
782c4cde 1762 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
0bd5f137 1763
3fa83edf 1764 # host outbound firewall
aadd745e 1765 $chain = "PVEFW-HOST-OUT";
dec84fcd
DM
1766 ruleset_create_chain($ruleset, $chain);
1767
178a63be
DM
1768 $loglevel = get_option_log_level($options, "log_level_out");
1769
dec84fcd 1770 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
e2943485
DM
1771
1772 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1773
23e888f8
DM
1774 # we use RETURN because we may want to check other thigs later
1775 $accept_action = 'RETURN';
1776
cc8dc02f
DM
1777 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
1778
35f0c37e
DM
1779 # add host rules first, so that cluster wide rules can be overwritten
1780 foreach my $rule (@$rules, @$cluster_rules) {
f8b12fff 1781 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1a9978ed
DM
1782 eval {
1783 if ($rule->{type} eq 'group') {
1784 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1785 } elsif ($rule->{type} eq 'out') {
1786 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
1787 undef, $cluster_conf);
1788 }
1789 };
1790 warn $@ if $@;
f8b12fff 1791 delete $rule->{iface_out};
0bd5f137
AD
1792 }
1793
3bc79f87 1794 # allow standard traffic on cluster network
525778d7
DM
1795 if ($localnet) {
1796 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006 -j $accept_action"); # PVE API
1797 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22 -j $accept_action"); # SSH
1798 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
1799 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
3bc79f87 1800
c5191f57 1801 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
525778d7 1802 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule");
f573ae2c 1803 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule");
3bc79f87
DM
1804 }
1805
23e888f8 1806 # implement output policy
63324b09 1807 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
782c4cde 1808 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
6158271d 1809
dec84fcd
DM
1810 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1811 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
9d31b418
AD
1812}
1813
1814sub generate_group_rules {
fca39c2c 1815 my ($ruleset, $cluster_conf, $group) = @_;
9d31b418 1816
c6f5cc88 1817 my $rules = $cluster_conf->{groups}->{$group};
6158271d 1818
b4deedab
DM
1819 if (!$rules) {
1820 warn "no such security group '$group'\n";
1821 $rules = []; # create empty chain
1822 }
1823
3fa83edf 1824 my $chain = "GROUP-${group}-IN";
9d31b418 1825
3fa83edf 1826 ruleset_create_chain($ruleset, $chain);
b47ecc88 1827 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 1828
92e976b3
DM
1829 foreach my $rule (@$rules) {
1830 next if $rule->{type} ne 'in';
ba791b1f 1831 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418
AD
1832 }
1833
3fa83edf 1834 $chain = "GROUP-${group}-OUT";
9d31b418 1835
3fa83edf 1836 ruleset_create_chain($ruleset, $chain);
4e6112f9 1837 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 1838
92e976b3
DM
1839 foreach my $rule (@$rules) {
1840 next if $rule->{type} ne 'out';
1841 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1842 # check also other tap rules later
cbb5d6f3 1843 ruleset_generate_rule($ruleset, $chain, $rule,
ba791b1f 1844 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418 1845 }
9d31b418
AD
1846}
1847
51bae274
DM
1848my $MAX_NETS = 32;
1849my $valid_netdev_names = {};
1850for (my $i = 0; $i < $MAX_NETS; $i++) {
1851 $valid_netdev_names->{"net$i"} = 1;
1852}
5e1267a5 1853
51bae274 1854sub parse_fw_rule {
dba740a9 1855 my ($line, $allow_iface, $allow_groups) = @_;
5e1267a5 1856
dba740a9 1857 chomp $line;
51bae274 1858
6d9246e7
DM
1859 my $rule = {};
1860
11bac5c2 1861 # we can add single line comments to the end of the rule
6d9246e7
DM
1862 if ($line =~ s/#\s*(.*?)\s*$//) {
1863 $rule->{comment} = decode('utf8', $1);
1864 }
11bac5c2
DM
1865
1866 # we can disable a rule when prefixed with '|'
ea9e5116 1867
6d9246e7 1868 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
51bae274 1869
dba740a9
DM
1870 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1871 die "unable to parse rule: $line\n";
6d9246e7
DM
1872
1873 $rule->{type} = lc($1);
1874 $rule->{action} = $2;
1875
1876 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1877 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1878 $rule->{macro} = $1;
1879 $rule->{action} = $2;
92e976b3 1880 }
51bae274
DM
1881 }
1882
dba740a9
DM
1883 while (length($line)) {
1884 if ($line =~ s/^-i (\S+)\s*//) {
1885 die "parameter -i not allowed\n" if !$allow_iface;
6d9246e7 1886 $rule->{iface} = $1;
dba740a9
DM
1887 next;
1888 }
51bae274 1889
6d9246e7 1890 last if $rule->{type} eq 'group';
51bae274 1891
dba740a9 1892 if ($line =~ s/^-p (\S+)\s*//) {
6d9246e7 1893 $rule->{proto} = $1;
dba740a9
DM
1894 next;
1895 }
6d9246e7 1896
dba740a9 1897 if ($line =~ s/^-dport (\S+)\s*//) {
6d9246e7 1898 $rule->{dport} = $1;
dba740a9
DM
1899 next;
1900 }
6d9246e7 1901
dba740a9 1902 if ($line =~ s/^-sport (\S+)\s*//) {
6d9246e7 1903 $rule->{sport} = $1;
dba740a9
DM
1904 next;
1905 }
1906 if ($line =~ s/^-source (\S+)\s*//) {
6d9246e7 1907 $rule->{source} = $1;
dba740a9
DM
1908 next;
1909 }
1910 if ($line =~ s/^-dest (\S+)\s*//) {
6d9246e7 1911 $rule->{dest} = $1;
dba740a9
DM
1912 next;
1913 }
51bae274 1914
dba740a9
DM
1915 last;
1916 }
ba791b1f 1917
dba740a9 1918 die "unable to parse rule parameters: $line\n" if length($line);
51bae274 1919
6d9246e7
DM
1920 $rule = verify_rule($rule, $allow_groups, 1);
1921
1922 return $rule;
51bae274
DM
1923}
1924
2d404ffc 1925sub parse_vmfw_option {
85c6eaed
DM
1926 my ($line) = @_;
1927
1928 my ($opt, $value);
1929
178a63be
DM
1930 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1931
6bafd113 1932 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
9c6b6efd
DM
1933 $opt = lc($1);
1934 $value = int($2);
178a63be
DM
1935 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1936 $opt = lc($1);
1937 $value = $2 ? lc($3) : '';
72f63fde 1938 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
85c6eaed
DM
1939 $opt = lc($1);
1940 $value = uc($3);
b47ecc88
AD
1941 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1942 $opt = lc($1);
1943 $value = $2;
9c6b6efd 1944 } else {
85c6eaed
DM
1945 chomp $line;
1946 die "can't parse option '$line'\n"
1947 }
1948
1949 return ($opt, $value);
1950}
1951
2d404ffc
DM
1952sub parse_hostfw_option {
1953 my ($line) = @_;
1954
1955 my ($opt, $value);
1956
1957 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1958
c50a5a68 1959 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2d404ffc
DM
1960 $opt = lc($1);
1961 $value = int($2);
178a63be 1962 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2d404ffc
DM
1963 $opt = lc($1);
1964 $value = $2 ? lc($3) : '';
28c082a1 1965 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
490cdead
DM
1966 $opt = lc($1);
1967 $value = int($2);
2d404ffc
DM
1968 } else {
1969 chomp $line;
1970 die "can't parse option '$line'\n"
1971 }
1972
1973 return ($opt, $value);
1974}
1975
c6f5cc88
DM
1976sub parse_clusterfw_option {
1977 my ($line) = @_;
1978
1979 my ($opt, $value);
1980
1981 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1982 $opt = lc($1);
1983 $value = int($2);
63324b09
DM
1984 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1985 $opt = lc($1);
1986 $value = uc($3);
c6f5cc88
DM
1987 } else {
1988 chomp $line;
1989 die "can't parse option '$line'\n"
1990 }
1991
1992 return ($opt, $value);
1993}
1994
e76a9f53 1995sub parse_alias {
92e1209b
AD
1996 my ($line) = @_;
1997
81d574a7
DM
1998 # we can add single line comments to the end of the line
1999 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2000
92e1209b 2001 if ($line =~ m/^(\S+)\s(\S+)$/) {
81d574a7
DM
2002 my ($name, $cidr) = ($1, $2);
2003 $cidr =~ s|/32$||;
2004 pve_verify_ipv4_or_cidr($cidr);
2005 my $data = {
2006 name => $name,
2007 cidr => $cidr,
2008 };
2009 $data->{comment} = $comment if $comment;
2010 return $data;
92e1209b
AD
2011 }
2012
81d574a7 2013 return undef;
92e1209b
AD
2014}
2015
51bae274
DM
2016sub parse_vm_fw_rules {
2017 my ($filename, $fh) = @_;
2018
e76a9f53
DM
2019 my $res = {
2020 rules => [],
2021 options => {},
2022 aliases => {},
2023 };
51bae274
DM
2024
2025 my $section;
2026
5e1267a5
DM
2027 while (defined(my $line = <$fh>)) {
2028 next if $line =~ m/^#/;
2029 next if $line =~ m/^\s*$/;
2030
961b4928
DM
2031 my $linenr = $fh->input_line_number();
2032 my $prefix = "$filename (line $linenr)";
2033
85c6eaed 2034 if ($line =~ m/^\[(\S+)\]\s*$/i) {
5e1267a5 2035 $section = lc($1);
85c6eaed 2036 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
5e1267a5
DM
2037 next;
2038 }
51bae274 2039 if (!$section) {
961b4928 2040 warn "$prefix: skip line - no section";
5e1267a5
DM
2041 next;
2042 }
2043
85c6eaed
DM
2044 next if !$res->{$section}; # skip undefined section
2045
2046 if ($section eq 'options') {
6158271d 2047 eval {
2d404ffc 2048 my ($opt, $value) = parse_vmfw_option($line);
85c6eaed
DM
2049 $res->{options}->{$opt} = $value;
2050 };
2051 warn "$prefix: $@" if $@;
2052 next;
2053 }
2054
e76a9f53
DM
2055 if ($section eq 'aliases') {
2056 eval {
2057 my $data = parse_alias($line);
2058 $res->{aliases}->{lc($data->{name})} = $data;
2059 };
2060 warn "$prefix: $@" if $@;
2061 next;
2062 }
2063
e5076eee
DM
2064 my $rule;
2065 eval { $rule = parse_fw_rule($line, 1, 1); };
51bae274 2066 if (my $err = $@) {
961b4928 2067 warn "$prefix: $err";
5e1267a5
DM
2068 next;
2069 }
2070
e5076eee 2071 push @{$res->{$section}}, $rule;
51bae274
DM
2072 }
2073
2074 return $res;
2075}
2076
2077sub parse_host_fw_rules {
2078 my ($filename, $fh) = @_;
2079
92e976b3 2080 my $res = { rules => [], options => {}};
51bae274
DM
2081
2082 my $section;
2083
2084 while (defined(my $line = <$fh>)) {
2085 next if $line =~ m/^#/;
2086 next if $line =~ m/^\s*$/;
2087
961b4928
DM
2088 my $linenr = $fh->input_line_number();
2089 my $prefix = "$filename (line $linenr)";
2090
2d404ffc 2091 if ($line =~ m/^\[(\S+)\]\s*$/i) {
51bae274 2092 $section = lc($1);
2d404ffc 2093 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
5e1267a5
DM
2094 next;
2095 }
51bae274 2096 if (!$section) {
961b4928 2097 warn "$prefix: skip line - no section";
5e1267a5
DM
2098 next;
2099 }
2100
2d404ffc
DM
2101 next if !$res->{$section}; # skip undefined section
2102
2103 if ($section eq 'options') {
2104 eval {
2d404ffc
DM
2105 my ($opt, $value) = parse_hostfw_option($line);
2106 $res->{options}->{$opt} = $value;
2107 };
2108 warn "$prefix: $@" if $@;
2109 next;
2110 }
2111
e5076eee
DM
2112 my $rule;
2113 eval { $rule = parse_fw_rule($line, 1, 1); };
ecbea048 2114 if (my $err = $@) {
961b4928 2115 warn "$prefix: $err";
ecbea048 2116 next;
ecbea048 2117 }
cbb5d6f3 2118
e5076eee 2119 push @{$res->{$section}}, $rule;
51bae274 2120 }
ecbea048 2121
51bae274
DM
2122 return $res;
2123}
4cdbb3b7 2124
c6f5cc88 2125sub parse_cluster_fw_rules {
51bae274 2126 my ($filename, $fh) = @_;
5e1267a5 2127
51bae274
DM
2128 my $section;
2129 my $group;
2130
e34d0e58
DM
2131 my $res = {
2132 rules => [],
2133 options => {},
2134 aliases => {},
2135 groups => {},
2136 group_comments => {},
d72c631c 2137 ipset => {} ,
e34d0e58 2138 ipset_comments => {},
0d22acb3 2139 };
6158271d 2140
51bae274
DM
2141 while (defined(my $line = <$fh>)) {
2142 next if $line =~ m/^#/;
2143 next if $line =~ m/^\s*$/;
2144
961b4928
DM
2145 my $linenr = $fh->input_line_number();
2146 my $prefix = "$filename (line $linenr)";
2147
c6f5cc88
DM
2148 if ($line =~ m/^\[options\]$/i) {
2149 $section = 'options';
2150 next;
2151 }
2152
92e1209b
AD
2153 if ($line =~ m/^\[aliases\]$/i) {
2154 $section = 'aliases';
2155 next;
2156 }
2157
0d22acb3 2158 if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
c6f5cc88 2159 $section = 'groups';
92e976b3 2160 $group = lc($1);
0d22acb3 2161 my $comment = $2;
c85c87f9 2162 $res->{$section}->{$group} = [];
649e4d57
DM
2163 $res->{group_comments}->{$group} = decode('utf8', $comment)
2164 if $comment;
51bae274
DM
2165 next;
2166 }
34cdedfa 2167
c6f5cc88
DM
2168 if ($line =~ m/^\[rules\]$/i) {
2169 $section = 'rules';
2170 next;
2171 }
cbb5d6f3 2172
d72c631c 2173 if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
34cdedfa
AD
2174 $section = 'ipset';
2175 $group = lc($1);
d72c631c 2176 my $comment = $2;
c85c87f9 2177 $res->{$section}->{$group} = [];
e34d0e58 2178 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
649e4d57 2179 if $comment;
34cdedfa
AD
2180 next;
2181 }
2182
c6f5cc88 2183 if (!$section) {
cbb5d6f3 2184 warn "$prefix: skip line - no section\n";
51bae274
DM
2185 next;
2186 }
2187
c6f5cc88
DM
2188 if ($section eq 'options') {
2189 eval {
2190 my ($opt, $value) = parse_clusterfw_option($line);
2191 $res->{options}->{$opt} = $value;
2192 };
2193 warn "$prefix: $@" if $@;
92e1209b
AD
2194 } elsif ($section eq 'aliases') {
2195 eval {
e76a9f53 2196 my $data = parse_alias($line);
81d574a7 2197 $res->{aliases}->{lc($data->{name})} = $data;
92e1209b
AD
2198 };
2199 warn "$prefix: $@" if $@;
c6f5cc88
DM
2200 } elsif ($section eq 'rules') {
2201 my $rule;
2202 eval { $rule = parse_fw_rule($line, 1, 1); };
2203 if (my $err = $@) {
2204 warn "$prefix: $err";
2205 next;
2206 }
2207 push @{$res->{$section}}, $rule;
2208 } elsif ($section eq 'groups') {
34cdedfa
AD
2209 my $rule;
2210 eval { $rule = parse_fw_rule($line, 0, 0); };
2211 if (my $err = $@) {
2212 warn "$prefix: $err";
2213 next;
2214 }
3f95d14a 2215 push @{$res->{$section}->{$group}}, $rule;
3f95d14a 2216 } elsif ($section eq 'ipset') {
9d6f90e6
DM
2217 # we can add single line comments to the end of the rule
2218 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2219
30f1b100 2220 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2a052ee3 2221 my $nomatch = $1;
9d6f90e6 2222 my $cidr = $2;
2a052ee3 2223
44be8ceb 2224 if($cidr !~ m/^${ip_alias_pattern}$/) {
92e1209b 2225 $cidr =~ s|/32$||;
e34d0e58 2226
92e1209b
AD
2227 eval { pve_verify_ipv4_or_cidr($cidr); };
2228 if (my $err = $@) {
2229 warn "$prefix: $cidr - $err";
2230 next;
2231 }
2a052ee3 2232 }
2a052ee3 2233
e34d0e58 2234 my $entry = { cidr => $cidr };
9d6f90e6
DM
2235 $entry->{nomatch} = 1 if $nomatch;
2236 $entry->{comment} = $comment if $comment;
e34d0e58 2237
9d6f90e6 2238 push @{$res->{$section}->{$group}}, $entry;
51bae274 2239 }
5e1267a5
DM
2240 }
2241
2242 return $res;
2243}
2244
06320eb0
DM
2245sub run_locked {
2246 my ($code, @param) = @_;
2247
2248 my $timeout = 10;
2249
2250 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2251
2252 die $@ if $@;
2253
2254 return $res;
2255}
2256
5e1267a5
DM
2257sub read_local_vm_config {
2258
2259 my $openvz = {};
5e1267a5
DM
2260 my $qemu = {};
2261
c8301d63 2262 my $vmdata = { openvz => $openvz, qemu => $qemu };
5e1267a5 2263
c8301d63
DM
2264 my $vmlist = PVE::Cluster::get_vmlist();
2265 return $vmdata if !$vmlist || !$vmlist->{ids};
2266 my $ids = $vmlist->{ids};
2267
2268 foreach my $vmid (keys %$ids) {
2269 next if !$vmid; # skip VE0
2270 my $d = $ids->{$vmid};
2271 next if !$d->{node} || $d->{node} ne $nodename;
2272 next if !$d->{type};
2273 if ($d->{type} eq 'openvz') {
d9fee004
DM
2274 if ($have_pve_manager) {
2275 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2276 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2277 $openvz->{$vmid} = $conf;
2278 }
c8301d63
DM
2279 }
2280 } elsif ($d->{type} eq 'qemu') {
d9fee004
DM
2281 if ($have_qemu_server) {
2282 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2283 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2284 $qemu->{$vmid} = $conf;
2285 }
c8301d63 2286 }
5e1267a5
DM
2287 }
2288 }
d9fee004 2289
5e1267a5
DM
2290 return $vmdata;
2291};
2292
e7b35711 2293sub load_vmfw_conf {
8aef5177 2294 my ($vmid, $dir) = @_;
e7b35711
DM
2295
2296 my $vmfw_conf = {};
2297
8aef5177
DM
2298 $dir = "/etc/pve/firewall" if !defined($dir);
2299
2300 my $filename = "$dir/$vmid.fw";
e7b35711
DM
2301 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2302 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2303 }
2304
2305 return $vmfw_conf;
2306}
2307
464f933e 2308my $format_rules = sub {
dba740a9 2309 my ($rules, $allow_iface) = @_;
464f933e
DM
2310
2311 my $raw = '';
2312
2313 foreach my $rule (@$rules) {
c14dacdf 2314 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
464f933e
DM
2315 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2316 $raw .= uc($rule->{type});
7ca36671
DM
2317 if ($rule->{macro}) {
2318 $raw .= " $rule->{macro}($rule->{action})";
2319 } else {
2320 $raw .= " " . $rule->{action};
2321 }
dba740a9
DM
2322 if ($allow_iface && $rule->{iface}) {
2323 $raw .= " -i $rule->{iface}";
2324 }
c14dacdf
DM
2325
2326 if ($rule->{type} ne 'group') {
dba740a9
DM
2327 $raw .= " -source $rule->{source}" if $rule->{source};
2328 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2329 $raw .= " -p $rule->{proto}" if $rule->{proto};
2330 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2331 $raw .= " -sport $rule->{sport}" if $rule->{sport};
c14dacdf
DM
2332 }
2333
cbb5d6f3 2334 $raw .= " # " . encode('utf8', $rule->{comment})
464f933e
DM
2335 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2336 $raw .= "\n";
2337 } else {
c14dacdf 2338 die "unknown rule type '$rule->{type}'";
464f933e
DM
2339 }
2340 }
2341
2342 return $raw;
2343};
2344
2345my $format_options = sub {
68c90e21
DM
2346 my ($options) = @_;
2347
2348 my $raw = '';
464f933e
DM
2349
2350 $raw .= "[OPTIONS]\n\n";
2351 foreach my $opt (keys %$options) {
2352 $raw .= "$opt: $options->{$opt}\n";
2353 }
2354 $raw .= "\n";
68c90e21
DM
2355
2356 return $raw;
464f933e
DM
2357};
2358
0d5f0a0f
DM
2359my $format_aliases = sub {
2360 my ($aliases) = @_;
2361
2362 my $raw = '';
2363
2364 $raw .= "[ALIASES]\n\n";
2365 foreach my $k (keys %$aliases) {
81d574a7
DM
2366 my $e = $aliases->{$k};
2367 $raw .= "$e->{name} $e->{cidr}";
2368 $raw .= " # " . encode('utf8', $e->{comment})
2369 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2370 $raw .= "\n";
0d5f0a0f
DM
2371 }
2372 $raw .= "\n";
2373
2374 return $raw;
2375};
2376
9d6f90e6
DM
2377my $format_ipset = sub {
2378 my ($options) = @_;
2379
2380 my $raw = '';
2381
6e299ae3 2382 my $nethash = {};
9d6f90e6 2383 foreach my $entry (@$options) {
6e299ae3
DM
2384 $nethash->{$entry->{cidr}} = $entry;
2385 }
2386
2387 foreach my $cidr (sort keys %$nethash) {
2388 my $entry = $nethash->{$cidr};
9d6f90e6
DM
2389 my $line = $entry->{nomatch} ? '!' : '';
2390 $line .= $entry->{cidr};
2391 $line .= " # " . encode('utf8', $entry->{comment})
2392 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2393 $raw .= "$line\n";
2394 }
e34d0e58 2395
9d6f90e6
DM
2396 return $raw;
2397};
2398
464f933e
DM
2399sub save_vmfw_conf {
2400 my ($vmid, $vmfw_conf) = @_;
2401
2402 my $raw = '';
2403
2404 my $options = $vmfw_conf->{options};
68c90e21 2405 $raw .= &$format_options($options) if scalar(keys %$options);
cbb5d6f3 2406
e76a9f53
DM
2407 my $aliases = $vmfw_conf->{aliases};
2408 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2409
8824b2f0 2410 my $rules = $vmfw_conf->{rules} || [];
464f933e
DM
2411 if (scalar(@$rules)) {
2412 $raw .= "[RULES]\n\n";
2413 $raw .= &$format_rules($rules, 1);
2414 $raw .= "\n";
2415 }
2416
2417 my $filename = "/etc/pve/firewall/$vmid.fw";
2418 PVE::Tools::file_set_contents($filename, $raw);
2419}
2420
6fc63ffd 2421sub read_vm_firewall_configs {
8aef5177
DM
2422 my ($vmdata, $dir) = @_;
2423
6fc63ffd 2424 my $vmfw_configs = {};
c8301d63 2425
5e1267a5 2426 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
8aef5177 2427 my $vmfw_conf = load_vmfw_conf($vmid, $dir);
e7b35711
DM
2428 next if !$vmfw_conf->{options}; # skip if file does not exists
2429 $vmfw_configs->{$vmid} = $vmfw_conf;
5e1267a5
DM
2430 }
2431
6fc63ffd 2432 return $vmfw_configs;
5e1267a5
DM
2433}
2434
2d404ffc
DM
2435sub get_option_log_level {
2436 my ($options, $k) = @_;
2437
2438 my $v = $options->{$k};
178a63be 2439 $v = $default_log_level if !defined($v);
2d404ffc
DM
2440
2441 return undef if $v eq '' || $v eq 'nolog';
2442
2443 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2444
2445 return $v if ($v >= 0) && ($v <= 7);
2446
2447 warn "unknown log level ($k = '$v')\n";
2448
2449 return undef;
2450}
2451
d8f2505e 2452sub generate_std_chains {
2d404ffc 2453 my ($ruleset, $options) = @_;
cbb5d6f3 2454
2d404ffc
DM
2455 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2456
2457 # same as shorewall smurflog.
782c4cde 2458 my $chain = 'PVEFW-smurflog';
12f3796e 2459 $pve_std_chains->{$chain} = [];
782c4cde
DM
2460
2461 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2462 push @{$pve_std_chains->{$chain}}, "-j DROP";
2d404ffc
DM
2463
2464 # same as shorewall logflags action.
2465 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
782c4cde 2466 $chain = 'PVEFW-logflags';
12f3796e
DM
2467 $pve_std_chains->{$chain} = [];
2468
782c4cde
DM
2469 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2470 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2471 push @{$pve_std_chains->{$chain}}, "-j DROP";
d8f2505e
DM
2472
2473 foreach my $chain (keys %$pve_std_chains) {
2474 ruleset_create_chain($ruleset, $chain);
2475 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2476 if (ref($rule)) {
2477 ruleset_generate_rule($ruleset, $chain, $rule);
2478 } else {
2479 ruleset_addrule($ruleset, $chain, $rule);
2480 }
2481 }
2482 }
2483}
2484
34cdedfa 2485sub generate_ipset_chains {
dd7a13fd 2486 my ($ipset_ruleset, $fw_conf) = @_;
34cdedfa 2487
dd7a13fd 2488 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
92e1209b 2489 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset}, $fw_conf->{aliases});
34cdedfa
AD
2490 }
2491}
2492
2493sub generate_ipset {
92e1209b 2494 my ($ipset_ruleset, $name, $options, $aliases) = @_;
34cdedfa 2495
dd7a13fd
DM
2496 my $hashsize = scalar(@$options);
2497 if ($hashsize <= 64) {
2a052ee3 2498 $hashsize = 64;
dd7a13fd 2499 } else {
2a052ee3
AD
2500 $hashsize = round_powerof2($hashsize);
2501 }
2502
dd7a13fd 2503 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
34cdedfa 2504
30f1b100
DM
2505 # remove duplicates
2506 my $nethash = {};
9d6f90e6 2507 foreach my $entry (@$options) {
92e1209b 2508 my $cidr = $entry->{cidr};
d4091b82 2509 if ($cidr =~ m/^${ip_alias_pattern}$/) {
81d574a7
DM
2510 my $alias = lc($cidr);
2511 if ($aliases->{$alias}) {
2512 $entry->{cidr} = $aliases->{$alias}->{cidr};
7dd13259 2513 $nethash->{$entry->{cidr}} = $entry;
d4091b82 2514 } else {
81d574a7 2515 warn "no such alias '$cidr'\n" if !$aliases->{$alias};
d4091b82 2516 }
7dd13259
DM
2517 } else {
2518 $nethash->{$entry->{cidr}} = $entry;
92e1209b 2519 }
30f1b100
DM
2520 }
2521
2522 foreach my $cidr (sort keys %$nethash) {
2523 my $entry = $nethash->{$cidr};
2524
9d6f90e6
DM
2525 my $cmd = "add $name $cidr";
2526 if ($entry->{nomatch}) {
2527 if ($feature_ipset_nomatch) {
2528 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2529 } else {
2530 warn "ignore !$cidr - nomatch not supported by kernel\n";
2531 }
2532 } else {
2533 push @{$ipset_ruleset->{$name}}, $cmd;
2534 }
34cdedfa 2535 }
2a052ee3
AD
2536}
2537
2538sub round_powerof2 {
dd7a13fd 2539 my ($int) = @_;
2a052ee3 2540
dd7a13fd
DM
2541 $int--;
2542 $int |= $int >> $_ foreach (1,2,4,8,16);
2543 return ++$int;
34cdedfa
AD
2544}
2545
fca39c2c 2546sub load_clusterfw_conf {
8aef5177
DM
2547 my ($filename) = @_;
2548
2549 $filename = $clusterfw_conf_filename if !defined($filename);
530c005e 2550
fca39c2c 2551 my $cluster_conf = {};
8aef5177
DM
2552 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2553 $cluster_conf = parse_cluster_fw_rules($filename, $fh);
51bae274 2554 }
5e1267a5 2555
fca39c2c 2556 return $cluster_conf;
e5d76bde
DM
2557}
2558
fca39c2c
DM
2559sub save_clusterfw_conf {
2560 my ($cluster_conf) = @_;
9c7e0858
DM
2561
2562 my $raw = '';
9c7e0858 2563
c6f5cc88 2564 my $options = $cluster_conf->{options};
68c90e21 2565 $raw .= &$format_options($options) if scalar(keys %$options);
9c7e0858 2566
0d5f0a0f
DM
2567 my $aliases = $cluster_conf->{aliases};
2568 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
e34d0e58 2569
9d6f90e6 2570 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
d72c631c 2571 if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
649e4d57
DM
2572 my $utf8comment = encode('utf8', $comment);
2573 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
d72c631c
DM
2574 } else {
2575 $raw .= "[IPSET $ipset]\n\n";
2576 }
9d6f90e6
DM
2577 my $options = $cluster_conf->{ipset}->{$ipset};
2578 $raw .= &$format_ipset($options);
2579 $raw .= "\n";
2580 }
c6f5cc88
DM
2581
2582 my $rules = $cluster_conf->{rules};
2583 if (scalar(@$rules)) {
2584 $raw .= "[RULES]\n\n";
63c91681 2585 $raw .= &$format_rules($rules, 1);
c6f5cc88
DM
2586 $raw .= "\n";
2587 }
2588
2589 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2590 my $rules = $cluster_conf->{groups}->{$group};
0d22acb3 2591 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
649e4d57
DM
2592 my $utf8comment = encode('utf8', $comment);
2593 $raw .= "[group $group] # $utf8comment\n\n";
0d22acb3
DM
2594 } else {
2595 $raw .= "[group $group]\n\n";
2596 }
2597
63c91681 2598 $raw .= &$format_rules($rules, 0);
9c7e0858
DM
2599 $raw .= "\n";
2600 }
2601
fca39c2c 2602 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
9c7e0858
DM
2603}
2604
8b27beb9 2605sub load_hostfw_conf {
8aef5177
DM
2606 my ($filename) = @_;
2607
2608 $filename = $hostfw_conf_filename if !defined($filename);
8b27beb9
DM
2609
2610 my $hostfw_conf = {};
8aef5177
DM
2611 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2612 $hostfw_conf = parse_host_fw_rules($filename, $fh);
8b27beb9
DM
2613 }
2614 return $hostfw_conf;
2615}
2616
63c91681
DM
2617sub save_hostfw_conf {
2618 my ($hostfw_conf) = @_;
2619
2620 my $raw = '';
2621
2622 my $options = $hostfw_conf->{options};
68c90e21 2623 $raw .= &$format_options($options) if scalar(keys %$options);
cbb5d6f3 2624
63c91681
DM
2625 my $rules = $hostfw_conf->{rules};
2626 if (scalar(@$rules)) {
2627 $raw .= "[RULES]\n\n";
2628 $raw .= &$format_rules($rules, 1);
2629 $raw .= "\n";
2630 }
2631
2632 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2633}
2634
e5d76bde 2635sub compile {
8aef5177 2636 my ($cluster_conf, $hostfw_conf, $vmdata) = @_;
3dfa8a7f 2637
8aef5177
DM
2638 my $vmfw_configs;
2639
2640 if ($vmdata) { # test mode
2641 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2642 my $filename = "$testdir/cluster.fw";
8aef5177
DM
2643 $cluster_conf = load_clusterfw_conf($filename);
2644
2645 $filename = "$testdir/host.fw";
8aef5177
DM
2646 $hostfw_conf = load_hostfw_conf($filename);
2647
2648 $vmfw_configs = read_vm_firewall_configs($vmdata, $testdir);
2649 } else { # normal operation
2650 $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
2651
2652 $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
2653
2654 $vmdata = read_local_vm_config();
2655 $vmfw_configs = read_vm_firewall_configs($vmdata);
2656 }
3dfa8a7f 2657
e5d76bde 2658
27083984 2659 $cluster_conf->{ipset}->{venet0} = [];
eb399cef 2660
525778d7
DM
2661 my $localnet;
2662 if ($cluster_conf->{aliases}->{local_network}) {
2663 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2664 } else {
2665 $localnet = local_network() || '127.0.0.0/8';
2666 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2667 }
2668
2669 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
eb399cef 2670
3fa83edf
DM
2671 my $ruleset = {};
2672
dec84fcd
DM
2673 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2674 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
5b1df9a0 2675
fadb13dd 2676 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
e34d0e58 2677
8b27beb9 2678 my $hostfw_options = $hostfw_conf->{options} || {};
fadb13dd 2679
88733a74
AD
2680 # fixme: what log level should we use here?
2681 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2682
097820b0 2683 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
88733a74 2684
e2943485 2685 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
27083984
AD
2686 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT");
2687 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT");
e2943485
DM
2688
2689 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2428e394 2690 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
e2943485 2691
d1b41c08 2692 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
e2943485
DM
2693
2694 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
d1b41c08 2695 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
e2943485
DM
2696
2697 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2428e394 2698 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
e2943485 2699
27083984 2700 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN");
e2943485 2701
92e976b3 2702 generate_std_chains($ruleset, $hostfw_options);
fadb13dd 2703
6d2ab017 2704 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2d404ffc 2705
1a9978ed
DM
2706 if ($hostfw_enable) {
2707 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2708 warn $@ if $@; # just to be sure - should not happen
2709 }
3fa83edf 2710
27083984 2711 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN");
62689a1e 2712
6158271d 2713 # generate firewall rules for QEMU VMs
3fa83edf 2714 foreach my $vmid (keys %{$vmdata->{qemu}}) {
1a9978ed
DM
2715 eval {
2716 my $conf = $vmdata->{qemu}->{$vmid};
2717 my $vmfw_conf = $vmfw_configs->{$vmid};
2718 return if !$vmfw_conf;
2719 return if !$vmfw_conf->{options}->{enable};
2720
2721 foreach my $netid (keys %$conf) {
2722 next if $netid !~ m/^net(\d+)$/;
2723 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2724 next if !$net->{firewall};
2725 my $iface = "tap${vmid}i$1";
2726
2727 my $macaddr = $net->{macaddr};
2728 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2729 $vmfw_conf, $vmid, 'IN');
2730 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2731 $vmfw_conf, $vmid, 'OUT');
2732 }
2733 };
2734 warn $@ if $@; # just to be sure - should not happen
3fa83edf 2735 }
c8301d63
DM
2736
2737 # generate firewall rules for OpenVZ containers
2738 foreach my $vmid (keys %{$vmdata->{openvz}}) {
1a9978ed
DM
2739 eval {
2740 my $conf = $vmdata->{openvz}->{$vmid};
c8301d63 2741
1a9978ed
DM
2742 my $vmfw_conf = $vmfw_configs->{$vmid};
2743 return if !$vmfw_conf;
2744 return if !$vmfw_conf->{options}->{enable};
c8301d63 2745
1a9978ed
DM
2746 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2747 my $ip = $conf->{ip_address}->{value};
2748 $ip =~ s/\s+/,/g;
2749 parse_address_list($ip); # make sure we have a valid $ip list
27083984 2750
1a9978ed 2751 my @ips = split(',', $ip);
27083984 2752
1a9978ed
DM
2753 foreach my $singleip (@ips) {
2754 my $venet0ipset = {};
2755 $venet0ipset->{cidr} = $singleip;
2756 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2757 }
c8301d63 2758
1a9978ed
DM
2759 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN');
2760 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT');
2761 }
530c005e 2762
1a9978ed
DM
2763 if ($conf->{netif} && $conf->{netif}->{value}) {
2764 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2765 foreach my $netid (keys %$netif) {
2766 my $d = $netif->{$netid};
2767
2768 my $macaddr = $d->{mac};
2769 my $iface = $d->{host_ifname};
2770 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2771 $vmfw_conf, $vmid, 'IN');
2772 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2773 $vmfw_conf, $vmid, 'OUT');
2774 }
c8301d63 2775 }
1a9978ed
DM
2776 };
2777 warn $@ if $@; # just to be sure - should not happen
c8301d63 2778 }
c0413e35 2779
097820b0
AD
2780 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2781 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2782 }
2783
27083984
AD
2784 my $ipset_ruleset = {};
2785 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2786
3dfa8a7f 2787 return ($ruleset, $ipset_ruleset);
3fa83edf
DM
2788}
2789
2790sub get_ruleset_status {
4bd0a9c4 2791 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3fa83edf
DM
2792
2793 my $statushash = {};
2794
2795 foreach my $chain (sort keys %$ruleset) {
4bd0a9c4 2796 my $sig = &$digest_fn($ruleset->{$chain});
9bf7d929 2797
3fa83edf
DM
2798 $statushash->{$chain}->{sig} = $sig;
2799
2800 my $oldsig = $active_chains->{$chain};
2801 if (!defined($oldsig)) {
2802 $statushash->{$chain}->{action} = 'create';
2803 } else {
2804 if ($oldsig eq $sig) {
2805 $statushash->{$chain}->{action} = 'exists';
2806 } else {
2807 $statushash->{$chain}->{action} = 'update';
2808 }
2809 }
2810 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2811 foreach my $cmd (@{$ruleset->{$chain}}) {
2812 print "\t$cmd\n" if $verbose;
2813 }
2814 }
2815
2816 foreach my $chain (sort keys %$active_chains) {
2817 if (!defined($ruleset->{$chain})) {
2818 my $sig = $active_chains->{$chain};
2819 $statushash->{$chain}->{action} = 'delete';
2820 $statushash->{$chain}->{sig} = $sig;
2821 print "delete $chain ($sig)\n" if $verbose;
2822 }
6158271d 2823 }
2a052ee3 2824
3fa83edf
DM
2825 return $statushash;
2826}
2827
3fa83edf
DM
2828sub print_sig_rule {
2829 my ($chain, $sig) = @_;
2830
09d5f68e
DM
2831 # We just use this to store a SHA1 checksum used to detect changes
2832 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
b6360c3f
DM
2833}
2834
df7cb349 2835sub get_ruleset_cmdlist {
a84f4d96 2836 my ($ruleset, $verbose) = @_;
3fa83edf 2837
3fa83edf 2838 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
cbb5d6f3 2839
4bd0a9c4
DM
2840 my ($active_chains, $hooks) = iptables_get_chains();
2841 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3fa83edf
DM
2842
2843 # create missing chains first
2844 foreach my $chain (sort keys %$ruleset) {
2845 my $stat = $statushash->{$chain};
2846 die "internal error" if !$stat;
2847 next if $stat->{action} ne 'create';
886aba9c 2848
3fa83edf
DM
2849 $cmdlist .= ":$chain - [0:0]\n";
2850 }
2851
4bd0a9c4
DM
2852 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2853 if (!$hooks->{$h}) {
2854 $cmdlist .= "-A $h -j PVEFW-$h\n";
2855 }
3fa83edf
DM
2856 }
2857
2858 foreach my $chain (sort keys %$ruleset) {
2859 my $stat = $statushash->{$chain};
2860 die "internal error" if !$stat;
2861
2862 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
2863 $cmdlist .= "-F $chain\n";
2864 foreach my $cmd (@{$ruleset->{$chain}}) {
2865 $cmdlist .= "$cmd\n";
2866 }
2867 $cmdlist .= print_sig_rule($chain, $stat->{sig});
2868 } elsif ($stat->{action} eq 'delete') {
f5d28682 2869 die "internal error"; # this should not happen
3fa83edf
DM
2870 } elsif ($stat->{action} eq 'exists') {
2871 # do nothing
2872 } else {
2873 die "internal error - unknown status '$stat->{action}'";
2874 }
2875 }
2876
f5d28682
DM
2877 foreach my $chain (keys %$statushash) {
2878 next if $statushash->{$chain}->{action} ne 'delete';
2879 $cmdlist .= "-F $chain\n";
2880 }
2881 foreach my $chain (keys %$statushash) {
2882 next if $statushash->{$chain}->{action} ne 'delete';
fadb13dd
DM
2883 next if $chain eq 'PVEFW-INPUT';
2884 next if $chain eq 'PVEFW-OUTPUT';
2885 next if $chain eq 'PVEFW-FORWARD';
f5d28682
DM
2886 $cmdlist .= "-X $chain\n";
2887 }
2888
3f95d14a 2889 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
4bd0a9c4 2890
3fa83edf
DM
2891 $cmdlist .= "COMMIT\n";
2892
3f95d14a 2893 return wantarray ? ($cmdlist, $changes) : $cmdlist;
6b9f68a2
DM
2894}
2895
34cdedfa 2896sub get_ipset_cmdlist {
dd7a13fd 2897 my ($ruleset, $verbose) = @_;
34cdedfa
AD
2898
2899 my $cmdlist = "";
2900
dd7a13fd
DM
2901 my $delete_cmdlist = "";
2902
4bd0a9c4
DM
2903 my $active_chains = ipset_get_chains();
2904 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
34cdedfa 2905
e34d0e58 2906 # remove stale _swap chains
30f1b100
DM
2907 foreach my $chain (keys %$active_chains) {
2908 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2909 $cmdlist .= "destroy $chain\n";
2910 }
2911 }
2912
dd7a13fd
DM
2913 foreach my $chain (sort keys %$ruleset) {
2914 my $stat = $statushash->{$chain};
2915 die "internal error" if !$stat;
2a052ee3 2916
dd7a13fd
DM
2917 if ($stat->{action} eq 'create') {
2918 foreach my $cmd (@{$ruleset->{$chain}}) {
34cdedfa
AD
2919 $cmdlist .= "$cmd\n";
2920 }
dd7a13fd 2921 }
34cdedfa 2922
dd7a13fd
DM
2923 if ($stat->{action} eq 'update') {
2924 my $chain_swap = $chain."_swap";
cbb5d6f3 2925
dd7a13fd
DM
2926 foreach my $cmd (@{$ruleset->{$chain}}) {
2927 $cmd =~ s/$chain/$chain_swap/;
2928 $cmdlist .= "$cmd\n";
34cdedfa 2929 }
dd7a13fd
DM
2930 $cmdlist .= "swap $chain_swap $chain\n";
2931 $cmdlist .= "flush $chain_swap\n";
2932 $cmdlist .= "destroy $chain_swap\n";
2a052ee3 2933 }
34cdedfa 2934
dd7a13fd 2935 }
3f95d14a 2936
dd7a13fd
DM
2937 foreach my $chain (keys %$statushash) {
2938 next if $statushash->{$chain}->{action} ne 'delete';
2a052ee3 2939
dd7a13fd
DM
2940 $delete_cmdlist .= "flush $chain\n";
2941 $delete_cmdlist .= "destroy $chain\n";
34cdedfa
AD
2942 }
2943
dd7a13fd 2944 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
cbb5d6f3 2945
dd7a13fd 2946 return ($cmdlist, $delete_cmdlist, $changes);
34cdedfa
AD
2947}
2948
6b9f68a2 2949sub apply_ruleset {
34cdedfa 2950 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
6b9f68a2
DM
2951
2952 enable_bridge_firewall();
2953
cbb5d6f3 2954 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
81a0bf43 2955 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
6b9f68a2 2956
81a0bf43 2957 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
2a052ee3 2958
81a0bf43
DM
2959 if ($verbose) {
2960 if ($ipset_changes) {
2961 print "ipset changes:\n";
2962 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2963 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2964 }
3f95d14a 2965
81a0bf43
DM
2966 if ($changes) {
2967 print "iptables changes:\n";
2968 print $cmdlist;
2969 }
2970 }
3fa83edf 2971
2a052ee3 2972 ipset_restore_cmdlist($ipset_create_cmdlist);
34cdedfa 2973
3fa83edf
DM
2974 iptables_restore_cmdlist($cmdlist);
2975
dd7a13fd 2976 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2a052ee3 2977
6158271d 2978 # test: re-read status and check if everything is up to date
4bd0a9c4 2979 my $active_chains = iptables_get_chains();
81a0bf43 2980 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3fa83edf
DM
2981
2982 my $errors;
2983 foreach my $chain (sort keys %$ruleset) {
2984 my $stat = $statushash->{$chain};
2985 if ($stat->{action} ne 'exists') {
2986 warn "unable to update chain '$chain'\n";
2987 $errors = 1;
2988 }
2989 }
b6360c3f 2990
3fa83edf 2991 die "unable to apply firewall changes\n" if $errors;
46a2ac1f
AD
2992
2993 update_nf_conntrack_max($hostfw_conf);
2994
2995 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
2996
b6360c3f
DM
2997}
2998
490cdead
DM
2999sub update_nf_conntrack_max {
3000 my ($hostfw_conf) = @_;
3001
3002 my $max = 65536; # reasonable default
3003
3004 my $options = $hostfw_conf->{options} || {};
3005
3006 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3007 $max = $options->{nf_conntrack_max};
3008 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3009 }
3010
3011 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3012 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3013
3014 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3015
3016 if ($current != $max) {
3017 my $hashsize = int($max/4);
3018 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3019 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3020 }
3021}
3022
28c082a1
AD
3023sub update_nf_conntrack_tcp_timeout_established {
3024 my ($hostfw_conf) = @_;
3025
3026 my $options = $hostfw_conf->{options} || {};
3027
3028 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3029
3030 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3031}
3032
c4a2e5ae
DM
3033sub remove_pvefw_chains {
3034
3035 my ($chash, $hooks) = iptables_get_chains();
3036 my $cmdlist = "*filter\n";
3037
3038 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3039 if ($hooks->{$h}) {
3040 $cmdlist .= "-D $h -j PVEFW-$h\n";
3041 }
3042 }
cbb5d6f3 3043
c4a2e5ae
DM
3044 foreach my $chain (keys %$chash) {
3045 $cmdlist .= "-F $chain\n";
3046 }
3047
3048 foreach my $chain (keys %$chash) {
3049 $cmdlist .= "-X $chain\n";
3050 }
3051 $cmdlist .= "COMMIT\n";
3052
3053 iptables_restore_cmdlist($cmdlist);
3054}
3055
8b453a09
DM
3056sub init {
3057 my $cluster_conf = load_clusterfw_conf();
3058 my $cluster_options = $cluster_conf->{options};
3059 my $enable = $cluster_options->{enable};
3060
3061 return if !$enable;
3062
3063 # load required modules here
3064}
3065
6b9f68a2 3066sub update {
e2beb7aa 3067 my ($verbose) = @_;
6b9f68a2
DM
3068
3069 my $code = sub {
3dfa8a7f
DM
3070
3071 my $cluster_conf = load_clusterfw_conf();
3072 my $cluster_options = $cluster_conf->{options};
3073
51e57fee 3074 my $enable = $cluster_options->{enable};
3dfa8a7f 3075
e2beb7aa 3076 die "Firewall is disabled - cannot start\n" if !$enable;
3dfa8a7f
DM
3077
3078 if (!$enable) {
b22130d3 3079 PVE::Firewall::remove_pvefw_chains();
3dfa8a7f
DM
3080 print "Firewall disabled\n" if $verbose;
3081 return;
3082 }
3083
3084 my $hostfw_conf = load_hostfw_conf();
3085
3086 my ($ruleset, $ipset_ruleset) = compile($cluster_conf, $hostfw_conf);
490cdead 3087
e2beb7aa 3088 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
6b9f68a2
DM
3089 };
3090
3091 run_locked($code);
3092}
3093
b6360c3f 30941;