]> git.proxmox.com Git - pve-firewall.git/blame - src/PVE/Firewall.pm
add aliases feature
[pve-firewall.git] / src / PVE / Firewall.pm
CommitLineData
b6360c3f
DM
1package PVE::Firewall;
2
3use warnings;
4use strict;
cbb5d6f3 5use POSIX;
b6360c3f 6use Data::Dumper;
09d5f68e 7use Digest::SHA;
c8301d63 8use PVE::INotify;
7ca36671 9use PVE::Exception qw(raise raise_param_exc);
e74a87f5 10use PVE::JSONSchema qw(register_standard_option get_standard_option);
c8301d63 11use PVE::Cluster;
5f0a912c 12use PVE::ProcFSTools;
009ee3ac 13use PVE::Tools qw($IPV4RE);
6b9f68a2 14use File::Basename;
5e1267a5
DM
15use File::Path;
16use IO::File;
ecbea048 17use Net::IP;
06320eb0 18use PVE::Tools qw(run_command lock_file);
30c1ae52 19use Encode;
ecbea048 20
63c91681 21my $hostfw_conf_filename = "/etc/pve/local/host.fw";
fca39c2c
DM
22my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw";
23
cbb5d6f3 24# dynamically include PVE::QemuServer and PVE::OpenVZ
d9fee004
DM
25# to avoid dependency problems
26my $have_qemu_server;
27eval {
28 require PVE::QemuServer;
29 $have_qemu_server = 1;
30};
31
32my $have_pve_manager;
33eval {
34 require PVE::OpenVZ;
35 $have_pve_manager = 1;
36};
37
009ee3ac
DM
38PVE::JSONSchema::register_format('IPv4orCIDR', \&pve_verify_ipv4_or_cidr);
39sub pve_verify_ipv4_or_cidr {
40 my ($cidr, $noerr) = @_;
41
30f1b100
DM
42 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
43 return $cidr if Net::IP->new($cidr);
44 return undef if $noerr;
45 die Net::IP::Error() . "\n";
009ee3ac
DM
46 }
47 return undef if $noerr;
48 die "value does not look like a valid IP address or CIDR network\n";
49}
50
e74a87f5
DM
51PVE::JSONSchema::register_standard_option('ipset-name', {
52 description => "IP set name.",
53 type => 'string',
54 pattern => '[A-Za-z][A-Za-z0-9\-\_]+',
387d0ffc
DM
55 minLength => 2,
56 maxLength => 20,
57});
58
6302c41f
DM
59PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => {
60 description => "Log level.",
61 type => 'string',
62 enum => ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
63 optional => 1,
64});
65
c14dacdf
DM
66my $security_group_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
67
387d0ffc
DM
68PVE::JSONSchema::register_standard_option('pve-security-group-name', {
69 description => "Security Group name.",
70 type => 'string',
c14dacdf 71 pattern => $security_group_pattern,
387d0ffc
DM
72 minLength => 2,
73 maxLength => 20,
e74a87f5 74});
009ee3ac 75
cbb5d6f3
DM
76my $feature_ipset_nomatch = 0;
77eval {
78 my (undef, undef, $release) = POSIX::uname();
79 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
80 my ($major, $minor) = ($1, $2);
81 $feature_ipset_nomatch = 1 if ($major > 3) ||
82 ($major == 3 && $minor >= 7);
83 }
84
85};
86
5e1267a5 87use Data::Dumper;
b6360c3f 88
c8301d63
DM
89my $nodename = PVE::INotify::nodename();
90
06320eb0 91my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
6b9f68a2 92my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
06320eb0 93
2d404ffc
DM
94my $default_log_level = 'info';
95
96my $log_level_hash = {
97 debug => 7,
98 info => 6,
99 notice => 5,
100 warning => 4,
101 err => 3,
102 crit => 2,
103 alert => 1,
104 emerg => 0,
105};
106
857f62c8 107# imported/converted from: /usr/share/shorewall/macro.*
961b4928 108my $pve_fw_macros = {
857f62c8 109 'Amanda' => [
ebd54ae9 110 "Amanda Backup",
857f62c8
DM
111 { action => 'PARAM', proto => 'udp', dport => '10080' },
112 { action => 'PARAM', proto => 'tcp', dport => '10080' },
113 ],
114 'Auth' => [
ebd54ae9 115 "Auth (identd) traffic",
857f62c8
DM
116 { action => 'PARAM', proto => 'tcp', dport => '113' },
117 ],
118 'BGP' => [
ebd54ae9 119 "Border Gateway Protocol traffic",
857f62c8
DM
120 { action => 'PARAM', proto => 'tcp', dport => '179' },
121 ],
122 'BitTorrent' => [
ebd54ae9 123 "BitTorrent traffic for BitTorrent 3.1 and earlier",
961b4928 124 { action => 'PARAM', proto => 'tcp', dport => '6881:6889' },
857f62c8
DM
125 { action => 'PARAM', proto => 'udp', dport => '6881' },
126 ],
127 'BitTorrent32' => [
ebd54ae9 128 "BitTorrent traffic for BitTorrent 3.2 and later",
857f62c8
DM
129 { action => 'PARAM', proto => 'tcp', dport => '6881:6999' },
130 { action => 'PARAM', proto => 'udp', dport => '6881' },
131 ],
132 'CVS' => [
ebd54ae9 133 "Concurrent Versions System pserver traffic",
857f62c8
DM
134 { action => 'PARAM', proto => 'tcp', dport => '2401' },
135 ],
136 'Citrix' => [
ebd54ae9 137 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
857f62c8
DM
138 { action => 'PARAM', proto => 'tcp', dport => '1494' },
139 { action => 'PARAM', proto => 'udp', dport => '1604' },
140 { action => 'PARAM', proto => 'tcp', dport => '2598' },
141 ],
142 'DAAP' => [
ebd54ae9 143 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
857f62c8
DM
144 { action => 'PARAM', proto => 'tcp', dport => '3689' },
145 { action => 'PARAM', proto => 'udp', dport => '3689' },
146 ],
147 'DCC' => [
ebd54ae9 148 "Distributed Checksum Clearinghouse spam filtering mechanism",
857f62c8
DM
149 { action => 'PARAM', proto => 'tcp', dport => '6277' },
150 ],
151 'DHCPfwd' => [
ebd54ae9 152 "Forwarded DHCP traffic (bidirectional)",
857f62c8
DM
153 { action => 'PARAM', proto => 'udp', dport => '67:68', sport => '67:68' },
154 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '67:68', sport => '67:68' },
155 ],
156 'DNS' => [
ebd54ae9 157 "Domain Name System traffic (upd and tcp)",
857f62c8
DM
158 { action => 'PARAM', proto => 'udp', dport => '53' },
159 { action => 'PARAM', proto => 'tcp', dport => '53' },
160 ],
161 'Distcc' => [
ebd54ae9 162 "Distributed Compiler service",
857f62c8
DM
163 { action => 'PARAM', proto => 'tcp', dport => '3632' },
164 ],
857f62c8 165 'FTP' => [
ebd54ae9 166 "File Transfer Protocol",
857f62c8
DM
167 { action => 'PARAM', proto => 'tcp', dport => '21' },
168 ],
169 'Finger' => [
ebd54ae9 170 "Finger protocol (RFC 742)",
857f62c8
DM
171 { action => 'PARAM', proto => 'tcp', dport => '79' },
172 ],
173 'GNUnet' => [
ebd54ae9 174 "GNUnet secure peer-to-peer networking traffic",
857f62c8
DM
175 { action => 'PARAM', proto => 'tcp', dport => '2086' },
176 { action => 'PARAM', proto => 'udp', dport => '2086' },
177 { action => 'PARAM', proto => 'tcp', dport => '1080' },
178 { action => 'PARAM', proto => 'udp', dport => '1080' },
179 ],
180 'GRE' => [
ebd54ae9 181 "Generic Routing Encapsulation tunneling protocol (bidirectional)",
857f62c8
DM
182 { action => 'PARAM', proto => '47' },
183 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
184 ],
185 'Git' => [
ebd54ae9 186 "Git distributed revision control traffic",
857f62c8
DM
187 { action => 'PARAM', proto => 'tcp', dport => '9418' },
188 ],
857f62c8 189 'HKP' => [
ebd54ae9 190 "OpenPGP HTTP keyserver protocol traffic",
857f62c8
DM
191 { action => 'PARAM', proto => 'tcp', dport => '11371' },
192 ],
193 'HTTP' => [
ebd54ae9 194 "Hypertext Transfer Protocol (WWW)",
961b4928
DM
195 { action => 'PARAM', proto => 'tcp', dport => '80' },
196 ],
857f62c8 197 'HTTPS' => [
ebd54ae9 198 "Hypertext Transfer Protocol (WWW) over SSL",
857f62c8
DM
199 { action => 'PARAM', proto => 'tcp', dport => '443' },
200 ],
201 'ICPV2' => [
ebd54ae9 202 "Internet Cache Protocol V2 (Squid) traffic",
857f62c8
DM
203 { action => 'PARAM', proto => 'udp', dport => '3130' },
204 ],
205 'ICQ' => [
ebd54ae9 206 "AOL Instant Messenger traffic",
857f62c8
DM
207 { action => 'PARAM', proto => 'tcp', dport => '5190' },
208 ],
209 'IMAP' => [
ebd54ae9 210 "Internet Message Access Protocol",
857f62c8
DM
211 { action => 'PARAM', proto => 'tcp', dport => '143' },
212 ],
213 'IMAPS' => [
ebd54ae9 214 "Internet Message Access Protocol over SSL",
857f62c8
DM
215 { action => 'PARAM', proto => 'tcp', dport => '993' },
216 ],
217 'IPIP' => [
ebd54ae9 218 "IPIP capsulation traffic (bidirectional)",
857f62c8
DM
219 { action => 'PARAM', proto => '94' },
220 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '94' },
221 ],
857f62c8 222 'IPsec' => [
ebd54ae9 223 "IPsec traffic (bidirectional)",
857f62c8
DM
224 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
225 { action => 'PARAM', proto => '50' },
226 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500', sport => '500' },
227 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
228 ],
229 'IPsecah' => [
ebd54ae9 230 "IPsec authentication (AH) traffic (bidirectional)",
857f62c8
DM
231 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
232 { action => 'PARAM', proto => '51' },
233 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500', sport => '500' },
234 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '51' },
235 ],
236 'IPsecnat' => [
ebd54ae9 237 "IPsec traffic and Nat-Traversal (bidirectional)",
857f62c8
DM
238 { action => 'PARAM', proto => 'udp', dport => '500' },
239 { action => 'PARAM', proto => 'udp', dport => '4500' },
240 { action => 'PARAM', proto => '50' },
241 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500' },
242 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '4500' },
243 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
244 ],
245 'IRC' => [
ebd54ae9 246 "Internet Relay Chat traffic",
857f62c8
DM
247 { action => 'PARAM', proto => 'tcp', dport => '6667' },
248 ],
857f62c8 249 'Jetdirect' => [
ebd54ae9 250 "HP Jetdirect printing",
857f62c8
DM
251 { action => 'PARAM', proto => 'tcp', dport => '9100' },
252 ],
253 'L2TP' => [
ebd54ae9 254 "Layer 2 Tunneling Protocol traffic",
857f62c8
DM
255 { action => 'PARAM', proto => 'udp', dport => '1701' },
256 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '1701' },
257 ],
258 'LDAP' => [
ebd54ae9 259 "Lightweight Directory Access Protocol traffic",
857f62c8
DM
260 { action => 'PARAM', proto => 'tcp', dport => '389' },
261 ],
262 'LDAPS' => [
ebd54ae9 263 "Secure Lightweight Directory Access Protocol traffic",
857f62c8
DM
264 { action => 'PARAM', proto => 'tcp', dport => '636' },
265 ],
266 'MSNP' => [
ebd54ae9 267 "Microsoft Notification Protocol",
857f62c8
DM
268 { action => 'PARAM', proto => 'tcp', dport => '1863' },
269 ],
270 'MSSQL' => [
ebd54ae9 271 "Microsoft SQL Server",
857f62c8
DM
272 { action => 'PARAM', proto => 'tcp', dport => '1433' },
273 ],
274 'Mail' => [
ebd54ae9 275 "Mail traffic (SMTP, SMTPS, Submission)",
857f62c8
DM
276 { action => 'PARAM', proto => 'tcp', dport => '25' },
277 { action => 'PARAM', proto => 'tcp', dport => '465' },
278 { action => 'PARAM', proto => 'tcp', dport => '587' },
279 ],
280 'Munin' => [
ebd54ae9 281 "Munin networked resource monitoring traffic",
857f62c8
DM
282 { action => 'PARAM', proto => 'tcp', dport => '4949' },
283 ],
284 'MySQL' => [
ebd54ae9 285 "MySQL server",
857f62c8
DM
286 { action => 'PARAM', proto => 'tcp', dport => '3306' },
287 ],
288 'NNTP' => [
ebd54ae9 289 "NNTP traffic (Usenet).",
857f62c8
DM
290 { action => 'PARAM', proto => 'tcp', dport => '119' },
291 ],
292 'NNTPS' => [
ebd54ae9 293 "Encrypted NNTP traffic (Usenet)",
857f62c8
DM
294 { action => 'PARAM', proto => 'tcp', dport => '563' },
295 ],
296 'NTP' => [
ebd54ae9 297 "Network Time Protocol (ntpd)",
857f62c8
DM
298 { action => 'PARAM', proto => 'udp', dport => '123' },
299 ],
300 'NTPbi' => [
ebd54ae9 301 "Bi-directional NTP (for NTP peers)",
857f62c8
DM
302 { action => 'PARAM', proto => 'udp', dport => '123' },
303 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '123' },
304 ],
857f62c8 305 'OSPF' => [
ebd54ae9 306 "OSPF multicast traffic",
857f62c8
DM
307 { action => 'PARAM', proto => '89' },
308 ],
309 'OpenVPN' => [
ebd54ae9 310 "OpenVPN traffic",
857f62c8
DM
311 { action => 'PARAM', proto => 'udp', dport => '1194' },
312 ],
313 'PCA' => [
ebd54ae9 314 "Symantec PCAnywere (tm)",
857f62c8
DM
315 { action => 'PARAM', proto => 'udp', dport => '5632' },
316 { action => 'PARAM', proto => 'tcp', dport => '5631' },
317 ],
318 'POP3' => [
ebd54ae9 319 "POP3 traffic",
857f62c8
DM
320 { action => 'PARAM', proto => 'tcp', dport => '110' },
321 ],
322 'POP3S' => [
ebd54ae9 323 "Encrypted POP3 traffic",
857f62c8
DM
324 { action => 'PARAM', proto => 'tcp', dport => '995' },
325 ],
326 'PPtP' => [
ebd54ae9 327 "Point-to-Point Tunneling Protocol",
857f62c8
DM
328 { action => 'PARAM', proto => '47' },
329 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
330 { action => 'PARAM', proto => 'tcp', dport => '1723' },
331 ],
332 'Ping' => [
ebd54ae9 333 "ICMP echo request",
269d4f13 334 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
857f62c8
DM
335 ],
336 'PostgreSQL' => [
ebd54ae9 337 "PostgreSQL server",
857f62c8
DM
338 { action => 'PARAM', proto => 'tcp', dport => '5432' },
339 ],
340 'Printer' => [
ebd54ae9 341 "Line Printer protocol printing",
857f62c8
DM
342 { action => 'PARAM', proto => 'tcp', dport => '515' },
343 ],
344 'RDP' => [
ebd54ae9 345 "Microsoft Remote Desktop Protocol traffic",
857f62c8
DM
346 { action => 'PARAM', proto => 'tcp', dport => '3389' },
347 ],
348 'RIPbi' => [
ebd54ae9 349 "Routing Information Protocol (bidirectional)",
857f62c8
DM
350 { action => 'PARAM', proto => 'udp', dport => '520' },
351 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '520' },
352 ],
353 'RNDC' => [
ebd54ae9 354 "BIND remote management protocol",
857f62c8
DM
355 { action => 'PARAM', proto => 'tcp', dport => '953' },
356 ],
357 'Razor' => [
ebd54ae9 358 "Razor Antispam System",
857f62c8
DM
359 { action => 'ACCEPT', proto => 'tcp', dport => '2703' },
360 ],
361 'Rdate' => [
ebd54ae9 362 "Remote time retrieval (rdate)",
857f62c8
DM
363 { action => 'PARAM', proto => 'tcp', dport => '37' },
364 ],
365 'Rsync' => [
ebd54ae9 366 "Rsync server",
857f62c8
DM
367 { action => 'PARAM', proto => 'tcp', dport => '873' },
368 ],
369 'SANE' => [
ebd54ae9 370 "SANE network scanning",
857f62c8
DM
371 { action => 'PARAM', proto => 'tcp', dport => '6566' },
372 ],
373 'SMB' => [
ebd54ae9 374 "Microsoft SMB traffic",
857f62c8
DM
375 { action => 'PARAM', proto => 'udp', dport => '135,445' },
376 { action => 'PARAM', proto => 'udp', dport => '137:139' },
377 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
378 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
379 ],
380 'SMBBI' => [
ebd54ae9 381 "Microsoft SMB traffic (bidirectional)",
857f62c8
DM
382 { action => 'PARAM', proto => 'udp', dport => '135,445' },
383 { action => 'PARAM', proto => 'udp', dport => '137:139' },
384 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
385 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
386 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '135,445' },
387 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '137:139' },
388 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '1024:65535', sport => '137' },
389 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'tcp', dport => '135,139,445' },
390 ],
391 'SMBswat' => [
ebd54ae9 392 "Samba Web Administration Tool",
857f62c8
DM
393 { action => 'PARAM', proto => 'tcp', dport => '901' },
394 ],
395 'SMTP' => [
ebd54ae9 396 "Simple Mail Transfer Protocol",
857f62c8
DM
397 { action => 'PARAM', proto => 'tcp', dport => '25' },
398 ],
399 'SMTPS' => [
ebd54ae9 400 "Encrypted Simple Mail Transfer Protocol",
857f62c8
DM
401 { action => 'PARAM', proto => 'tcp', dport => '465' },
402 ],
403 'SNMP' => [
ebd54ae9 404 "Simple Network Management Protocol",
857f62c8
DM
405 { action => 'PARAM', proto => 'udp', dport => '161:162' },
406 { action => 'PARAM', proto => 'tcp', dport => '161' },
407 ],
408 'SPAMD' => [
ebd54ae9 409 "Spam Assassin SPAMD traffic",
857f62c8
DM
410 { action => 'PARAM', proto => 'tcp', dport => '783' },
411 ],
412 'SSH' => [
ebd54ae9 413 "Secure shell traffic",
857f62c8
DM
414 { action => 'PARAM', proto => 'tcp', dport => '22' },
415 ],
416 'SVN' => [
ebd54ae9 417 "Subversion server (svnserve)",
857f62c8
DM
418 { action => 'PARAM', proto => 'tcp', dport => '3690' },
419 ],
420 'SixXS' => [
ebd54ae9 421 "SixXS IPv6 Deployment and Tunnel Broker",
857f62c8
DM
422 { action => 'PARAM', proto => 'tcp', dport => '3874' },
423 { action => 'PARAM', proto => 'udp', dport => '3740' },
424 { action => 'PARAM', proto => '41' },
425 { action => 'PARAM', proto => 'udp', dport => '5072,8374' },
426 ],
427 'Squid' => [
ebd54ae9 428 "Squid web proxy traffic",
857f62c8
DM
429 { action => 'PARAM', proto => 'tcp', dport => '3128' },
430 ],
431 'Submission' => [
ebd54ae9 432 "Mail message submission traffic",
857f62c8
DM
433 { action => 'PARAM', proto => 'tcp', dport => '587' },
434 ],
435 'Syslog' => [
ebd54ae9 436 "Syslog protocol (RFC 5424) traffic",
857f62c8
DM
437 { action => 'PARAM', proto => 'udp', dport => '514' },
438 { action => 'PARAM', proto => 'tcp', dport => '514' },
439 ],
440 'TFTP' => [
ebd54ae9 441 "Trivial File Transfer Protocol traffic",
857f62c8
DM
442 { action => 'PARAM', proto => 'udp', dport => '69' },
443 ],
444 'Telnet' => [
ebd54ae9 445 "Telnet traffic",
857f62c8
DM
446 { action => 'PARAM', proto => 'tcp', dport => '23' },
447 ],
448 'Telnets' => [
ebd54ae9 449 "Telnet over SSL",
857f62c8
DM
450 { action => 'PARAM', proto => 'tcp', dport => '992' },
451 ],
452 'Time' => [
ebd54ae9 453 "RFC 868 Time protocol",
857f62c8
DM
454 { action => 'PARAM', proto => 'tcp', dport => '37' },
455 ],
456 'Trcrt' => [
ebd54ae9 457 "Traceroute (for up to 30 hops) traffic",
857f62c8 458 { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
269d4f13 459 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
857f62c8
DM
460 ],
461 'VNC' => [
ebd54ae9 462 "VNC traffic for VNC display's 0 - 9",
857f62c8
DM
463 { action => 'PARAM', proto => 'tcp', dport => '5900:5909' },
464 ],
465 'VNCL' => [
ebd54ae9 466 "VNC traffic from Vncservers to Vncviewers in listen mode",
857f62c8
DM
467 { action => 'PARAM', proto => 'tcp', dport => '5500' },
468 ],
469 'Web' => [
ebd54ae9 470 "WWW traffic (HTTP and HTTPS)",
857f62c8 471 { action => 'PARAM', proto => 'tcp', dport => '80' },
961b4928
DM
472 { action => 'PARAM', proto => 'tcp', dport => '443' },
473 ],
857f62c8 474 'Webcache' => [
ebd54ae9 475 "Web Cache/Proxy traffic (port 8080)",
857f62c8
DM
476 { action => 'PARAM', proto => 'tcp', dport => '8080' },
477 ],
478 'Webmin' => [
ebd54ae9 479 "Webmin traffic",
857f62c8
DM
480 { action => 'PARAM', proto => 'tcp', dport => '10000' },
481 ],
482 'Whois' => [
ebd54ae9 483 "Whois (nicname, RFC 3912) traffic",
857f62c8
DM
484 { action => 'PARAM', proto => 'tcp', dport => '43' },
485 ],
961b4928
DM
486};
487
488my $pve_fw_parsed_macros;
ebd54ae9 489my $pve_fw_macro_descr;
961b4928 490my $pve_fw_preferred_macro_names = {};
3a616aa0 491
d8f2505e
DM
492my $pve_std_chains = {
493 'PVEFW-SET-ACCEPT-MARK' => [
494 "-j MARK --set-mark 1",
495 ],
79929d9c
DM
496 'PVEFW-DropBroadcast' => [
497 # same as shorewall 'Broadcast'
498 # simply DROP BROADCAST/MULTICAST/ANYCAST
499 # we can use this to reduce logging
500 { action => 'DROP', dsttype => 'BROADCAST' },
501 { action => 'DROP', dsttype => 'MULTICAST' },
502 { action => 'DROP', dsttype => 'ANYCAST' },
cbb5d6f3 503 { action => 'DROP', dest => '224.0.0.0/4' },
79929d9c
DM
504 ],
505 'PVEFW-reject' => [
506 # same as shorewall 'reject'
507 { action => 'DROP', dsttype => 'BROADCAST' },
cbb5d6f3 508 { action => 'DROP', source => '224.0.0.0/4' },
79929d9c
DM
509 { action => 'DROP', proto => 'icmp' },
510 "-p tcp -j REJECT --reject-with tcp-reset",
511 "-p udp -j REJECT --reject-with icmp-port-unreachable",
512 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
513 "-j REJECT --reject-with icmp-host-prohibited",
514 ],
515 'PVEFW-Drop' => [
cbb5d6f3 516 # same as shorewall 'Drop', which is equal to DROP,
79929d9c
DM
517 # but REJECT/DROP some packages to reduce logging,
518 # and ACCEPT critical ICMP types
519 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
520 # we are not interested in BROADCAST/MULTICAST/ANYCAST
521 { action => 'PVEFW-DropBroadcast' },
522 # ACCEPT critical ICMP types
523 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
524 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
525 # Drop packets with INVALID state
526 "-m conntrack --ctstate INVALID -j DROP",
527 # Drop Microsoft SMB noise
528 { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 },
529 { action => 'DROP', proto => 'udp', dport => '137:139'},
530 { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
531 { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
532 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
533 # Drop new/NotSyn traffic so that it doesn't get logged
534 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
535 # Drop DNS replies
536 { action => 'DROP', proto => 'udp', sport => 53 },
537 ],
538 'PVEFW-Reject' => [
cbb5d6f3 539 # same as shorewall 'Reject', which is equal to Reject,
79929d9c
DM
540 # but REJECT/DROP some packages to reduce logging,
541 # and ACCEPT critical ICMP types
542 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
543 # we are not interested in BROADCAST/MULTICAST/ANYCAST
544 { action => 'PVEFW-DropBroadcast' },
545 # ACCEPT critical ICMP types
546 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
547 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
548 # Drop packets with INVALID state
549 "-m conntrack --ctstate INVALID -j DROP",
550 # Drop Microsoft SMB noise
551 { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
552 { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'},
553 { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 },
554 { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
555 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
556 # Drop new/NotSyn traffic so that it doesn't get logged
557 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
558 # Drop DNS replies
559 { action => 'DROP', proto => 'udp', sport => 53 },
560 ],
d86659ef
DM
561 'PVEFW-tcpflags' => [
562 # same as shorewall tcpflags action.
563 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
564 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
565 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
566 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
567 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
568 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
569 ],
bee633ab
DM
570 'PVEFW-smurfs' => [
571 # same as shorewall smurfs action
572 # Filter packets for smurfs (packets with a broadcast address as the source).
573 "-s 0.0.0.0/32 -j RETURN",
574 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
575 "-s 224.0.0.0/4 -g PVEFW-smurflog",
576 ],
d8f2505e
DM
577};
578
4b586518
DM
579# iptables -p icmp -h
580my $icmp_type_names = {
581 any => 1,
582 'echo-reply' => 1,
583 'destination-unreachable' => 1,
584 'network-unreachable' => 1,
585 'host-unreachable' => 1,
586 'protocol-unreachable' => 1,
587 'port-unreachable' => 1,
588 'fragmentation-needed' => 1,
589 'source-route-failed' => 1,
590 'network-unknown' => 1,
591 'host-unknown' => 1,
592 'network-prohibited' => 1,
593 'host-prohibited' => 1,
594 'TOS-network-unreachable' => 1,
595 'TOS-host-unreachable' => 1,
596 'communication-prohibited' => 1,
597 'host-precedence-violation' => 1,
598 'precedence-cutoff' => 1,
599 'source-quench' => 1,
600 'redirect' => 1,
601 'network-redirect' => 1,
602 'host-redirect' => 1,
603 'TOS-network-redirect' => 1,
604 'TOS-host-redirect' => 1,
605 'echo-request' => 1,
606 'router-advertisement' => 1,
607 'router-solicitation' => 1,
608 'time-exceeded' => 1,
609 'ttl-zero-during-transit' => 1,
610 'ttl-zero-during-reassembly' => 1,
611 'parameter-problem' => 1,
612 'ip-header-bad' => 1,
613 'required-option-missing' => 1,
614 'timestamp-request' => 1,
615 'timestamp-reply' => 1,
616 'address-mask-request' => 1,
617 'address-mask-reply' => 1,
618};
619
54cd19a8 620sub init_firewall_macros {
6158271d 621
961b4928 622 $pve_fw_parsed_macros = {};
9aab3127 623
961b4928 624 foreach my $k (keys %$pve_fw_macros) {
e5076eee
DM
625 my $lc_name = lc($k);
626 my $macro = $pve_fw_macros->{$k};
ebd54ae9
DM
627 if (!ref($macro->[0])) {
628 $pve_fw_macro_descr->{$k} = shift @$macro;
629 }
e5076eee
DM
630 $pve_fw_preferred_macro_names->{$lc_name} = $k;
631 $pve_fw_parsed_macros->{$k} = $macro;
961b4928 632 }
9aab3127
DM
633}
634
54cd19a8
DM
635init_firewall_macros();
636
ebd54ae9
DM
637sub get_macros {
638 return wantarray ? ($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
639}
640
fcba0beb
DM
641my $etc_services;
642
643sub get_etc_services {
644
645 return $etc_services if $etc_services;
646
647 my $filename = "/etc/services";
648
649 my $fh = IO::File->new($filename, O_RDONLY);
650 if (!$fh) {
651 warn "unable to read '$filename' - $!\n";
652 return {};
653 }
654
655 my $services = {};
656
657 while (my $line = <$fh>) {
658 chomp ($line);
659 next if $line =~m/^#/;
660 next if ($line =~m/^\s*$/);
661
662 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
663 $services->{byid}->{$2}->{name} = $1;
35b66e9d 664 $services->{byid}->{$2}->{port} = $2;
fcba0beb
DM
665 $services->{byid}->{$2}->{$3} = 1;
666 $services->{byname}->{$1} = $services->{byid}->{$2};
667 }
668 }
669
670 close($fh);
671
6158271d
DM
672 $etc_services = $services;
673
3a616aa0 674
fcba0beb
DM
675 return $etc_services;
676}
677
678my $etc_protocols;
679
680sub get_etc_protocols {
681 return $etc_protocols if $etc_protocols;
682
683 my $filename = "/etc/protocols";
684
685 my $fh = IO::File->new($filename, O_RDONLY);
686 if (!$fh) {
687 warn "unable to read '$filename' - $!\n";
688 return {};
689 }
690
691 my $protocols = {};
692
693 while (my $line = <$fh>) {
694 chomp ($line);
695 next if $line =~m/^#/;
696 next if ($line =~m/^\s*$/);
697
698 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
699 $protocols->{byid}->{$2}->{name} = $1;
700 $protocols->{byname}->{$1} = $protocols->{byid}->{$2};
701 }
702 }
703
704 close($fh);
705
706 $etc_protocols = $protocols;
707
708 return $etc_protocols;
709}
710
ecbea048
DM
711sub parse_address_list {
712 my ($str) = @_;
713
28311400 714 return if $str =~ m/^(\+)(\S+)$/; # ipset ref
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
da6fc60b 1096 return 1 if $name =~ m/^vmbr\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 {
530c005e
DM
1381 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
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");
3cc81077
DM
1396 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-in -j $bridge-OUT");
1397 ruleset_insertrule($ruleset, "PVEFW-INPUT", "-i $bridge -m physdev --physdev-is-in -j $bridge-OUT");
9fcad984
AD
1398 }
1399
1400 if (!ruleset_chain_exist($ruleset, "$bridge-IN")) {
1401 ruleset_create_chain($ruleset, "$bridge-IN");
3cc81077 1402 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j $bridge-IN");
fdb0bf20 1403 ruleset_addrule($ruleset, "$bridge-FW", "-m mark --mark 1 -j ACCEPT");
7323008d 1404 # accept traffic to unmanaged bridge ports
3cc81077 1405 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j ACCEPT ");
3fa83edf
DM
1406 }
1407}
3a616aa0 1408
ead850e8 1409sub ruleset_add_chain_policy {
782c4cde 1410 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
ead850e8
DM
1411
1412 if ($policy eq 'ACCEPT') {
1413
1414 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1415 { ACCEPT => $accept_action});
1416
1417 } elsif ($policy eq 'DROP') {
1418
1419 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1420
782c4cde 1421 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1422
1423 ruleset_addrule($ruleset, $chain, "-j DROP");
1424 } elsif ($policy eq 'REJECT') {
1425 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1426
782c4cde 1427 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1428
1429 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1430 } else {
1431 # should not happen
1432 die "internal error: unknown policy '$policy'";
1433 }
1434}
1435
9e15114a 1436sub ruleset_create_vm_chain {
6bafd113 1437 my ($ruleset, $chain, $options, $host_options, $macaddr, $direction) = @_;
3a616aa0 1438
9e15114a 1439 ruleset_create_chain($ruleset, $chain);
b47ecc88 1440 my $accept = generate_nfqueue($options);
3a616aa0 1441
6bafd113 1442 if (!(defined($host_options->{nosmurfs}) && $host_options->{nosmurfs} == 0)) {
9e15114a 1443 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
bee633ab
DM
1444 }
1445
ce15d90b 1446 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
76a2d1e7 1447 if ($direction eq 'OUT') {
cbb5d6f3 1448 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
0f168d7b 1449 proto => 'udp', sport => 68, dport => 67 });
76a2d1e7 1450 } else {
cbb5d6f3 1451 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
0f168d7b 1452 proto => 'udp', sport => 67, dport => 68 });
76a2d1e7 1453 }
ce15d90b
DM
1454 }
1455
6bafd113 1456 if ($host_options->{tcpflags}) {
9e15114a 1457 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
bee633ab
DM
1458 }
1459
9e15114a 1460 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
cbb5d6f3 1461 if ($direction eq 'OUT') {
b47ecc88 1462 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -g PVEFW-SET-ACCEPT-MARK");
cbb5d6f3 1463 } else {
b47ecc88
AD
1464 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1465 }
cbb5d6f3 1466
b21aca2c
DM
1467 if ($direction eq 'OUT') {
1468 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
9e15114a 1469 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
b21aca2c 1470 }
9e15114a 1471 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
c29f55c9 1472 }
9e15114a
DM
1473}
1474
1475sub ruleset_generate_vm_rules {
fca39c2c 1476 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
9e15114a
DM
1477
1478 my $lc_direction = lc($direction);
c29f55c9 1479
92e976b3
DM
1480 foreach my $rule (@$rules) {
1481 next if $rule->{iface} && $rule->{iface} ne $netid;
ea9e5116 1482 next if !$rule->{enable};
92e976b3 1483 if ($rule->{type} eq 'group') {
cbb5d6f3 1484 my $group_chain = "GROUP-$rule->{action}-$direction";
92e976b3 1485 if(!ruleset_chain_exist($ruleset, $group_chain)){
fca39c2c 1486 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
92e976b3 1487 }
9e15114a 1488 ruleset_addrule($ruleset, $chain, "-j $group_chain");
b47ecc88
AD
1489 if ($direction eq 'OUT'){
1490 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j RETURN");
1491 }else{
1492 my $accept = generate_nfqueue($options);
1493 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $accept");
1494 }
1495
92e976b3
DM
1496 } else {
1497 next if $rule->{type} ne $lc_direction;
1498 if ($direction eq 'OUT') {
cbb5d6f3 1499 ruleset_generate_rule($ruleset, $chain, $rule,
ba791b1f 1500 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
4e6112f9 1501 } else {
b47ecc88 1502 my $accept = generate_nfqueue($options);
ba791b1f 1503 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject" }, undef, $cluster_conf);
3a616aa0 1504 }
4e6112f9 1505 }
3a616aa0 1506 }
9e15114a
DM
1507}
1508
b47ecc88
AD
1509sub generate_nfqueue {
1510 my ($options) = @_;
1511
1512 my $action = "";
1513 if($options->{ips}){
1514 $action = "NFQUEUE";
1515 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1516 if(defined($3) && defined($1)) {
1517 $action .= " --queue-balance $1:$3";
1518 }elsif (defined($1)) {
1519 $action .= " --queue-num $1";
1520 }
1521 }
8dc92812 1522 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
b47ecc88
AD
1523 }else{
1524 $action = "ACCEPT";
1525 }
1526
1527 return $action;
1528}
1529
da6fc60b
AD
1530sub ruleset_generate_vm_ipsrules {
1531 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1532
1533 if ($options->{ips} && $direction eq 'IN') {
1534 my $nfqueue = generate_nfqueue($options);
1535
1536 if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
1537 ruleset_create_chain($ruleset, "PVEFW-IPS");
1538 }
1539
1540 if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
1541 ruleset_create_chain($ruleset, "$bridge-IPS");
1542 ruleset_insertrule($ruleset, "PVEFW-IPS", "-o $bridge -m physdev --physdev-is-out -j $bridge-IPS");
1543 }
1544
1545 ruleset_addrule($ruleset, "$bridge-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
1546 }
1547}
1548
9e15114a 1549sub generate_venet_rules_direction {
6bafd113 1550 my ($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
9e15114a 1551
5176619e 1552 parse_address_list($ip); # make sure we have a valid $ip list
9e15114a
DM
1553
1554 my $lc_direction = lc($direction);
1555
1556 my $rules = $vmfw_conf->{rules};
1557
1558 my $options = $vmfw_conf->{options};
6bafd113 1559 my $hostfw_options = $vmfw_conf->{options};
9e15114a
DM
1560 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1561
1562 my $chain = "venet0-$vmid-$direction";
1563
6bafd113 1564 ruleset_create_vm_chain($ruleset, $chain, $options, $hostfw_options, undef, $direction);
9e15114a 1565
fca39c2c 1566 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
9e15114a
DM
1567
1568 # implement policy
1569 my $policy;
1570
1571 if ($direction eq 'OUT') {
1572 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1573 } else {
1574 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1575 }
1576
b47ecc88
AD
1577 my $accept = generate_nfqueue($options);
1578 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1579 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
9e15114a 1580
38485daa 1581 # plug into FORWARD, INPUT and OUTPUT chain
eba0fb64
DM
1582 if ($direction eq 'OUT') {
1583 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD", {
1584 action => $chain,
1585 source => $ip,
1586 iface_in => 'venet0'});
38485daa
DM
1587
1588 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT", {
1589 action => $chain,
1590 source => $ip,
1591 iface_in => 'venet0'});
eba0fb64
DM
1592 } else {
1593 ruleset_generate_rule($ruleset, "PVEFW-FORWARD", {
1594 action => $chain,
1595 dest => $ip,
1596 iface_out => 'venet0'});
38485daa
DM
1597
1598 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT", {
1599 action => $chain,
1600 dest => $ip,
1601 iface_out => 'venet0'});
eba0fb64 1602 }
9e15114a
DM
1603}
1604
1605sub generate_tap_rules_direction {
6bafd113 1606 my ($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
9e15114a
DM
1607
1608 my $lc_direction = lc($direction);
1609
1610 my $rules = $vmfw_conf->{rules};
1611
1612 my $options = $vmfw_conf->{options};
6bafd113 1613 my $hostfw_options = $hostfw_conf->{options};
9e15114a
DM
1614 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1615
1616 my $tapchain = "$iface-$direction";
1617
6bafd113 1618 ruleset_create_vm_chain($ruleset, $tapchain, $options, $hostfw_options, $macaddr, $direction);
9e15114a 1619
fca39c2c 1620 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
3a616aa0 1621
da6fc60b
AD
1622 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1623
ccae0b50
DM
1624 # implement policy
1625 my $policy;
1626
1627 if ($direction eq 'OUT') {
72f63fde 1628 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
ccae0b50 1629 } else {
72f63fde 1630 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
ccae0b50
DM
1631 }
1632
b47ecc88
AD
1633 my $accept = generate_nfqueue($options);
1634 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1635 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
3a616aa0 1636
3fa83edf 1637 # plug the tap chain to bridge chain
3cc81077
DM
1638 if ($direction eq 'IN') {
1639 ruleset_insertrule($ruleset, "$bridge-IN",
1640 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
1641 } else {
1642 ruleset_insertrule($ruleset, "$bridge-OUT",
1643 "-m physdev --physdev-in $iface -j $tapchain");
1644 }
3a616aa0
AD
1645}
1646
d18c1e2b 1647sub enable_host_firewall {
fca39c2c 1648 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
0bd5f137 1649
92e976b3 1650 my $options = $hostfw_conf->{options};
63324b09 1651 my $cluster_options = $cluster_conf->{options};
92e976b3 1652 my $rules = $hostfw_conf->{rules};
35f0c37e 1653 my $cluster_rules = $cluster_conf->{rules};
178a63be 1654
3fa83edf 1655 # host inbound firewall
dec84fcd
DM
1656 my $chain = "PVEFW-HOST-IN";
1657 ruleset_create_chain($ruleset, $chain);
0bd5f137 1658
178a63be
DM
1659 my $loglevel = get_option_log_level($options, "log_level_in");
1660
4ac863a6
DM
1661 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1662 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1663 }
1664
fb424a00
DM
1665 if ($options->{tcpflags}) {
1666 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1667 }
1668
7fab95bc
DM
1669 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1670 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
dec84fcd
DM
1671 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
1672 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
97156ecc 1673 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
dec84fcd 1674 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
0bd5f137 1675
23e888f8
DM
1676 # we use RETURN because we need to check also tap rules
1677 my $accept_action = 'RETURN';
1678
35f0c37e
DM
1679 # add host rules first, so that cluster wide rules can be overwritten
1680 foreach my $rule (@$rules, @$cluster_rules) {
92e976b3 1681 next if $rule->{type} ne 'in';
ba791b1f 1682 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
0bd5f137
AD
1683 }
1684
23e888f8 1685 # implement input policy
63324b09 1686 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
782c4cde 1687 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
0bd5f137 1688
3fa83edf 1689 # host outbound firewall
aadd745e 1690 $chain = "PVEFW-HOST-OUT";
dec84fcd
DM
1691 ruleset_create_chain($ruleset, $chain);
1692
178a63be
DM
1693 $loglevel = get_option_log_level($options, "log_level_out");
1694
7fab95bc
DM
1695 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1696 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
dec84fcd
DM
1697 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
1698 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
97156ecc 1699 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
dec84fcd 1700 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
0bd5f137 1701
23e888f8
DM
1702 # we use RETURN because we may want to check other thigs later
1703 $accept_action = 'RETURN';
1704
35f0c37e
DM
1705 # add host rules first, so that cluster wide rules can be overwritten
1706 foreach my $rule (@$rules, @$cluster_rules) {
92e976b3 1707 next if $rule->{type} ne 'out';
ba791b1f 1708 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
0bd5f137
AD
1709 }
1710
23e888f8 1711 # implement output policy
63324b09 1712 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
782c4cde 1713 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
6158271d 1714
dec84fcd
DM
1715 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1716 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
9d31b418
AD
1717}
1718
1719sub generate_group_rules {
fca39c2c 1720 my ($ruleset, $cluster_conf, $group) = @_;
c6f5cc88 1721 die "no such security group '$group'\n" if !$cluster_conf->{groups}->{$group};
9d31b418 1722
c6f5cc88 1723 my $rules = $cluster_conf->{groups}->{$group};
6158271d 1724
3fa83edf 1725 my $chain = "GROUP-${group}-IN";
9d31b418 1726
3fa83edf 1727 ruleset_create_chain($ruleset, $chain);
b47ecc88 1728 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 1729
92e976b3
DM
1730 foreach my $rule (@$rules) {
1731 next if $rule->{type} ne 'in';
ba791b1f 1732 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418
AD
1733 }
1734
3fa83edf 1735 $chain = "GROUP-${group}-OUT";
9d31b418 1736
3fa83edf 1737 ruleset_create_chain($ruleset, $chain);
4e6112f9 1738 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 1739
92e976b3
DM
1740 foreach my $rule (@$rules) {
1741 next if $rule->{type} ne 'out';
1742 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1743 # check also other tap rules later
cbb5d6f3 1744 ruleset_generate_rule($ruleset, $chain, $rule,
ba791b1f 1745 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418 1746 }
9d31b418
AD
1747}
1748
51bae274
DM
1749my $MAX_NETS = 32;
1750my $valid_netdev_names = {};
1751for (my $i = 0; $i < $MAX_NETS; $i++) {
1752 $valid_netdev_names->{"net$i"} = 1;
1753}
5e1267a5 1754
51bae274
DM
1755sub parse_fw_rule {
1756 my ($line, $need_iface, $allow_groups) = @_;
5e1267a5 1757
92e976b3 1758 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
51bae274 1759
11bac5c2 1760 # we can add single line comments to the end of the rule
30c1ae52 1761 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
11bac5c2
DM
1762
1763 # we can disable a rule when prefixed with '|'
ea9e5116
DM
1764 my $enable = 1;
1765
1766 $enable = 0 if $line =~ s/^\|//;
51bae274
DM
1767
1768 my @data = split(/\s+/, $line);
92e976b3 1769 my $expected_elements = $need_iface ? 8 : 7;
51bae274
DM
1770
1771 die "wrong number of rule elements\n" if scalar(@data) > $expected_elements;
1772
1773 if ($need_iface) {
92e976b3 1774 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
51bae274 1775 } else {
92e976b3 1776 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
51bae274
DM
1777 }
1778
92e976b3 1779 die "incomplete rule\n" if ! ($type && $action);
51bae274 1780
961b4928 1781 my $macro;
961b4928 1782
92e976b3
DM
1783 $type = lc($type);
1784
1785 if ($type eq 'in' || $type eq 'out') {
1786 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1787 # OK
1788 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
e5076eee
DM
1789 $action = $2;
1790 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1791 die "unknown macro '$1'\n" if !$preferred_name;
1792 $macro = $preferred_name;
92e976b3
DM
1793 } else {
1794 die "unknown action '$action'\n";
1795 }
1796 } elsif ($type eq 'group') {
1797 die "wrong number of rule elements\n" if scalar(@data) != 3;
1798 die "groups disabled\n" if !$allow_groups;
1799
c14dacdf 1800 die "invalid characters in group name\n" if $action !~ m/^${security_group_pattern}$/;
51bae274 1801 } else {
92e976b3 1802 die "unknown rule type '$type'\n";
51bae274
DM
1803 }
1804
1805 if ($need_iface) {
1806 $iface = undef if $iface && $iface eq '-';
51bae274
DM
1807 }
1808
1809 $proto = undef if $proto && $proto eq '-';
54cd19a8 1810 pve_fw_verify_protocol_spec($proto) if $proto;
51bae274
DM
1811
1812 $source = undef if $source && $source eq '-';
1813 $dest = undef if $dest && $dest eq '-';
1814
1815 $dport = undef if $dport && $dport eq '-';
1816 $sport = undef if $sport && $sport eq '-';
1817
e5076eee
DM
1818 parse_port_name_number_or_range($dport) if defined($dport);
1819 parse_port_name_number_or_range($sport) if defined($sport);
ba791b1f 1820
d72beb8e
DM
1821 parse_address_list($source) if $source;
1822 parse_address_list($dest) if $dest;
51bae274 1823
e5076eee 1824 return {
92e976b3 1825 type => $type,
ea9e5116 1826 enable => $enable,
11bac5c2 1827 comment => $comment,
51bae274 1828 action => $action,
e5076eee 1829 macro => $macro,
51bae274
DM
1830 iface => $iface,
1831 source => $source,
1832 dest => $dest,
51bae274
DM
1833 proto => $proto,
1834 dport => $dport,
1835 sport => $sport,
51bae274
DM
1836 };
1837}
1838
2d404ffc 1839sub parse_vmfw_option {
85c6eaed
DM
1840 my ($line) = @_;
1841
1842 my ($opt, $value);
1843
178a63be
DM
1844 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1845
6bafd113 1846 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
9c6b6efd
DM
1847 $opt = lc($1);
1848 $value = int($2);
178a63be
DM
1849 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1850 $opt = lc($1);
1851 $value = $2 ? lc($3) : '';
72f63fde 1852 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
85c6eaed
DM
1853 $opt = lc($1);
1854 $value = uc($3);
b47ecc88
AD
1855 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1856 $opt = lc($1);
1857 $value = $2;
9c6b6efd 1858 } else {
85c6eaed
DM
1859 chomp $line;
1860 die "can't parse option '$line'\n"
1861 }
1862
1863 return ($opt, $value);
1864}
1865
2d404ffc
DM
1866sub parse_hostfw_option {
1867 my ($line) = @_;
1868
1869 my ($opt, $value);
1870
1871 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1872
9166ddf8 1873 if ($line =~ m/^(enable|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
2d404ffc
DM
1874 $opt = lc($1);
1875 $value = int($2);
178a63be 1876 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2d404ffc
DM
1877 $opt = lc($1);
1878 $value = $2 ? lc($3) : '';
28c082a1 1879 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
490cdead
DM
1880 $opt = lc($1);
1881 $value = int($2);
2d404ffc
DM
1882 } else {
1883 chomp $line;
1884 die "can't parse option '$line'\n"
1885 }
1886
1887 return ($opt, $value);
1888}
1889
c6f5cc88
DM
1890sub parse_clusterfw_option {
1891 my ($line) = @_;
1892
1893 my ($opt, $value);
1894
1895 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1896 $opt = lc($1);
1897 $value = int($2);
63324b09
DM
1898 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1899 $opt = lc($1);
1900 $value = uc($3);
c6f5cc88
DM
1901 } else {
1902 chomp $line;
1903 die "can't parse option '$line'\n"
1904 }
1905
1906 return ($opt, $value);
1907}
1908
92e1209b
AD
1909sub parse_clusterfw_alias {
1910 my ($line) = @_;
1911
1912 my ($opt, $value);
1913 if ($line =~ m/^(\S+)\s(\S+)$/) {
1914 $opt = lc($1);
1915 if($2){
1916 $2 =~ s|/32$||;
1917 pve_verify_ipv4_or_cidr($2) if $2;
1918 $value = $2;
1919 }
1920 } else {
1921 chomp $line;
1922 die "can't parse option '$line'\n";
1923 }
1924
1925 return ($opt, $value);
1926}
1927
51bae274
DM
1928sub parse_vm_fw_rules {
1929 my ($filename, $fh) = @_;
1930
92e976b3 1931 my $res = { rules => [], options => {}};
51bae274
DM
1932
1933 my $section;
1934
5e1267a5
DM
1935 while (defined(my $line = <$fh>)) {
1936 next if $line =~ m/^#/;
1937 next if $line =~ m/^\s*$/;
1938
961b4928
DM
1939 my $linenr = $fh->input_line_number();
1940 my $prefix = "$filename (line $linenr)";
1941
85c6eaed 1942 if ($line =~ m/^\[(\S+)\]\s*$/i) {
5e1267a5 1943 $section = lc($1);
85c6eaed 1944 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
5e1267a5
DM
1945 next;
1946 }
51bae274 1947 if (!$section) {
961b4928 1948 warn "$prefix: skip line - no section";
5e1267a5
DM
1949 next;
1950 }
1951
85c6eaed
DM
1952 next if !$res->{$section}; # skip undefined section
1953
1954 if ($section eq 'options') {
6158271d 1955 eval {
2d404ffc 1956 my ($opt, $value) = parse_vmfw_option($line);
85c6eaed
DM
1957 $res->{options}->{$opt} = $value;
1958 };
1959 warn "$prefix: $@" if $@;
1960 next;
1961 }
1962
e5076eee
DM
1963 my $rule;
1964 eval { $rule = parse_fw_rule($line, 1, 1); };
51bae274 1965 if (my $err = $@) {
961b4928 1966 warn "$prefix: $err";
5e1267a5
DM
1967 next;
1968 }
1969
e5076eee 1970 push @{$res->{$section}}, $rule;
51bae274
DM
1971 }
1972
1973 return $res;
1974}
1975
1976sub parse_host_fw_rules {
1977 my ($filename, $fh) = @_;
1978
92e976b3 1979 my $res = { rules => [], options => {}};
51bae274
DM
1980
1981 my $section;
1982
1983 while (defined(my $line = <$fh>)) {
1984 next if $line =~ m/^#/;
1985 next if $line =~ m/^\s*$/;
1986
961b4928
DM
1987 my $linenr = $fh->input_line_number();
1988 my $prefix = "$filename (line $linenr)";
1989
2d404ffc 1990 if ($line =~ m/^\[(\S+)\]\s*$/i) {
51bae274 1991 $section = lc($1);
2d404ffc 1992 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
5e1267a5
DM
1993 next;
1994 }
51bae274 1995 if (!$section) {
961b4928 1996 warn "$prefix: skip line - no section";
5e1267a5
DM
1997 next;
1998 }
1999
2d404ffc
DM
2000 next if !$res->{$section}; # skip undefined section
2001
2002 if ($section eq 'options') {
2003 eval {
2d404ffc
DM
2004 my ($opt, $value) = parse_hostfw_option($line);
2005 $res->{options}->{$opt} = $value;
2006 };
2007 warn "$prefix: $@" if $@;
2008 next;
2009 }
2010
e5076eee
DM
2011 my $rule;
2012 eval { $rule = parse_fw_rule($line, 1, 1); };
ecbea048 2013 if (my $err = $@) {
961b4928 2014 warn "$prefix: $err";
ecbea048 2015 next;
ecbea048 2016 }
cbb5d6f3 2017
e5076eee 2018 push @{$res->{$section}}, $rule;
51bae274 2019 }
ecbea048 2020
51bae274
DM
2021 return $res;
2022}
4cdbb3b7 2023
c6f5cc88 2024sub parse_cluster_fw_rules {
51bae274 2025 my ($filename, $fh) = @_;
5e1267a5 2026
51bae274
DM
2027 my $section;
2028 my $group;
2029
0d22acb3
DM
2030 my $res = {
2031 rules => [],
2032 options => {},
2033 groups => {},
2034 group_comments => {},
d72c631c
DM
2035 ipset => {} ,
2036 ipset_comments => {},
0d22acb3 2037 };
6158271d 2038
51bae274
DM
2039 while (defined(my $line = <$fh>)) {
2040 next if $line =~ m/^#/;
2041 next if $line =~ m/^\s*$/;
2042
961b4928
DM
2043 my $linenr = $fh->input_line_number();
2044 my $prefix = "$filename (line $linenr)";
2045
c6f5cc88
DM
2046 if ($line =~ m/^\[options\]$/i) {
2047 $section = 'options';
2048 next;
2049 }
2050
92e1209b
AD
2051 if ($line =~ m/^\[aliases\]$/i) {
2052 $section = 'aliases';
2053 next;
2054 }
2055
0d22acb3 2056 if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
c6f5cc88 2057 $section = 'groups';
92e976b3 2058 $group = lc($1);
0d22acb3 2059 my $comment = $2;
c85c87f9 2060 $res->{$section}->{$group} = [];
649e4d57
DM
2061 $res->{group_comments}->{$group} = decode('utf8', $comment)
2062 if $comment;
51bae274
DM
2063 next;
2064 }
34cdedfa 2065
c6f5cc88
DM
2066 if ($line =~ m/^\[rules\]$/i) {
2067 $section = 'rules';
2068 next;
2069 }
cbb5d6f3 2070
d72c631c 2071 if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
34cdedfa
AD
2072 $section = 'ipset';
2073 $group = lc($1);
d72c631c 2074 my $comment = $2;
c85c87f9 2075 $res->{$section}->{$group} = [];
649e4d57
DM
2076 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
2077 if $comment;
34cdedfa
AD
2078 next;
2079 }
2080
c6f5cc88 2081 if (!$section) {
cbb5d6f3 2082 warn "$prefix: skip line - no section\n";
51bae274
DM
2083 next;
2084 }
2085
c6f5cc88
DM
2086 if ($section eq 'options') {
2087 eval {
2088 my ($opt, $value) = parse_clusterfw_option($line);
2089 $res->{options}->{$opt} = $value;
2090 };
2091 warn "$prefix: $@" if $@;
92e1209b
AD
2092 } elsif ($section eq 'aliases') {
2093 eval {
2094 my ($opt, $value) = parse_clusterfw_alias($line);
2095 $res->{aliases}->{$opt} = $value;
2096 };
2097 warn "$prefix: $@" if $@;
c6f5cc88
DM
2098 } elsif ($section eq 'rules') {
2099 my $rule;
2100 eval { $rule = parse_fw_rule($line, 1, 1); };
2101 if (my $err = $@) {
2102 warn "$prefix: $err";
2103 next;
2104 }
2105 push @{$res->{$section}}, $rule;
2106 } elsif ($section eq 'groups') {
34cdedfa
AD
2107 my $rule;
2108 eval { $rule = parse_fw_rule($line, 0, 0); };
2109 if (my $err = $@) {
2110 warn "$prefix: $err";
2111 next;
2112 }
3f95d14a 2113 push @{$res->{$section}->{$group}}, $rule;
3f95d14a 2114 } elsif ($section eq 'ipset') {
9d6f90e6
DM
2115 # we can add single line comments to the end of the rule
2116 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2117
30f1b100 2118 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2a052ee3 2119 my $nomatch = $1;
9d6f90e6 2120 my $cidr = $2;
2a052ee3 2121
92e1209b
AD
2122 if($cidr !~ m/^${security_group_pattern}$/) {
2123 $cidr =~ s|/32$||;
30f1b100 2124
92e1209b
AD
2125 eval { pve_verify_ipv4_or_cidr($cidr); };
2126 if (my $err = $@) {
2127 warn "$prefix: $cidr - $err";
2128 next;
2129 }
2a052ee3 2130 }
2a052ee3 2131
9d6f90e6
DM
2132 my $entry = { cidr => $cidr };
2133 $entry->{nomatch} = 1 if $nomatch;
2134 $entry->{comment} = $comment if $comment;
2135
2136 push @{$res->{$section}->{$group}}, $entry;
51bae274 2137 }
5e1267a5
DM
2138 }
2139
2140 return $res;
2141}
2142
06320eb0
DM
2143sub run_locked {
2144 my ($code, @param) = @_;
2145
2146 my $timeout = 10;
2147
2148 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2149
2150 die $@ if $@;
2151
2152 return $res;
2153}
2154
5e1267a5
DM
2155sub read_local_vm_config {
2156
2157 my $openvz = {};
5e1267a5
DM
2158 my $qemu = {};
2159
c8301d63 2160 my $vmdata = { openvz => $openvz, qemu => $qemu };
5e1267a5 2161
c8301d63
DM
2162 my $vmlist = PVE::Cluster::get_vmlist();
2163 return $vmdata if !$vmlist || !$vmlist->{ids};
2164 my $ids = $vmlist->{ids};
2165
2166 foreach my $vmid (keys %$ids) {
2167 next if !$vmid; # skip VE0
2168 my $d = $ids->{$vmid};
2169 next if !$d->{node} || $d->{node} ne $nodename;
2170 next if !$d->{type};
2171 if ($d->{type} eq 'openvz') {
d9fee004
DM
2172 if ($have_pve_manager) {
2173 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2174 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2175 $openvz->{$vmid} = $conf;
2176 }
c8301d63
DM
2177 }
2178 } elsif ($d->{type} eq 'qemu') {
d9fee004
DM
2179 if ($have_qemu_server) {
2180 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2181 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2182 $qemu->{$vmid} = $conf;
2183 }
c8301d63 2184 }
5e1267a5
DM
2185 }
2186 }
d9fee004 2187
5e1267a5
DM
2188 return $vmdata;
2189};
2190
e7b35711
DM
2191sub load_vmfw_conf {
2192 my ($vmid) = @_;
2193
2194 my $vmfw_conf = {};
2195
2196 my $filename = "/etc/pve/firewall/$vmid.fw";
2197 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2198 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2199 }
2200
2201 return $vmfw_conf;
2202}
2203
464f933e
DM
2204my $format_rules = sub {
2205 my ($rules, $need_iface) = @_;
2206
2207 my $raw = '';
2208
2209 foreach my $rule (@$rules) {
c14dacdf 2210 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
464f933e
DM
2211 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2212 $raw .= uc($rule->{type});
7ca36671
DM
2213 if ($rule->{macro}) {
2214 $raw .= " $rule->{macro}($rule->{action})";
2215 } else {
2216 $raw .= " " . $rule->{action};
2217 }
464f933e 2218 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
c14dacdf
DM
2219
2220 if ($rule->{type} ne 'group') {
2221 $raw .= " " . ($rule->{source} || '-');
2222 $raw .= " " . ($rule->{dest} || '-');
2223 $raw .= " " . ($rule->{proto} || '-');
2224 $raw .= " " . ($rule->{dport} || '-');
2225 $raw .= " " . ($rule->{sport} || '-');
2226 }
2227
cbb5d6f3 2228 $raw .= " # " . encode('utf8', $rule->{comment})
464f933e
DM
2229 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2230 $raw .= "\n";
2231 } else {
c14dacdf 2232 die "unknown rule type '$rule->{type}'";
464f933e
DM
2233 }
2234 }
2235
2236 return $raw;
2237};
2238
2239my $format_options = sub {
68c90e21
DM
2240 my ($options) = @_;
2241
2242 my $raw = '';
464f933e
DM
2243
2244 $raw .= "[OPTIONS]\n\n";
2245 foreach my $opt (keys %$options) {
2246 $raw .= "$opt: $options->{$opt}\n";
2247 }
2248 $raw .= "\n";
68c90e21
DM
2249
2250 return $raw;
464f933e
DM
2251};
2252
9d6f90e6
DM
2253my $format_ipset = sub {
2254 my ($options) = @_;
2255
2256 my $raw = '';
2257
6e299ae3 2258 my $nethash = {};
9d6f90e6 2259 foreach my $entry (@$options) {
6e299ae3
DM
2260 $nethash->{$entry->{cidr}} = $entry;
2261 }
2262
2263 foreach my $cidr (sort keys %$nethash) {
2264 my $entry = $nethash->{$cidr};
9d6f90e6
DM
2265 my $line = $entry->{nomatch} ? '!' : '';
2266 $line .= $entry->{cidr};
2267 $line .= " # " . encode('utf8', $entry->{comment})
2268 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2269 $raw .= "$line\n";
2270 }
2271
2272 return $raw;
2273};
2274
464f933e
DM
2275sub save_vmfw_conf {
2276 my ($vmid, $vmfw_conf) = @_;
2277
2278 my $raw = '';
2279
2280 my $options = $vmfw_conf->{options};
68c90e21 2281 $raw .= &$format_options($options) if scalar(keys %$options);
cbb5d6f3 2282
464f933e
DM
2283 my $rules = $vmfw_conf->{rules};
2284 if (scalar(@$rules)) {
2285 $raw .= "[RULES]\n\n";
2286 $raw .= &$format_rules($rules, 1);
2287 $raw .= "\n";
2288 }
2289
2290 my $filename = "/etc/pve/firewall/$vmid.fw";
2291 PVE::Tools::file_set_contents($filename, $raw);
2292}
2293
6fc63ffd 2294sub read_vm_firewall_configs {
5e1267a5 2295 my ($vmdata) = @_;
6fc63ffd 2296 my $vmfw_configs = {};
c8301d63 2297
5e1267a5 2298 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
e7b35711
DM
2299 my $vmfw_conf = load_vmfw_conf($vmid);
2300 next if !$vmfw_conf->{options}; # skip if file does not exists
2301 $vmfw_configs->{$vmid} = $vmfw_conf;
5e1267a5
DM
2302 }
2303
6fc63ffd 2304 return $vmfw_configs;
5e1267a5
DM
2305}
2306
2d404ffc
DM
2307sub get_option_log_level {
2308 my ($options, $k) = @_;
2309
2310 my $v = $options->{$k};
178a63be 2311 $v = $default_log_level if !defined($v);
2d404ffc
DM
2312
2313 return undef if $v eq '' || $v eq 'nolog';
2314
2315 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2316
2317 return $v if ($v >= 0) && ($v <= 7);
2318
2319 warn "unknown log level ($k = '$v')\n";
2320
2321 return undef;
2322}
2323
d8f2505e 2324sub generate_std_chains {
2d404ffc 2325 my ($ruleset, $options) = @_;
cbb5d6f3 2326
2d404ffc
DM
2327 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2328
2329 # same as shorewall smurflog.
782c4cde 2330 my $chain = 'PVEFW-smurflog';
12f3796e 2331 $pve_std_chains->{$chain} = [];
782c4cde
DM
2332
2333 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2334 push @{$pve_std_chains->{$chain}}, "-j DROP";
2d404ffc
DM
2335
2336 # same as shorewall logflags action.
2337 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
782c4cde 2338 $chain = 'PVEFW-logflags';
12f3796e
DM
2339 $pve_std_chains->{$chain} = [];
2340
782c4cde
DM
2341 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2342 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2343 push @{$pve_std_chains->{$chain}}, "-j DROP";
d8f2505e
DM
2344
2345 foreach my $chain (keys %$pve_std_chains) {
2346 ruleset_create_chain($ruleset, $chain);
2347 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2348 if (ref($rule)) {
2349 ruleset_generate_rule($ruleset, $chain, $rule);
2350 } else {
2351 ruleset_addrule($ruleset, $chain, $rule);
2352 }
2353 }
2354 }
2355}
2356
34cdedfa 2357sub generate_ipset_chains {
dd7a13fd 2358 my ($ipset_ruleset, $fw_conf) = @_;
34cdedfa 2359
dd7a13fd 2360 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
92e1209b 2361 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset}, $fw_conf->{aliases});
34cdedfa
AD
2362 }
2363}
2364
2365sub generate_ipset {
92e1209b 2366 my ($ipset_ruleset, $name, $options, $aliases) = @_;
34cdedfa 2367
dd7a13fd
DM
2368 my $hashsize = scalar(@$options);
2369 if ($hashsize <= 64) {
2a052ee3 2370 $hashsize = 64;
dd7a13fd 2371 } else {
2a052ee3
AD
2372 $hashsize = round_powerof2($hashsize);
2373 }
2374
dd7a13fd 2375 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
34cdedfa 2376
30f1b100
DM
2377 # remove duplicates
2378 my $nethash = {};
9d6f90e6 2379 foreach my $entry (@$options) {
92e1209b
AD
2380 my $cidr = $entry->{cidr};
2381 #check aliases
2382 if ($cidr =~ m/^${security_group_pattern}$/){
2383 die "no such alias $cidr" if !$aliases->{$cidr};
2384 $entry->{cidr} = $aliases->{$cidr};
2385 }
30f1b100
DM
2386 $nethash->{$entry->{cidr}} = $entry;
2387 }
2388
2389 foreach my $cidr (sort keys %$nethash) {
2390 my $entry = $nethash->{$cidr};
2391
9d6f90e6
DM
2392 my $cmd = "add $name $cidr";
2393 if ($entry->{nomatch}) {
2394 if ($feature_ipset_nomatch) {
2395 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2396 } else {
2397 warn "ignore !$cidr - nomatch not supported by kernel\n";
2398 }
2399 } else {
2400 push @{$ipset_ruleset->{$name}}, $cmd;
2401 }
34cdedfa 2402 }
2a052ee3
AD
2403}
2404
2405sub round_powerof2 {
dd7a13fd 2406 my ($int) = @_;
2a052ee3 2407
dd7a13fd
DM
2408 $int--;
2409 $int |= $int >> $_ foreach (1,2,4,8,16);
2410 return ++$int;
34cdedfa
AD
2411}
2412
6b9f68a2
DM
2413sub save_pvefw_status {
2414 my ($status) = @_;
2415
2416 die "unknown status '$status' - internal error"
2417 if $status !~ m/^(stopped|active)$/;
2418
2419 mkdir dirname($pve_fw_status_filename);
2420 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2421}
2422
2423sub read_pvefw_status {
2424
2425 my $status = 'unknown';
2426
2427 return 'stopped' if ! -f $pve_fw_status_filename;
2428
2429 eval {
2430 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2431 };
2432 warn $@ if $@;
2433
2434 return $status;
2435}
2436
530c005e
DM
2437# fixme: move to pve-common PVE::ProcFSTools
2438sub read_proc_net_route {
2439 my $filename = "/proc/net/route";
2440
2441 my $res = {};
2442
2443 my $fh = IO::File->new ($filename, "r");
2444 return $res if !$fh;
2445
2446 my $int_to_quad = sub {
2447 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2448 };
2449
2450 while (defined(my $line = <$fh>)) {
2451 next if $line =~/^Iface\s+Destination/; # skip head
2452 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2453 push @{$res->{$iface}}, {
2454 dest => &$int_to_quad(hex($dest)),
2455 gateway => &$int_to_quad(hex($gateway)),
2456 mask => &$int_to_quad(hex($mask)),
2457 metric => $metric,
2458 mtu => $mtu,
2459 };
2460 }
2461
2462 return $res;
2463}
2464
fca39c2c 2465sub load_clusterfw_conf {
530c005e 2466
fca39c2c
DM
2467 my $cluster_conf = {};
2468 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
c6f5cc88 2469 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
51bae274 2470 }
5e1267a5 2471
fca39c2c 2472 return $cluster_conf;
e5d76bde
DM
2473}
2474
fca39c2c
DM
2475sub save_clusterfw_conf {
2476 my ($cluster_conf) = @_;
9c7e0858
DM
2477
2478 my $raw = '';
9c7e0858 2479
c6f5cc88 2480 my $options = $cluster_conf->{options};
68c90e21 2481 $raw .= &$format_options($options) if scalar(keys %$options);
9c7e0858 2482
9d6f90e6 2483 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
d72c631c 2484 if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
649e4d57
DM
2485 my $utf8comment = encode('utf8', $comment);
2486 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
d72c631c
DM
2487 } else {
2488 $raw .= "[IPSET $ipset]\n\n";
2489 }
9d6f90e6
DM
2490 my $options = $cluster_conf->{ipset}->{$ipset};
2491 $raw .= &$format_ipset($options);
2492 $raw .= "\n";
2493 }
c6f5cc88
DM
2494
2495 my $rules = $cluster_conf->{rules};
2496 if (scalar(@$rules)) {
2497 $raw .= "[RULES]\n\n";
63c91681 2498 $raw .= &$format_rules($rules, 1);
c6f5cc88
DM
2499 $raw .= "\n";
2500 }
2501
2502 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2503 my $rules = $cluster_conf->{groups}->{$group};
0d22acb3 2504 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
649e4d57
DM
2505 my $utf8comment = encode('utf8', $comment);
2506 $raw .= "[group $group] # $utf8comment\n\n";
0d22acb3
DM
2507 } else {
2508 $raw .= "[group $group]\n\n";
2509 }
2510
63c91681 2511 $raw .= &$format_rules($rules, 0);
9c7e0858
DM
2512 $raw .= "\n";
2513 }
2514
fca39c2c 2515 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
9c7e0858
DM
2516}
2517
8b27beb9
DM
2518sub load_hostfw_conf {
2519
2520 my $hostfw_conf = {};
63c91681
DM
2521 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2522 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
8b27beb9
DM
2523 }
2524 return $hostfw_conf;
2525}
2526
63c91681
DM
2527sub save_hostfw_conf {
2528 my ($hostfw_conf) = @_;
2529
2530 my $raw = '';
2531
2532 my $options = $hostfw_conf->{options};
68c90e21 2533 $raw .= &$format_options($options) if scalar(keys %$options);
cbb5d6f3 2534
63c91681
DM
2535 my $rules = $hostfw_conf->{rules};
2536 if (scalar(@$rules)) {
2537 $raw .= "[RULES]\n\n";
2538 $raw .= &$format_rules($rules, 1);
2539 $raw .= "\n";
2540 }
2541
2542 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2543}
2544
e5d76bde 2545sub compile {
3dfa8a7f
DM
2546 my ($cluster_conf, $hostfw_conf) = @_;
2547
2548 $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
2549 $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
2550
e5d76bde
DM
2551 my $vmdata = read_local_vm_config();
2552 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2553
2554 my $routing_table = read_proc_net_route();
2555
34cdedfa 2556 my $ipset_ruleset = {};
fca39c2c 2557 generate_ipset_chains($ipset_ruleset, $cluster_conf);
34cdedfa 2558
3fa83edf
DM
2559 my $ruleset = {};
2560
dec84fcd
DM
2561 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2562 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
5b1df9a0 2563
fadb13dd 2564 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3fa83edf 2565
8b27beb9 2566 my $hostfw_options = $hostfw_conf->{options} || {};
fadb13dd 2567
92e976b3 2568 generate_std_chains($ruleset, $hostfw_options);
fadb13dd 2569
6d2ab017 2570 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2d404ffc 2571
fca39c2c 2572 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
3fa83edf 2573
6158271d 2574 # generate firewall rules for QEMU VMs
3fa83edf
DM
2575 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2576 my $conf = $vmdata->{qemu}->{$vmid};
6fc63ffd 2577 my $vmfw_conf = $vmfw_configs->{$vmid};
fa9c4a6f
DM
2578 next if !$vmfw_conf;
2579 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
3fa83edf
DM
2580
2581 foreach my $netid (keys %$conf) {
2582 next if $netid !~ m/^net(\d+)$/;
2583 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2584 next if !$net;
2585 my $iface = "tap${vmid}i$1";
5e1267a5 2586
3fa83edf
DM
2587 my $bridge = $net->{bridge};
2588 next if !$bridge; # fixme: ?
2589
2590 $bridge .= "v$net->{tag}" if $net->{tag};
2591
530c005e 2592 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
3fa83edf 2593
c29f55c9 2594 my $macaddr = $net->{macaddr};
6bafd113 2595 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
782c4cde 2596 $vmfw_conf, $vmid, $bridge, 'IN');
6bafd113 2597 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
782c4cde 2598 $vmfw_conf, $vmid, $bridge, 'OUT');
3fa83edf
DM
2599 }
2600 }
c8301d63
DM
2601
2602 # generate firewall rules for OpenVZ containers
2603 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2604 my $conf = $vmdata->{openvz}->{$vmid};
2605
2606 my $vmfw_conf = $vmfw_configs->{$vmid};
2607 next if !$vmfw_conf;
2608 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2609
2610 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2611 my $ip = $conf->{ip_address}->{value};
6bafd113
DM
2612 generate_venet_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, 'IN');
2613 generate_venet_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, 'OUT');
c8301d63
DM
2614 }
2615
2616 if ($conf->{netif} && $conf->{netif}->{value}) {
2617 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
c8301d63
DM
2618 foreach my $netid (keys %$netif) {
2619 my $d = $netif->{$netid};
2620 my $bridge = $d->{bridge};
2621 if (!$bridge) {
2622 warn "no bridge device for CT $vmid iface '$netid'\n";
2623 next; # fixme?
2624 }
cbb5d6f3 2625
530c005e
DM
2626 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2627
12d0f130 2628 my $macaddr = $d->{mac};
c8301d63 2629 my $iface = $d->{host_ifname};
6bafd113 2630 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
782c4cde 2631 $vmfw_conf, $vmid, $bridge, 'IN');
6bafd113 2632 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
782c4cde 2633 $vmfw_conf, $vmid, $bridge, 'OUT');
c8301d63
DM
2634 }
2635 }
2636 }
c0413e35 2637
cc10e5d7 2638 if($hostfw_options->{optimize}){
da6fc60b 2639
e9d9a73e 2640 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
da6fc60b 2641 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
cc10e5d7
AD
2642 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2643 }
2644
eba0fb64
DM
2645 # fixme: what log level should we use here?
2646 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2647
c98c037d
DM
2648 # fixme: should we really block inter-bridge traffic?
2649
2650 # always allow traffic from containers?
2651 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2652
eba0fb64 2653 # disable interbridge routing
cbb5d6f3 2654 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
eba0fb64 2655 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
cbb5d6f3
DM
2656 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2657 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2658 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
eba0fb64
DM
2659 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2660
3dfa8a7f 2661 return ($ruleset, $ipset_ruleset);
3fa83edf
DM
2662}
2663
2664sub get_ruleset_status {
4bd0a9c4 2665 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3fa83edf
DM
2666
2667 my $statushash = {};
2668
2669 foreach my $chain (sort keys %$ruleset) {
4bd0a9c4 2670 my $sig = &$digest_fn($ruleset->{$chain});
9bf7d929 2671
3fa83edf
DM
2672 $statushash->{$chain}->{sig} = $sig;
2673
2674 my $oldsig = $active_chains->{$chain};
2675 if (!defined($oldsig)) {
2676 $statushash->{$chain}->{action} = 'create';
2677 } else {
2678 if ($oldsig eq $sig) {
2679 $statushash->{$chain}->{action} = 'exists';
2680 } else {
2681 $statushash->{$chain}->{action} = 'update';
2682 }
2683 }
2684 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2685 foreach my $cmd (@{$ruleset->{$chain}}) {
2686 print "\t$cmd\n" if $verbose;
2687 }
2688 }
2689
2690 foreach my $chain (sort keys %$active_chains) {
2691 if (!defined($ruleset->{$chain})) {
2692 my $sig = $active_chains->{$chain};
2693 $statushash->{$chain}->{action} = 'delete';
2694 $statushash->{$chain}->{sig} = $sig;
2695 print "delete $chain ($sig)\n" if $verbose;
2696 }
6158271d 2697 }
2a052ee3 2698
3fa83edf
DM
2699 return $statushash;
2700}
2701
3fa83edf
DM
2702sub print_sig_rule {
2703 my ($chain, $sig) = @_;
2704
09d5f68e
DM
2705 # We just use this to store a SHA1 checksum used to detect changes
2706 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
b6360c3f
DM
2707}
2708
df7cb349 2709sub get_ruleset_cmdlist {
a84f4d96 2710 my ($ruleset, $verbose) = @_;
3fa83edf 2711
3fa83edf 2712 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
cbb5d6f3 2713
4bd0a9c4
DM
2714 my ($active_chains, $hooks) = iptables_get_chains();
2715 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3fa83edf
DM
2716
2717 # create missing chains first
2718 foreach my $chain (sort keys %$ruleset) {
2719 my $stat = $statushash->{$chain};
2720 die "internal error" if !$stat;
2721 next if $stat->{action} ne 'create';
886aba9c 2722
3fa83edf
DM
2723 $cmdlist .= ":$chain - [0:0]\n";
2724 }
2725
4bd0a9c4
DM
2726 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2727 if (!$hooks->{$h}) {
2728 $cmdlist .= "-A $h -j PVEFW-$h\n";
2729 }
3fa83edf
DM
2730 }
2731
2732 foreach my $chain (sort keys %$ruleset) {
2733 my $stat = $statushash->{$chain};
2734 die "internal error" if !$stat;
2735
2736 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
2737 $cmdlist .= "-F $chain\n";
2738 foreach my $cmd (@{$ruleset->{$chain}}) {
2739 $cmdlist .= "$cmd\n";
2740 }
2741 $cmdlist .= print_sig_rule($chain, $stat->{sig});
2742 } elsif ($stat->{action} eq 'delete') {
f5d28682 2743 die "internal error"; # this should not happen
3fa83edf
DM
2744 } elsif ($stat->{action} eq 'exists') {
2745 # do nothing
2746 } else {
2747 die "internal error - unknown status '$stat->{action}'";
2748 }
2749 }
2750
f5d28682
DM
2751 foreach my $chain (keys %$statushash) {
2752 next if $statushash->{$chain}->{action} ne 'delete';
2753 $cmdlist .= "-F $chain\n";
2754 }
2755 foreach my $chain (keys %$statushash) {
2756 next if $statushash->{$chain}->{action} ne 'delete';
fadb13dd
DM
2757 next if $chain eq 'PVEFW-INPUT';
2758 next if $chain eq 'PVEFW-OUTPUT';
2759 next if $chain eq 'PVEFW-FORWARD';
f5d28682
DM
2760 $cmdlist .= "-X $chain\n";
2761 }
2762
3f95d14a 2763 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
4bd0a9c4 2764
3fa83edf
DM
2765 $cmdlist .= "COMMIT\n";
2766
3f95d14a 2767 return wantarray ? ($cmdlist, $changes) : $cmdlist;
6b9f68a2
DM
2768}
2769
34cdedfa 2770sub get_ipset_cmdlist {
dd7a13fd 2771 my ($ruleset, $verbose) = @_;
34cdedfa
AD
2772
2773 my $cmdlist = "";
2774
dd7a13fd
DM
2775 my $delete_cmdlist = "";
2776
4bd0a9c4
DM
2777 my $active_chains = ipset_get_chains();
2778 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
34cdedfa 2779
30f1b100
DM
2780 # remove stale _swap chains
2781 foreach my $chain (keys %$active_chains) {
2782 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2783 $cmdlist .= "destroy $chain\n";
2784 }
2785 }
2786
dd7a13fd
DM
2787 foreach my $chain (sort keys %$ruleset) {
2788 my $stat = $statushash->{$chain};
2789 die "internal error" if !$stat;
2a052ee3 2790
dd7a13fd
DM
2791 if ($stat->{action} eq 'create') {
2792 foreach my $cmd (@{$ruleset->{$chain}}) {
34cdedfa
AD
2793 $cmdlist .= "$cmd\n";
2794 }
dd7a13fd 2795 }
34cdedfa 2796
dd7a13fd
DM
2797 if ($stat->{action} eq 'update') {
2798 my $chain_swap = $chain."_swap";
cbb5d6f3 2799
dd7a13fd
DM
2800 foreach my $cmd (@{$ruleset->{$chain}}) {
2801 $cmd =~ s/$chain/$chain_swap/;
2802 $cmdlist .= "$cmd\n";
34cdedfa 2803 }
dd7a13fd
DM
2804 $cmdlist .= "swap $chain_swap $chain\n";
2805 $cmdlist .= "flush $chain_swap\n";
2806 $cmdlist .= "destroy $chain_swap\n";
2a052ee3 2807 }
34cdedfa 2808
dd7a13fd 2809 }
3f95d14a 2810
dd7a13fd
DM
2811 foreach my $chain (keys %$statushash) {
2812 next if $statushash->{$chain}->{action} ne 'delete';
2a052ee3 2813
dd7a13fd
DM
2814 $delete_cmdlist .= "flush $chain\n";
2815 $delete_cmdlist .= "destroy $chain\n";
34cdedfa
AD
2816 }
2817
dd7a13fd 2818 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
cbb5d6f3 2819
dd7a13fd 2820 return ($cmdlist, $delete_cmdlist, $changes);
34cdedfa
AD
2821}
2822
6b9f68a2 2823sub apply_ruleset {
34cdedfa 2824 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
6b9f68a2
DM
2825
2826 enable_bridge_firewall();
2827
edb75ba9
DM
2828 update_nf_conntrack_max($hostfw_conf);
2829
28c082a1
AD
2830 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
2831
cbb5d6f3 2832 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
81a0bf43 2833 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
6b9f68a2 2834
81a0bf43 2835 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
2a052ee3 2836
81a0bf43
DM
2837 if ($verbose) {
2838 if ($ipset_changes) {
2839 print "ipset changes:\n";
2840 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2841 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2842 }
3f95d14a 2843
81a0bf43
DM
2844 if ($changes) {
2845 print "iptables changes:\n";
2846 print $cmdlist;
2847 }
2848 }
3fa83edf 2849
2a052ee3 2850 ipset_restore_cmdlist($ipset_create_cmdlist);
34cdedfa 2851
3fa83edf
DM
2852 iptables_restore_cmdlist($cmdlist);
2853
dd7a13fd 2854 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2a052ee3 2855
6158271d 2856 # test: re-read status and check if everything is up to date
4bd0a9c4 2857 my $active_chains = iptables_get_chains();
81a0bf43 2858 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3fa83edf
DM
2859
2860 my $errors;
2861 foreach my $chain (sort keys %$ruleset) {
2862 my $stat = $statushash->{$chain};
2863 if ($stat->{action} ne 'exists') {
2864 warn "unable to update chain '$chain'\n";
2865 $errors = 1;
2866 }
2867 }
b6360c3f 2868
3fa83edf 2869 die "unable to apply firewall changes\n" if $errors;
b6360c3f
DM
2870}
2871
490cdead
DM
2872sub update_nf_conntrack_max {
2873 my ($hostfw_conf) = @_;
2874
2875 my $max = 65536; # reasonable default
2876
2877 my $options = $hostfw_conf->{options} || {};
2878
2879 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
2880 $max = $options->{nf_conntrack_max};
2881 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2882 }
2883
2884 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2885 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2886
2887 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
2888
2889 if ($current != $max) {
2890 my $hashsize = int($max/4);
2891 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
2892 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
2893 }
2894}
2895
28c082a1
AD
2896sub update_nf_conntrack_tcp_timeout_established {
2897 my ($hostfw_conf) = @_;
2898
2899 my $options = $hostfw_conf->{options} || {};
2900
2901 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
2902
2903 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
2904}
2905
c4a2e5ae
DM
2906sub remove_pvefw_chains {
2907
2908 my ($chash, $hooks) = iptables_get_chains();
2909 my $cmdlist = "*filter\n";
2910
2911 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2912 if ($hooks->{$h}) {
2913 $cmdlist .= "-D $h -j PVEFW-$h\n";
2914 }
2915 }
cbb5d6f3 2916
c4a2e5ae
DM
2917 foreach my $chain (keys %$chash) {
2918 $cmdlist .= "-F $chain\n";
2919 }
2920
2921 foreach my $chain (keys %$chash) {
2922 $cmdlist .= "-X $chain\n";
2923 }
2924 $cmdlist .= "COMMIT\n";
2925
2926 iptables_restore_cmdlist($cmdlist);
2927}
2928
6b9f68a2
DM
2929sub update {
2930 my ($start, $verbose) = @_;
2931
2932 my $code = sub {
3dfa8a7f
DM
2933
2934 my $cluster_conf = load_clusterfw_conf();
2935 my $cluster_options = $cluster_conf->{options};
2936
51e57fee 2937 my $enable = $cluster_options->{enable};
3dfa8a7f 2938
6b9f68a2
DM
2939 my $status = read_pvefw_status();
2940
3dfa8a7f
DM
2941 die "Firewall is disabled - cannot start\n" if !$enable && $start;
2942
2943 if (!$enable) {
b22130d3 2944 PVE::Firewall::remove_pvefw_chains();
3dfa8a7f
DM
2945 print "Firewall disabled\n" if $verbose;
2946 return;
2947 }
2948
2949 my $hostfw_conf = load_hostfw_conf();
2950
2951 my ($ruleset, $ipset_ruleset) = compile($cluster_conf, $hostfw_conf);
490cdead 2952
6b9f68a2
DM
2953 if ($start || $status eq 'active') {
2954
2955 save_pvefw_status('active') if ($status ne 'active');
2956
34cdedfa 2957 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
6b9f68a2
DM
2958 } else {
2959 print "Firewall not active (status = $status)\n" if $verbose;
2960 }
2961 };
2962
2963 run_locked($code);
2964}
2965
2966
b6360c3f 29671;