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