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