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