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