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