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