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