]> git.proxmox.com Git - pve-firewall.git/blob - src/PVE/Firewall.pm
add ips optimizations
[pve-firewall.git] / src / PVE / Firewall.pm
1 package PVE::Firewall;
2
3 use warnings;
4 use strict;
5 use Data::Dumper;
6 use Digest::SHA;
7 use PVE::INotify;
8 use PVE::Cluster;
9 use PVE::ProcFSTools;
10 use PVE::Tools;
11 use File::Basename;
12 use File::Path;
13 use IO::File;
14 use Net::IP;
15 use PVE::Tools qw(run_command lock_file);
16 use Encode;
17
18 # dynamically include PVE::QemuServer and PVE::OpenVZ
19 # to avoid dependency problems
20 my $have_qemu_server;
21 eval {
22 require PVE::QemuServer;
23 $have_qemu_server = 1;
24 };
25
26 my $have_pve_manager;
27 eval {
28 require PVE::OpenVZ;
29 $have_pve_manager = 1;
30 };
31
32 use Data::Dumper;
33
34 my $nodename = PVE::INotify::nodename();
35
36 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
37 my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
38
39 my $default_log_level = 'info';
40
41 my $log_level_hash = {
42 debug => 7,
43 info => 6,
44 notice => 5,
45 warning => 4,
46 err => 3,
47 crit => 2,
48 alert => 1,
49 emerg => 0,
50 };
51
52 # imported/converted from: /usr/share/shorewall/macro.*
53 my $pve_fw_macros = {
54 'Amanda' => [
55 { action => 'PARAM', proto => 'udp', dport => '10080' },
56 { action => 'PARAM', proto => 'tcp', dport => '10080' },
57 ],
58 'Auth' => [
59 { action => 'PARAM', proto => 'tcp', dport => '113' },
60 ],
61 'BGP' => [
62 { action => 'PARAM', proto => 'tcp', dport => '179' },
63 ],
64 'BitTorrent' => [
65 { action => 'PARAM', proto => 'tcp', dport => '6881:6889' },
66 { action => 'PARAM', proto => 'udp', dport => '6881' },
67 ],
68 'BitTorrent32' => [
69 { action => 'PARAM', proto => 'tcp', dport => '6881:6999' },
70 { action => 'PARAM', proto => 'udp', dport => '6881' },
71 ],
72 'CVS' => [
73 { action => 'PARAM', proto => 'tcp', dport => '2401' },
74 ],
75 'Citrix' => [
76 { action => 'PARAM', proto => 'tcp', dport => '1494' },
77 { action => 'PARAM', proto => 'udp', dport => '1604' },
78 { action => 'PARAM', proto => 'tcp', dport => '2598' },
79 ],
80 'DAAP' => [
81 { action => 'PARAM', proto => 'tcp', dport => '3689' },
82 { action => 'PARAM', proto => 'udp', dport => '3689' },
83 ],
84 'DCC' => [
85 { action => 'PARAM', proto => 'tcp', dport => '6277' },
86 ],
87 'DHCPfwd' => [
88 { action => 'PARAM', proto => 'udp', dport => '67:68', sport => '67:68' },
89 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '67:68', sport => '67:68' },
90 ],
91 'DNS' => [
92 { action => 'PARAM', proto => 'udp', dport => '53' },
93 { action => 'PARAM', proto => 'tcp', dport => '53' },
94 ],
95 'Distcc' => [
96 { action => 'PARAM', proto => 'tcp', dport => '3632' },
97 ],
98 'Edonkey' => [
99 { action => 'PARAM', proto => 'tcp', dport => '4662' },
100 { action => 'PARAM', proto => 'udp', dport => '4665' },
101 ],
102 'FTP' => [
103 { action => 'PARAM', proto => 'tcp', dport => '21' },
104 ],
105 'Finger' => [
106 { action => 'PARAM', proto => 'tcp', dport => '79' },
107 ],
108 'GNUnet' => [
109 { action => 'PARAM', proto => 'tcp', dport => '2086' },
110 { action => 'PARAM', proto => 'udp', dport => '2086' },
111 { action => 'PARAM', proto => 'tcp', dport => '1080' },
112 { action => 'PARAM', proto => 'udp', dport => '1080' },
113 ],
114 'GRE' => [
115 { action => 'PARAM', proto => '47' },
116 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
117 ],
118 'Git' => [
119 { action => 'PARAM', proto => 'tcp', dport => '9418' },
120 ],
121 'Gnutella' => [
122 { action => 'PARAM', proto => 'tcp', dport => '6346' },
123 { action => 'PARAM', proto => 'udp', dport => '6346' },
124 ],
125 'HKP' => [
126 { action => 'PARAM', proto => 'tcp', dport => '11371' },
127 ],
128 'HTTP' => [
129 { action => 'PARAM', proto => 'tcp', dport => '80' },
130 ],
131 'HTTPS' => [
132 { action => 'PARAM', proto => 'tcp', dport => '443' },
133 ],
134 'ICPV2' => [
135 { action => 'PARAM', proto => 'udp', dport => '3130' },
136 ],
137 'ICQ' => [
138 { action => 'PARAM', proto => 'tcp', dport => '5190' },
139 ],
140 'IMAP' => [
141 { action => 'PARAM', proto => 'tcp', dport => '143' },
142 ],
143 'IMAPS' => [
144 { action => 'PARAM', proto => 'tcp', dport => '993' },
145 ],
146 'IPIP' => [
147 { action => 'PARAM', proto => '94' },
148 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '94' },
149 ],
150 'IPP' => [
151 { action => 'PARAM', proto => 'tcp', dport => '631' },
152 ],
153 'IPPbrd' => [
154 { action => 'PARAM', proto => 'udp', dport => '631' },
155 ],
156 'IPPserver' => [
157 { action => 'PARAM', source => 'SOURCE', dest => 'DEST', proto => 'tcp', dport => '631' },
158 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '631' },
159 ],
160 'IPsec' => [
161 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
162 { action => 'PARAM', proto => '50' },
163 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500', sport => '500' },
164 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
165 ],
166 'IPsecah' => [
167 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
168 { action => 'PARAM', proto => '51' },
169 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500', sport => '500' },
170 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '51' },
171 ],
172 'IPsecnat' => [
173 { action => 'PARAM', proto => 'udp', dport => '500' },
174 { action => 'PARAM', proto => 'udp', dport => '4500' },
175 { action => 'PARAM', proto => '50' },
176 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500' },
177 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '4500' },
178 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
179 ],
180 'IRC' => [
181 { action => 'PARAM', proto => 'tcp', dport => '6667' },
182 ],
183 'JabberPlain' => [
184 { action => 'PARAM', proto => 'tcp', dport => '5222' },
185 ],
186 'JabberSecure' => [
187 { action => 'PARAM', proto => 'tcp', dport => '5223' },
188 ],
189 'Jabberd' => [
190 { action => 'PARAM', proto => 'tcp', dport => '5269' },
191 ],
192 'Jetdirect' => [
193 { action => 'PARAM', proto => 'tcp', dport => '9100' },
194 ],
195 'L2TP' => [
196 { action => 'PARAM', proto => 'udp', dport => '1701' },
197 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '1701' },
198 ],
199 'LDAP' => [
200 { action => 'PARAM', proto => 'tcp', dport => '389' },
201 ],
202 'LDAPS' => [
203 { action => 'PARAM', proto => 'tcp', dport => '636' },
204 ],
205 'MSNP' => [
206 { action => 'PARAM', proto => 'tcp', dport => '1863' },
207 ],
208 'MSSQL' => [
209 { action => 'PARAM', proto => 'tcp', dport => '1433' },
210 ],
211 'Mail' => [
212 { action => 'PARAM', proto => 'tcp', dport => '25' },
213 { action => 'PARAM', proto => 'tcp', dport => '465' },
214 { action => 'PARAM', proto => 'tcp', dport => '587' },
215 ],
216 'Munin' => [
217 { action => 'PARAM', proto => 'tcp', dport => '4949' },
218 ],
219 'MySQL' => [
220 { action => 'PARAM', proto => 'tcp', dport => '3306' },
221 ],
222 'NNTP' => [
223 { action => 'PARAM', proto => 'tcp', dport => '119' },
224 ],
225 'NNTPS' => [
226 { action => 'PARAM', proto => 'tcp', dport => '563' },
227 ],
228 'NTP' => [
229 { action => 'PARAM', proto => 'udp', dport => '123' },
230 ],
231 'NTPbi' => [
232 { action => 'PARAM', proto => 'udp', dport => '123' },
233 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '123' },
234 ],
235 'NTPbrd' => [
236 { action => 'PARAM', proto => 'udp', dport => '123' },
237 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '123' },
238 ],
239 'OSPF' => [
240 { action => 'PARAM', proto => '89' },
241 ],
242 'OpenVPN' => [
243 { action => 'PARAM', proto => 'udp', dport => '1194' },
244 ],
245 'PCA' => [
246 { action => 'PARAM', proto => 'udp', dport => '5632' },
247 { action => 'PARAM', proto => 'tcp', dport => '5631' },
248 ],
249 'POP3' => [
250 { action => 'PARAM', proto => 'tcp', dport => '110' },
251 ],
252 'POP3S' => [
253 { action => 'PARAM', proto => 'tcp', dport => '995' },
254 ],
255 'PPtP' => [
256 { action => 'PARAM', proto => '47' },
257 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
258 { action => 'PARAM', proto => 'tcp', dport => '1723' },
259 ],
260 'Ping' => [
261 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
262 ],
263 'PostgreSQL' => [
264 { action => 'PARAM', proto => 'tcp', dport => '5432' },
265 ],
266 'Printer' => [
267 { action => 'PARAM', proto => 'tcp', dport => '515' },
268 ],
269 'RDP' => [
270 { action => 'PARAM', proto => 'tcp', dport => '3389' },
271 ],
272 'RIPbi' => [
273 { action => 'PARAM', proto => 'udp', dport => '520' },
274 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '520' },
275 ],
276 'RNDC' => [
277 { action => 'PARAM', proto => 'tcp', dport => '953' },
278 ],
279 'Razor' => [
280 { action => 'ACCEPT', proto => 'tcp', dport => '2703' },
281 ],
282 'Rdate' => [
283 { action => 'PARAM', proto => 'tcp', dport => '37' },
284 ],
285 'Rsync' => [
286 { action => 'PARAM', proto => 'tcp', dport => '873' },
287 ],
288 'SANE' => [
289 { action => 'PARAM', proto => 'tcp', dport => '6566' },
290 ],
291 'SMB' => [
292 { action => 'PARAM', proto => 'udp', dport => '135,445' },
293 { action => 'PARAM', proto => 'udp', dport => '137:139' },
294 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
295 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
296 ],
297 'SMBBI' => [
298 { action => 'PARAM', proto => 'udp', dport => '135,445' },
299 { action => 'PARAM', proto => 'udp', dport => '137:139' },
300 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
301 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
302 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '135,445' },
303 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '137:139' },
304 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '1024:65535', sport => '137' },
305 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'tcp', dport => '135,139,445' },
306 ],
307 'SMBswat' => [
308 { action => 'PARAM', proto => 'tcp', dport => '901' },
309 ],
310 'SMTP' => [
311 { action => 'PARAM', proto => 'tcp', dport => '25' },
312 ],
313 'SMTPS' => [
314 { action => 'PARAM', proto => 'tcp', dport => '465' },
315 ],
316 'SNMP' => [
317 { action => 'PARAM', proto => 'udp', dport => '161:162' },
318 { action => 'PARAM', proto => 'tcp', dport => '161' },
319 ],
320 'SPAMD' => [
321 { action => 'PARAM', proto => 'tcp', dport => '783' },
322 ],
323 'SSH' => [
324 { action => 'PARAM', proto => 'tcp', dport => '22' },
325 ],
326 'SVN' => [
327 { action => 'PARAM', proto => 'tcp', dport => '3690' },
328 ],
329 'SixXS' => [
330 { action => 'PARAM', proto => 'tcp', dport => '3874' },
331 { action => 'PARAM', proto => 'udp', dport => '3740' },
332 { action => 'PARAM', proto => '41' },
333 { action => 'PARAM', proto => 'udp', dport => '5072,8374' },
334 ],
335 'Squid' => [
336 { action => 'PARAM', proto => 'tcp', dport => '3128' },
337 ],
338 'Submission' => [
339 { action => 'PARAM', proto => 'tcp', dport => '587' },
340 ],
341 'Syslog' => [
342 { action => 'PARAM', proto => 'udp', dport => '514' },
343 { action => 'PARAM', proto => 'tcp', dport => '514' },
344 ],
345 'TFTP' => [
346 { action => 'PARAM', proto => 'udp', dport => '69' },
347 ],
348 'Telnet' => [
349 { action => 'PARAM', proto => 'tcp', dport => '23' },
350 ],
351 'Telnets' => [
352 { action => 'PARAM', proto => 'tcp', dport => '992' },
353 ],
354 'Time' => [
355 { action => 'PARAM', proto => 'tcp', dport => '37' },
356 ],
357 'Trcrt' => [
358 { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
359 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
360 ],
361 'VNC' => [
362 { action => 'PARAM', proto => 'tcp', dport => '5900:5909' },
363 ],
364 'VNCL' => [
365 { action => 'PARAM', proto => 'tcp', dport => '5500' },
366 ],
367 'Web' => [
368 { action => 'PARAM', proto => 'tcp', dport => '80' },
369 { action => 'PARAM', proto => 'tcp', dport => '443' },
370 ],
371 'Webcache' => [
372 { action => 'PARAM', proto => 'tcp', dport => '8080' },
373 ],
374 'Webmin' => [
375 { action => 'PARAM', proto => 'tcp', dport => '10000' },
376 ],
377 'Whois' => [
378 { action => 'PARAM', proto => 'tcp', dport => '43' },
379 ],
380 };
381
382 my $pve_fw_parsed_macros;
383 my $pve_fw_preferred_macro_names = {};
384
385 my $pve_std_chains = {
386 'PVEFW-SET-ACCEPT-MARK' => [
387 "-j MARK --set-mark 1",
388 ],
389 'PVEFW-DropBroadcast' => [
390 # same as shorewall 'Broadcast'
391 # simply DROP BROADCAST/MULTICAST/ANYCAST
392 # we can use this to reduce logging
393 { action => 'DROP', dsttype => 'BROADCAST' },
394 { action => 'DROP', dsttype => 'MULTICAST' },
395 { action => 'DROP', dsttype => 'ANYCAST' },
396 { action => 'DROP', dest => '224.0.0.0/4' },
397 ],
398 'PVEFW-reject' => [
399 # same as shorewall 'reject'
400 { action => 'DROP', dsttype => 'BROADCAST' },
401 { action => 'DROP', source => '224.0.0.0/4' },
402 { action => 'DROP', proto => 'icmp' },
403 "-p tcp -j REJECT --reject-with tcp-reset",
404 "-p udp -j REJECT --reject-with icmp-port-unreachable",
405 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
406 "-j REJECT --reject-with icmp-host-prohibited",
407 ],
408 'PVEFW-Drop' => [
409 # same as shorewall 'Drop', which is equal to DROP,
410 # but REJECT/DROP some packages to reduce logging,
411 # and ACCEPT critical ICMP types
412 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
413 # we are not interested in BROADCAST/MULTICAST/ANYCAST
414 { action => 'PVEFW-DropBroadcast' },
415 # ACCEPT critical ICMP types
416 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
417 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
418 # Drop packets with INVALID state
419 "-m conntrack --ctstate INVALID -j DROP",
420 # Drop Microsoft SMB noise
421 { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 },
422 { action => 'DROP', proto => 'udp', dport => '137:139'},
423 { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
424 { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
425 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
426 # Drop new/NotSyn traffic so that it doesn't get logged
427 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
428 # Drop DNS replies
429 { action => 'DROP', proto => 'udp', sport => 53 },
430 ],
431 'PVEFW-Reject' => [
432 # same as shorewall 'Reject', which is equal to Reject,
433 # but REJECT/DROP some packages to reduce logging,
434 # and ACCEPT critical ICMP types
435 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
436 # we are not interested in BROADCAST/MULTICAST/ANYCAST
437 { action => 'PVEFW-DropBroadcast' },
438 # ACCEPT critical ICMP types
439 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
440 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
441 # Drop packets with INVALID state
442 "-m conntrack --ctstate INVALID -j DROP",
443 # Drop Microsoft SMB noise
444 { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
445 { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'},
446 { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 },
447 { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
448 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
449 # Drop new/NotSyn traffic so that it doesn't get logged
450 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
451 # Drop DNS replies
452 { action => 'DROP', proto => 'udp', sport => 53 },
453 ],
454 'PVEFW-tcpflags' => [
455 # same as shorewall tcpflags action.
456 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
457 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
458 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
459 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
460 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
461 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
462 ],
463 'PVEFW-smurfs' => [
464 # same as shorewall smurfs action
465 # Filter packets for smurfs (packets with a broadcast address as the source).
466 "-s 0.0.0.0/32 -j RETURN",
467 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
468 "-s 224.0.0.0/4 -g PVEFW-smurflog",
469 ],
470 };
471
472 # iptables -p icmp -h
473 my $icmp_type_names = {
474 any => 1,
475 'echo-reply' => 1,
476 'destination-unreachable' => 1,
477 'network-unreachable' => 1,
478 'host-unreachable' => 1,
479 'protocol-unreachable' => 1,
480 'port-unreachable' => 1,
481 'fragmentation-needed' => 1,
482 'source-route-failed' => 1,
483 'network-unknown' => 1,
484 'host-unknown' => 1,
485 'network-prohibited' => 1,
486 'host-prohibited' => 1,
487 'TOS-network-unreachable' => 1,
488 'TOS-host-unreachable' => 1,
489 'communication-prohibited' => 1,
490 'host-precedence-violation' => 1,
491 'precedence-cutoff' => 1,
492 'source-quench' => 1,
493 'redirect' => 1,
494 'network-redirect' => 1,
495 'host-redirect' => 1,
496 'TOS-network-redirect' => 1,
497 'TOS-host-redirect' => 1,
498 'echo-request' => 1,
499 'router-advertisement' => 1,
500 'router-solicitation' => 1,
501 'time-exceeded' => 1,
502 'ttl-zero-during-transit' => 1,
503 'ttl-zero-during-reassembly' => 1,
504 'parameter-problem' => 1,
505 'ip-header-bad' => 1,
506 'required-option-missing' => 1,
507 'timestamp-request' => 1,
508 'timestamp-reply' => 1,
509 'address-mask-request' => 1,
510 'address-mask-reply' => 1,
511 };
512
513 sub get_firewall_macros {
514
515 return $pve_fw_parsed_macros if $pve_fw_parsed_macros;
516
517 $pve_fw_parsed_macros = {};
518
519 foreach my $k (keys %$pve_fw_macros) {
520 my $name = lc($k);
521
522 my $macro = $pve_fw_macros->{$k};
523 $pve_fw_preferred_macro_names->{$name} = $k;
524 $pve_fw_parsed_macros->{$name} = $macro;
525 }
526
527 return $pve_fw_parsed_macros;
528 }
529
530 my $etc_services;
531
532 sub get_etc_services {
533
534 return $etc_services if $etc_services;
535
536 my $filename = "/etc/services";
537
538 my $fh = IO::File->new($filename, O_RDONLY);
539 if (!$fh) {
540 warn "unable to read '$filename' - $!\n";
541 return {};
542 }
543
544 my $services = {};
545
546 while (my $line = <$fh>) {
547 chomp ($line);
548 next if $line =~m/^#/;
549 next if ($line =~m/^\s*$/);
550
551 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
552 $services->{byid}->{$2}->{name} = $1;
553 $services->{byid}->{$2}->{port} = $2;
554 $services->{byid}->{$2}->{$3} = 1;
555 $services->{byname}->{$1} = $services->{byid}->{$2};
556 }
557 }
558
559 close($fh);
560
561 $etc_services = $services;
562
563
564 return $etc_services;
565 }
566
567 my $etc_protocols;
568
569 sub get_etc_protocols {
570 return $etc_protocols if $etc_protocols;
571
572 my $filename = "/etc/protocols";
573
574 my $fh = IO::File->new($filename, O_RDONLY);
575 if (!$fh) {
576 warn "unable to read '$filename' - $!\n";
577 return {};
578 }
579
580 my $protocols = {};
581
582 while (my $line = <$fh>) {
583 chomp ($line);
584 next if $line =~m/^#/;
585 next if ($line =~m/^\s*$/);
586
587 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
588 $protocols->{byid}->{$2}->{name} = $1;
589 $protocols->{byname}->{$1} = $protocols->{byid}->{$2};
590 }
591 }
592
593 close($fh);
594
595 $etc_protocols = $protocols;
596
597 return $etc_protocols;
598 }
599
600 sub parse_address_list {
601 my ($str) = @_;
602
603 my $nbaor = 0;
604 foreach my $aor (split(/,/, $str)) {
605 if (!Net::IP->new($aor)) {
606 my $err = Net::IP::Error();
607 die "invalid IP address: $err\n";
608 }else{
609 $nbaor++;
610 }
611 }
612 return $nbaor;
613 }
614
615 sub parse_port_name_number_or_range {
616 my ($str) = @_;
617
618 my $services = PVE::Firewall::get_etc_services();
619 my $nbports = 0;
620 foreach my $item (split(/,/, $str)) {
621 my $portlist = "";
622 my $oldpon = undef;
623 $nbports++;
624 foreach my $pon (split(':', $item, 2)) {
625 $pon = $services->{byname}->{$pon}->{port} if $services->{byname}->{$pon}->{port};
626 if ($pon =~ m/^\d+$/){
627 die "invalid port '$pon'\n" if $pon < 0 && $pon > 65535;
628 die "port '$pon' must be bigger than port '$oldpon' \n" if $oldpon && ($pon < $oldpon);
629 $oldpon = $pon;
630 }else{
631 die "invalid port $services->{byname}->{$pon}\n" if !$services->{byname}->{$pon};
632 }
633 }
634 }
635
636 return ($nbports);
637 }
638
639 # helper function for API
640 sub cleanup_fw_rule {
641 my ($rule, $digest, $pos) = @_;
642
643 my $r = {};
644
645 foreach my $k (keys %$rule) {
646 next if $k eq 'nbdport';
647 next if $k eq 'nbsport';
648 my $v = $rule->{$k};
649 next if !defined($v);
650 $r->{$k} = $v;
651 $r->{digest} = $digest;
652 $r->{pos} = $pos;
653 }
654
655 return $r;
656 }
657
658 my $bridge_firewall_enabled = 0;
659
660 sub enable_bridge_firewall {
661
662 return if $bridge_firewall_enabled; # only once
663
664 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
665 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
666
667 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
668 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
669
670 $bridge_firewall_enabled = 1;
671 }
672
673 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
674
675 sub iptables {
676 my ($cmd) = @_;
677
678 run_command("/sbin/iptables $cmd", outfunc => sub {}, errfunc => sub {});
679 }
680
681 sub iptables_restore_cmdlist {
682 my ($cmdlist) = @_;
683
684 run_command("/sbin/iptables-restore -n", input => $cmdlist);
685 }
686
687 sub iptables_get_chains {
688
689 my $res = {};
690
691 # check what chains we want to track
692 my $is_pvefw_chain = sub {
693 my $name = shift;
694
695 return 1 if $name =~ m/^PVEFW-\S+$/;
696
697 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
698
699 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
700
701 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
702
703 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
704 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
705
706 return undef;
707 };
708
709 my $table = '';
710
711 my $parser = sub {
712 my $line = shift;
713
714 return if $line =~ m/^#/;
715 return if $line =~ m/^\s*$/;
716
717 if ($line =~ m/^\*(\S+)$/) {
718 $table = $1;
719 return;
720 }
721
722 return if $table ne 'filter';
723
724 if ($line =~ m/^:(\S+)\s/) {
725 my $chain = $1;
726 return if !&$is_pvefw_chain($chain);
727 $res->{$chain} = "unknown";
728 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
729 my ($chain, $sig) = ($1, $2);
730 return if !&$is_pvefw_chain($chain);
731 $res->{$chain} = $sig;
732 } else {
733 # simply ignore the rest
734 return;
735 }
736 };
737
738 run_command("/sbin/iptables-save", outfunc => $parser);
739
740 return $res;
741 }
742
743 sub iptables_chain_exist {
744 my ($chain) = @_;
745
746 eval{
747 iptables("-n --list $chain");
748 };
749 return undef if $@;
750
751 return 1;
752 }
753
754 sub iptables_rule_exist {
755 my ($rule) = @_;
756
757 eval{
758 iptables("-C $rule");
759 };
760 return undef if $@;
761
762 return 1;
763 }
764
765 sub ruleset_generate_cmdstr {
766 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
767
768 return if defined($rule->{enable}) && !$rule->{enable};
769
770 my @cmd = ();
771
772 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
773 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
774
775 push @cmd, "-m iprange --src-range" if $rule->{nbsource} && $rule->{nbsource} > 1;
776 push @cmd, "-s $rule->{source}" if $rule->{source};
777 push @cmd, "-m iprange --dst-range" if $rule->{nbdest} && $rule->{nbdest} > 1;
778 push @cmd, "-d $rule->{dest}" if $rule->{dest};
779
780 if ($rule->{proto}) {
781 push @cmd, "-p $rule->{proto}";
782
783 my $multiport = 0;
784 $multiport++ if $rule->{nbdport} && ($rule->{nbdport} > 1);
785 $multiport++ if $rule->{nbsport} && ($rule->{nbsport} > 1);
786
787 push @cmd, "--match multiport" if $multiport;
788
789 die "multiport: option '--sports' cannot be used together with '--dports'\n"
790 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
791
792 if ($rule->{dport}) {
793 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
794 # Note: we use dport to store --icmp-type
795 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
796 push @cmd, "-m icmp --icmp-type $rule->{dport}";
797 } else {
798 if ($rule->{nbdport} && $rule->{nbdport} > 1) {
799 if ($multiport == 2) {
800 push @cmd, "--ports $rule->{dport}";
801 } else {
802 push @cmd, "--dports $rule->{dport}";
803 }
804 } else {
805 push @cmd, "--dport $rule->{dport}";
806 }
807 }
808 }
809
810 if ($rule->{sport}) {
811 if ($rule->{nbsport} && $rule->{nbsport} > 1) {
812 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
813 } else {
814 push @cmd, "--sport $rule->{sport}";
815 }
816 }
817 } elsif ($rule->{dport} || $rule->{sport}) {
818 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport};
819 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport};
820 }
821
822 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
823
824 if (my $action = $rule->{action}) {
825 $action = $actions->{$action} if defined($actions->{$action});
826 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
827 push @cmd, $goto ? "-g $action" : "-j $action";
828 }
829
830 return scalar(@cmd) ? join(' ', @cmd) : undef;
831 }
832
833 sub ruleset_generate_rule {
834 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
835
836 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
837 ruleset_addrule($ruleset, $chain, $cmdstr);
838 }
839 }
840
841 sub ruleset_generate_rule_insert {
842 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
843
844 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
845 ruleset_insertrule($ruleset, $chain, $cmdstr);
846 }
847 }
848
849 sub ruleset_create_chain {
850 my ($ruleset, $chain) = @_;
851
852 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
853 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
854
855 die "chain '$chain' already exists\n" if $ruleset->{$chain};
856
857 $ruleset->{$chain} = [];
858 }
859
860 sub ruleset_chain_exist {
861 my ($ruleset, $chain) = @_;
862
863 return $ruleset->{$chain} ? 1 : undef;
864 }
865
866 sub ruleset_addrule {
867 my ($ruleset, $chain, $rule) = @_;
868
869 die "no such chain '$chain'\n" if !$ruleset->{$chain};
870
871 push @{$ruleset->{$chain}}, "-A $chain $rule";
872 }
873
874 sub ruleset_insertrule {
875 my ($ruleset, $chain, $rule) = @_;
876
877 die "no such chain '$chain'\n" if !$ruleset->{$chain};
878
879 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
880 }
881
882 sub get_log_rule_base {
883 my ($chain, $vmid, $msg, $loglevel) = @_;
884
885 die "internal error - no log level" if !defined($loglevel);
886
887 $vmid = 0 if !defined($vmid);
888
889 # Note: we use special format for prefix to pass further
890 # info to log daemon (VMID, LOGVELEL and CHAIN)
891
892 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
893 }
894
895 sub ruleset_addlog {
896 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
897
898 return if !defined($loglevel);
899
900 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
901
902 $logrule = "$rule $logrule" if defined($rule);
903
904 ruleset_addrule($ruleset, $chain, $logrule)
905 }
906
907 sub generate_bridge_chains {
908 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
909
910 my $options = $hostfw_conf->{options} || {};
911
912 die "error: detected direct route to bridge '$bridge'\n"
913 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
914
915 if (!ruleset_chain_exist($ruleset, "$bridge-FW")) {
916 ruleset_create_chain($ruleset, "$bridge-FW");
917 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o $bridge -m physdev --physdev-is-out -j $bridge-FW");
918 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i $bridge -m physdev --physdev-is-in -j $bridge-FW");
919 }
920
921 if (!ruleset_chain_exist($ruleset, "$bridge-OUT")) {
922 ruleset_create_chain($ruleset, "$bridge-OUT");
923 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-in -j $bridge-OUT");
924 ruleset_insertrule($ruleset, "PVEFW-INPUT", "-i $bridge -m physdev --physdev-is-in -j $bridge-OUT");
925 }
926
927 if (!ruleset_chain_exist($ruleset, "$bridge-IN")) {
928 ruleset_create_chain($ruleset, "$bridge-IN");
929 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j $bridge-IN");
930 ruleset_addrule($ruleset, "$bridge-FW", "-m mark --mark 1 -j ACCEPT");
931 # accept traffic to unmanaged bridge ports
932 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j ACCEPT ");
933 }
934 }
935
936 sub ruleset_add_chain_policy {
937 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
938
939 if ($policy eq 'ACCEPT') {
940
941 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
942 { ACCEPT => $accept_action});
943
944 } elsif ($policy eq 'DROP') {
945
946 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
947
948 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
949
950 ruleset_addrule($ruleset, $chain, "-j DROP");
951 } elsif ($policy eq 'REJECT') {
952 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
953
954 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
955
956 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
957 } else {
958 # should not happen
959 die "internal error: unknown policy '$policy'";
960 }
961 }
962
963 sub ruleset_create_vm_chain {
964 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
965
966 ruleset_create_chain($ruleset, $chain);
967 my $accept = generate_nfqueue($options);
968
969 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
970 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
971 }
972
973 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
974 if ($direction eq 'OUT') {
975 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
976 proto => 'udp', sport => 68, dport => 67 });
977 } else {
978 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
979 proto => 'udp', sport => 67, dport => 68 });
980 }
981 }
982
983 if ($options->{tcpflags}) {
984 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
985 }
986
987 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
988 if($direction eq 'OUT'){
989 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -g PVEFW-SET-ACCEPT-MARK");
990
991 }else{
992 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
993 }
994 if ($direction eq 'OUT') {
995 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
996 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
997 }
998 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
999 }
1000
1001
1002 }
1003
1004 sub ruleset_generate_vm_rules {
1005 my ($ruleset, $rules, $groups_conf, $chain, $netid, $direction, $options) = @_;
1006
1007 my $lc_direction = lc($direction);
1008
1009 foreach my $rule (@$rules) {
1010 next if $rule->{iface} && $rule->{iface} ne $netid;
1011 next if !$rule->{enable};
1012 if ($rule->{type} eq 'group') {
1013 my $group_chain = "GROUP-$rule->{action}-$direction";
1014 if(!ruleset_chain_exist($ruleset, $group_chain)){
1015 generate_group_rules($ruleset, $groups_conf, $rule->{action});
1016 }
1017 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1018 if ($direction eq 'OUT'){
1019 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j RETURN");
1020 }else{
1021 my $accept = generate_nfqueue($options);
1022 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $accept");
1023 }
1024
1025 } else {
1026 next if $rule->{type} ne $lc_direction;
1027 if ($direction eq 'OUT') {
1028 ruleset_generate_rule($ruleset, $chain, $rule,
1029 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" });
1030 } else {
1031 my $accept = generate_nfqueue($options);
1032 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject" });
1033 }
1034 }
1035 }
1036 }
1037
1038 sub generate_nfqueue {
1039 my ($options) = @_;
1040
1041 my $action = "";
1042 if($options->{ips}){
1043 $action = "NFQUEUE";
1044 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1045 if(defined($3) && defined($1)) {
1046 $action .= " --queue-balance $1:$3";
1047 }elsif (defined($1)) {
1048 $action .= " --queue-num $1";
1049 }
1050 }
1051 $action .= " --queue-bypass";
1052 }else{
1053 $action = "ACCEPT";
1054 }
1055
1056 return $action;
1057 }
1058
1059 sub ruleset_generate_vm_ipsrules {
1060 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1061
1062 if ($options->{ips} && $direction eq 'IN') {
1063 my $nfqueue = generate_nfqueue($options);
1064
1065 if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
1066 ruleset_create_chain($ruleset, "PVEFW-IPS");
1067 }
1068
1069 if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
1070 ruleset_create_chain($ruleset, "$bridge-IPS");
1071 ruleset_insertrule($ruleset, "PVEFW-IPS", "-o $bridge -m physdev --physdev-is-out -j $bridge-IPS");
1072 }
1073
1074 ruleset_addrule($ruleset, "$bridge-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
1075 }
1076 }
1077
1078 sub generate_venet_rules_direction {
1079 my ($ruleset, $groups_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1080
1081 parse_address_list($ip); # make sure we have a valid $ip list
1082
1083 my $lc_direction = lc($direction);
1084
1085 my $rules = $vmfw_conf->{rules};
1086
1087 my $options = $vmfw_conf->{options};
1088 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1089
1090 my $chain = "venet0-$vmid-$direction";
1091
1092 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1093
1094 ruleset_generate_vm_rules($ruleset, $rules, $groups_conf, $chain, 'venet', $direction);
1095
1096 # implement policy
1097 my $policy;
1098
1099 if ($direction eq 'OUT') {
1100 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1101 } else {
1102 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1103 }
1104
1105 my $accept = generate_nfqueue($options);
1106 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1107 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1108
1109 # plug into FORWARD, INPUT and OUTPUT chain
1110 if ($direction eq 'OUT') {
1111 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD", {
1112 action => $chain,
1113 source => $ip,
1114 iface_in => 'venet0'});
1115
1116 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT", {
1117 action => $chain,
1118 source => $ip,
1119 iface_in => 'venet0'});
1120 } else {
1121 ruleset_generate_rule($ruleset, "PVEFW-FORWARD", {
1122 action => $chain,
1123 dest => $ip,
1124 iface_out => 'venet0'});
1125
1126 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT", {
1127 action => $chain,
1128 dest => $ip,
1129 iface_out => 'venet0'});
1130 }
1131 }
1132
1133 sub generate_tap_rules_direction {
1134 my ($ruleset, $groups_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1135
1136 my $lc_direction = lc($direction);
1137
1138 my $rules = $vmfw_conf->{rules};
1139
1140 my $options = $vmfw_conf->{options};
1141 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1142
1143 my $tapchain = "$iface-$direction";
1144
1145 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1146
1147 ruleset_generate_vm_rules($ruleset, $rules, $groups_conf, $tapchain, $netid, $direction, $options);
1148
1149 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1150
1151 # implement policy
1152 my $policy;
1153
1154 if ($direction eq 'OUT') {
1155 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1156 } else {
1157 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1158 }
1159
1160 my $accept = generate_nfqueue($options);
1161 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1162 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1163
1164 # plug the tap chain to bridge chain
1165 if ($direction eq 'IN') {
1166 ruleset_insertrule($ruleset, "$bridge-IN",
1167 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
1168 } else {
1169 ruleset_insertrule($ruleset, "$bridge-OUT",
1170 "-m physdev --physdev-in $iface -j $tapchain");
1171 }
1172 }
1173
1174 sub enable_host_firewall {
1175 my ($ruleset, $hostfw_conf, $groups_conf) = @_;
1176
1177 # fixme: allow security groups
1178
1179 my $options = $hostfw_conf->{options};
1180 my $rules = $hostfw_conf->{rules};
1181
1182 # host inbound firewall
1183 my $chain = "PVEFW-HOST-IN";
1184 ruleset_create_chain($ruleset, $chain);
1185
1186 my $loglevel = get_option_log_level($options, "log_level_in");
1187
1188 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1189 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1190 }
1191
1192 if ($options->{tcpflags}) {
1193 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1194 }
1195
1196 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1197 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
1198 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
1199 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
1200 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
1201 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
1202
1203 # we use RETURN because we need to check also tap rules
1204 my $accept_action = 'RETURN';
1205
1206 foreach my $rule (@$rules) {
1207 next if $rule->{type} ne 'in';
1208 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" });
1209 }
1210
1211 # implement input policy
1212 my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1213 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1214
1215 # host outbound firewall
1216 $chain = "PVEFW-HOST-OUT";
1217 ruleset_create_chain($ruleset, $chain);
1218
1219 $loglevel = get_option_log_level($options, "log_level_out");
1220
1221 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1222 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
1223 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
1224 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
1225 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
1226 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
1227
1228 # we use RETURN because we may want to check other thigs later
1229 $accept_action = 'RETURN';
1230
1231 foreach my $rule (@$rules) {
1232 next if $rule->{type} ne 'out';
1233 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" });
1234 }
1235
1236 # implement output policy
1237 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1238 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1239
1240 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1241 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
1242 }
1243
1244 sub generate_group_rules {
1245 my ($ruleset, $groups_conf, $group) = @_;
1246 die "no such security group '$group'\n" if !$groups_conf->{rules}->{$group};
1247
1248 my $rules = $groups_conf->{rules}->{$group};
1249
1250 my $chain = "GROUP-${group}-IN";
1251
1252 ruleset_create_chain($ruleset, $chain);
1253 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1254
1255 foreach my $rule (@$rules) {
1256 next if $rule->{type} ne 'in';
1257 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" });
1258 }
1259
1260 $chain = "GROUP-${group}-OUT";
1261
1262 ruleset_create_chain($ruleset, $chain);
1263 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1264
1265 foreach my $rule (@$rules) {
1266 next if $rule->{type} ne 'out';
1267 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1268 # check also other tap rules later
1269 ruleset_generate_rule($ruleset, $chain, $rule,
1270 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" });
1271 }
1272 }
1273
1274 my $MAX_NETS = 32;
1275 my $valid_netdev_names = {};
1276 for (my $i = 0; $i < $MAX_NETS; $i++) {
1277 $valid_netdev_names->{"net$i"} = 1;
1278 }
1279
1280 sub parse_fw_rule {
1281 my ($line, $need_iface, $allow_groups) = @_;
1282
1283 my $macros = get_firewall_macros();
1284 my $protocols = get_etc_protocols();
1285
1286 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
1287
1288 # we can add single line comments to the end of the rule
1289 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1290
1291 # we can disable a rule when prefixed with '|'
1292 my $enable = 1;
1293
1294 $enable = 0 if $line =~ s/^\|//;
1295
1296 my @data = split(/\s+/, $line);
1297 my $expected_elements = $need_iface ? 8 : 7;
1298
1299 die "wrong number of rule elements\n" if scalar(@data) > $expected_elements;
1300
1301 if ($need_iface) {
1302 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1303 } else {
1304 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1305 }
1306
1307 die "incomplete rule\n" if ! ($type && $action);
1308
1309 my $macro;
1310 my $macro_name;
1311
1312 $type = lc($type);
1313
1314 if ($type eq 'in' || $type eq 'out') {
1315 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1316 # OK
1317 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1318 ($macro_name, $action) = ($1, $2);
1319 my $lc_macro_name = lc($macro_name);
1320 my $preferred_name = $pve_fw_preferred_macro_names->{$lc_macro_name};
1321 $macro_name = $preferred_name if $preferred_name;
1322 $macro = $macros->{$lc_macro_name};
1323 die "unknown macro '$macro_name'\n" if !$macro;
1324 } else {
1325 die "unknown action '$action'\n";
1326 }
1327 } elsif ($type eq 'group') {
1328 die "wrong number of rule elements\n" if scalar(@data) != 3;
1329 die "groups disabled\n" if !$allow_groups;
1330
1331 die "invalid characters in group name\n" if $action !~ m/^[A-Za-z0-9_\-]+$/;
1332 } else {
1333 die "unknown rule type '$type'\n";
1334 }
1335
1336 if ($need_iface) {
1337 $iface = undef if $iface && $iface eq '-';
1338 }
1339
1340 $proto = undef if $proto && $proto eq '-';
1341 die "unknown protokol '$proto'\n" if $proto &&
1342 !(defined($protocols->{byname}->{$proto}) ||
1343 defined($protocols->{byid}->{$proto}));
1344
1345 $source = undef if $source && $source eq '-';
1346 $dest = undef if $dest && $dest eq '-';
1347
1348 $dport = undef if $dport && $dport eq '-';
1349 $sport = undef if $sport && $sport eq '-';
1350
1351 my $nbsource = undef;
1352 my $nbdest = undef;
1353
1354 $nbsource = parse_address_list($source) if $source;
1355 $nbdest = parse_address_list($dest) if $dest;
1356
1357 my $rules = [];
1358
1359 my $param = {
1360 type => $type,
1361 enable => $enable,
1362 comment => $comment,
1363 action => $action,
1364 iface => $iface,
1365 source => $source,
1366 dest => $dest,
1367 nbsource => $nbsource,
1368 nbdest => $nbdest,
1369 proto => $proto,
1370 dport => $dport,
1371 sport => $sport,
1372 };
1373
1374 if ($macro) {
1375 foreach my $templ (@$macro) {
1376 my $rule = {};
1377 my $param_used = {};
1378 foreach my $k (keys %$templ) {
1379 my $v = $templ->{$k};
1380 if ($v eq 'PARAM') {
1381 $v = $param->{$k};
1382 $param_used->{$k} = 1;
1383 } elsif ($v eq 'DEST') {
1384 $v = $param->{dest};
1385 $param_used->{dest} = 1;
1386 } elsif ($v eq 'SOURCE') {
1387 $v = $param->{source};
1388 $param_used->{source} = 1;
1389 }
1390
1391 die "missing parameter '$k' in macro '$macro_name'\n" if !defined($v);
1392 $rule->{$k} = $v;
1393 }
1394 foreach my $k (keys %$param) {
1395 next if !defined($param->{$k});
1396 next if $param_used->{$k};
1397 if (defined($rule->{$k})) {
1398 die "parameter '$k' already define in macro (value = '$rule->{$k}')\n"
1399 if $rule->{$k} ne $param->{$k};
1400 } else {
1401 $rule->{$k} = $param->{$k};
1402 }
1403 }
1404 push @$rules, $rule;
1405 }
1406 } else {
1407 push @$rules, $param;
1408 }
1409
1410 foreach my $rule (@$rules) {
1411 $rule->{nbdport} = parse_port_name_number_or_range($rule->{dport})
1412 if defined($rule->{dport});
1413 $rule->{nbsport} = parse_port_name_number_or_range($rule->{sport})
1414 if defined($rule->{sport});
1415 }
1416
1417 return $rules;
1418 }
1419
1420 sub parse_vmfw_option {
1421 my ($line) = @_;
1422
1423 my ($opt, $value);
1424
1425 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1426
1427 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
1428 $opt = lc($1);
1429 $value = int($2);
1430 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1431 $opt = lc($1);
1432 $value = $2 ? lc($3) : '';
1433 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1434 $opt = lc($1);
1435 $value = uc($3);
1436 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1437 $opt = lc($1);
1438 $value = $2;
1439 } else {
1440 chomp $line;
1441 die "can't parse option '$line'\n"
1442 }
1443
1444 return ($opt, $value);
1445 }
1446
1447 sub parse_hostfw_option {
1448 my ($line) = @_;
1449
1450 my ($opt, $value);
1451
1452 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1453
1454 if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1455 $opt = lc($1);
1456 $value = int($2);
1457 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1458 $opt = lc($1);
1459 $value = $2 ? lc($3) : '';
1460 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1461 $opt = lc($1);
1462 $value = uc($3);
1463 } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
1464 $opt = lc($1);
1465 $value = int($2);
1466 } else {
1467 chomp $line;
1468 die "can't parse option '$line'\n"
1469 }
1470
1471 return ($opt, $value);
1472 }
1473
1474 sub parse_vm_fw_rules {
1475 my ($filename, $fh) = @_;
1476
1477 my $res = { rules => [], options => {}};
1478
1479 my $section;
1480
1481 my $digest = Digest::SHA->new('sha1');
1482
1483 while (defined(my $line = <$fh>)) {
1484 $digest->add($line);
1485
1486 next if $line =~ m/^#/;
1487 next if $line =~ m/^\s*$/;
1488
1489 my $linenr = $fh->input_line_number();
1490 my $prefix = "$filename (line $linenr)";
1491
1492 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1493 $section = lc($1);
1494 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1495 next;
1496 }
1497 if (!$section) {
1498 warn "$prefix: skip line - no section";
1499 next;
1500 }
1501
1502 next if !$res->{$section}; # skip undefined section
1503
1504 if ($section eq 'options') {
1505 eval {
1506 my ($opt, $value) = parse_vmfw_option($line);
1507 $res->{options}->{$opt} = $value;
1508 };
1509 warn "$prefix: $@" if $@;
1510 next;
1511 }
1512
1513 my $rules;
1514 eval { $rules = parse_fw_rule($line, 1, 1); };
1515 if (my $err = $@) {
1516 warn "$prefix: $err";
1517 next;
1518 }
1519
1520 push @{$res->{$section}}, @$rules;
1521 }
1522
1523 $res->{digest} = $digest->b64digest;
1524
1525 return $res;
1526 }
1527
1528 sub parse_host_fw_rules {
1529 my ($filename, $fh) = @_;
1530
1531 my $res = { rules => [], options => {}};
1532
1533 my $section;
1534
1535 my $digest = Digest::SHA->new('sha1');
1536
1537 while (defined(my $line = <$fh>)) {
1538 $digest->add($line);
1539
1540 next if $line =~ m/^#/;
1541 next if $line =~ m/^\s*$/;
1542
1543 my $linenr = $fh->input_line_number();
1544 my $prefix = "$filename (line $linenr)";
1545
1546 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1547 $section = lc($1);
1548 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1549 next;
1550 }
1551 if (!$section) {
1552 warn "$prefix: skip line - no section";
1553 next;
1554 }
1555
1556 next if !$res->{$section}; # skip undefined section
1557
1558 if ($section eq 'options') {
1559 eval {
1560 my ($opt, $value) = parse_hostfw_option($line);
1561 $res->{options}->{$opt} = $value;
1562 };
1563 warn "$prefix: $@" if $@;
1564 next;
1565 }
1566
1567 my $rules;
1568 eval { $rules = parse_fw_rule($line, 1, 1); };
1569 if (my $err = $@) {
1570 warn "$prefix: $err";
1571 next;
1572 }
1573
1574 push @{$res->{$section}}, @$rules;
1575 }
1576
1577 $res->{digest} = $digest->b64digest;
1578
1579 return $res;
1580 }
1581
1582 sub parse_group_fw_rules {
1583 my ($filename, $fh) = @_;
1584
1585 my $section;
1586 my $group;
1587
1588 my $res = { rules => {} };
1589
1590 my $digest = Digest::SHA->new('sha1');
1591
1592 while (defined(my $line = <$fh>)) {
1593 $digest->add($line);
1594
1595 next if $line =~ m/^#/;
1596 next if $line =~ m/^\s*$/;
1597
1598 my $linenr = $fh->input_line_number();
1599 my $prefix = "$filename (line $linenr)";
1600
1601 if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
1602 $section = 'rules';
1603 $group = lc($1);
1604 next;
1605 }
1606 if (!$section || !$group) {
1607 warn "$prefix: skip line - no section";
1608 next;
1609 }
1610
1611 my $rules;
1612 eval { $rules = parse_fw_rule($line, 0, 0); };
1613 if (my $err = $@) {
1614 warn "$prefix: $err";
1615 next;
1616 }
1617
1618 push @{$res->{$section}->{$group}}, @$rules;
1619 }
1620
1621 $res->{digest} = $digest->b64digest;
1622
1623 return $res;
1624 }
1625
1626 sub run_locked {
1627 my ($code, @param) = @_;
1628
1629 my $timeout = 10;
1630
1631 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
1632
1633 die $@ if $@;
1634
1635 return $res;
1636 }
1637
1638 sub read_local_vm_config {
1639
1640 my $openvz = {};
1641 my $qemu = {};
1642
1643 my $vmdata = { openvz => $openvz, qemu => $qemu };
1644
1645 my $vmlist = PVE::Cluster::get_vmlist();
1646 return $vmdata if !$vmlist || !$vmlist->{ids};
1647 my $ids = $vmlist->{ids};
1648
1649 foreach my $vmid (keys %$ids) {
1650 next if !$vmid; # skip VE0
1651 my $d = $ids->{$vmid};
1652 next if !$d->{node} || $d->{node} ne $nodename;
1653 next if !$d->{type};
1654 if ($d->{type} eq 'openvz') {
1655 if ($have_pve_manager) {
1656 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
1657 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
1658 $openvz->{$vmid} = $conf;
1659 }
1660 }
1661 } elsif ($d->{type} eq 'qemu') {
1662 if ($have_qemu_server) {
1663 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
1664 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
1665 $qemu->{$vmid} = $conf;
1666 }
1667 }
1668 }
1669 }
1670
1671 return $vmdata;
1672 };
1673
1674 sub load_vmfw_conf {
1675 my ($vmid) = @_;
1676
1677 my $vmfw_conf = {};
1678
1679 my $filename = "/etc/pve/firewall/$vmid.fw";
1680 if (my $fh = IO::File->new($filename, O_RDONLY)) {
1681 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
1682 }
1683
1684 return $vmfw_conf;
1685 }
1686
1687 sub read_vm_firewall_configs {
1688 my ($vmdata) = @_;
1689 my $vmfw_configs = {};
1690
1691 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
1692 my $vmfw_conf = load_vmfw_conf($vmid);
1693 next if !$vmfw_conf->{options}; # skip if file does not exists
1694 $vmfw_configs->{$vmid} = $vmfw_conf;
1695 }
1696
1697 return $vmfw_configs;
1698 }
1699
1700 sub get_option_log_level {
1701 my ($options, $k) = @_;
1702
1703 my $v = $options->{$k};
1704 $v = $default_log_level if !defined($v);
1705
1706 return undef if $v eq '' || $v eq 'nolog';
1707
1708 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
1709
1710 return $v if ($v >= 0) && ($v <= 7);
1711
1712 warn "unknown log level ($k = '$v')\n";
1713
1714 return undef;
1715 }
1716
1717 sub generate_std_chains {
1718 my ($ruleset, $options) = @_;
1719
1720 my $loglevel = get_option_log_level($options, 'smurf_log_level');
1721
1722 # same as shorewall smurflog.
1723 my $chain = 'PVEFW-smurflog';
1724
1725 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
1726 push @{$pve_std_chains->{$chain}}, "-j DROP";
1727
1728 # same as shorewall logflags action.
1729 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
1730 $chain = 'PVEFW-logflags';
1731 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
1732 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
1733 push @{$pve_std_chains->{$chain}}, "-j DROP";
1734
1735 foreach my $chain (keys %$pve_std_chains) {
1736 ruleset_create_chain($ruleset, $chain);
1737 foreach my $rule (@{$pve_std_chains->{$chain}}) {
1738 if (ref($rule)) {
1739 ruleset_generate_rule($ruleset, $chain, $rule);
1740 } else {
1741 ruleset_addrule($ruleset, $chain, $rule);
1742 }
1743 }
1744 }
1745 }
1746
1747 sub save_pvefw_status {
1748 my ($status) = @_;
1749
1750 die "unknown status '$status' - internal error"
1751 if $status !~ m/^(stopped|active)$/;
1752
1753 mkdir dirname($pve_fw_status_filename);
1754 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
1755 }
1756
1757 sub read_pvefw_status {
1758
1759 my $status = 'unknown';
1760
1761 return 'stopped' if ! -f $pve_fw_status_filename;
1762
1763 eval {
1764 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
1765 };
1766 warn $@ if $@;
1767
1768 return $status;
1769 }
1770
1771 # fixme: move to pve-common PVE::ProcFSTools
1772 sub read_proc_net_route {
1773 my $filename = "/proc/net/route";
1774
1775 my $res = {};
1776
1777 my $fh = IO::File->new ($filename, "r");
1778 return $res if !$fh;
1779
1780 my $int_to_quad = sub {
1781 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
1782 };
1783
1784 while (defined(my $line = <$fh>)) {
1785 next if $line =~/^Iface\s+Destination/; # skip head
1786 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
1787 push @{$res->{$iface}}, {
1788 dest => &$int_to_quad(hex($dest)),
1789 gateway => &$int_to_quad(hex($gateway)),
1790 mask => &$int_to_quad(hex($mask)),
1791 metric => $metric,
1792 mtu => $mtu,
1793 };
1794 }
1795
1796 return $res;
1797 }
1798
1799 sub load_security_groups {
1800
1801 my $groups_conf = {};
1802 my $filename = "/etc/pve/firewall/groups.fw";
1803 if (my $fh = IO::File->new($filename, O_RDONLY)) {
1804 $groups_conf = parse_group_fw_rules($filename, $fh);
1805 }
1806
1807 return $groups_conf;
1808 }
1809
1810 sub load_hostfw_conf {
1811
1812 my $hostfw_conf = {};
1813 my $filename = "/etc/pve/local/host.fw";
1814 if (my $fh = IO::File->new($filename, O_RDONLY)) {
1815 $hostfw_conf = parse_host_fw_rules($filename, $fh);
1816 }
1817 return $hostfw_conf;
1818 }
1819
1820 sub compile {
1821 my $vmdata = read_local_vm_config();
1822 my $vmfw_configs = read_vm_firewall_configs($vmdata);
1823
1824 my $routing_table = read_proc_net_route();
1825
1826 my $groups_conf = load_security_groups();
1827
1828 my $ruleset = {};
1829
1830 ruleset_create_chain($ruleset, "PVEFW-INPUT");
1831 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
1832
1833 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
1834
1835 my $hostfw_conf = load_hostfw_conf();
1836 my $hostfw_options = $hostfw_conf->{options} || {};
1837
1838 generate_std_chains($ruleset, $hostfw_options);
1839
1840 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
1841
1842 enable_host_firewall($ruleset, $hostfw_conf, $groups_conf) if $hostfw_enable;
1843
1844 my $ips_enable = undef;
1845
1846 # generate firewall rules for QEMU VMs
1847 foreach my $vmid (keys %{$vmdata->{qemu}}) {
1848 my $conf = $vmdata->{qemu}->{$vmid};
1849 my $vmfw_conf = $vmfw_configs->{$vmid};
1850 next if !$vmfw_conf;
1851 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
1852
1853 $ips_enable = 1 if $vmfw_conf->{options}->{ips};
1854
1855 foreach my $netid (keys %$conf) {
1856 next if $netid !~ m/^net(\d+)$/;
1857 my $net = PVE::QemuServer::parse_net($conf->{$netid});
1858 next if !$net;
1859 my $iface = "tap${vmid}i$1";
1860
1861 my $bridge = $net->{bridge};
1862 next if !$bridge; # fixme: ?
1863
1864 $bridge .= "v$net->{tag}" if $net->{tag};
1865
1866 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
1867
1868 my $macaddr = $net->{macaddr};
1869 generate_tap_rules_direction($ruleset, $groups_conf, $iface, $netid, $macaddr,
1870 $vmfw_conf, $vmid, $bridge, 'IN');
1871 generate_tap_rules_direction($ruleset, $groups_conf, $iface, $netid, $macaddr,
1872 $vmfw_conf, $vmid, $bridge, 'OUT');
1873 }
1874 }
1875
1876 # generate firewall rules for OpenVZ containers
1877 foreach my $vmid (keys %{$vmdata->{openvz}}) {
1878 my $conf = $vmdata->{openvz}->{$vmid};
1879
1880 my $vmfw_conf = $vmfw_configs->{$vmid};
1881 next if !$vmfw_conf;
1882 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
1883
1884 $ips_enable = 1 if $vmfw_conf->{options}->{ips};
1885
1886 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
1887 my $ip = $conf->{ip_address}->{value};
1888 generate_venet_rules_direction($ruleset, $groups_conf, $vmfw_conf, $vmid, $ip, 'IN');
1889 generate_venet_rules_direction($ruleset, $groups_conf, $vmfw_conf, $vmid, $ip, 'OUT');
1890 }
1891
1892 if ($conf->{netif} && $conf->{netif}->{value}) {
1893 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
1894 foreach my $netid (keys %$netif) {
1895 my $d = $netif->{$netid};
1896 my $bridge = $d->{bridge};
1897 if (!$bridge) {
1898 warn "no bridge device for CT $vmid iface '$netid'\n";
1899 next; # fixme?
1900 }
1901
1902 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
1903
1904 my $macaddr = $d->{mac};
1905 my $iface = $d->{host_ifname};
1906 generate_tap_rules_direction($ruleset, $groups_conf, $iface, $netid, $macaddr,
1907 $vmfw_conf, $vmid, $bridge, 'IN');
1908 generate_tap_rules_direction($ruleset, $groups_conf, $iface, $netid, $macaddr,
1909 $vmfw_conf, $vmid, $bridge, 'OUT');
1910 }
1911 }
1912 }
1913
1914 if($hostfw_options->{optimize}){
1915
1916 my $accept = $ips_enable ? "PVEFW-IPS" : "ACCEPT";
1917 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1918 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
1919 }
1920
1921 # fixme: what log level should we use here?
1922 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
1923
1924 # fixme: should we really block inter-bridge traffic?
1925
1926 # always allow traffic from containers?
1927 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
1928
1929 # disable interbridge routing
1930 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
1931 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
1932 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
1933 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
1934 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
1935 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
1936
1937 return wantarray ? ($ruleset, $hostfw_conf) : $ruleset;
1938 }
1939
1940 sub get_ruleset_status {
1941 my ($ruleset, $verbose) = @_;
1942
1943 my $active_chains = iptables_get_chains();
1944
1945 my $statushash = {};
1946
1947 foreach my $chain (sort keys %$ruleset) {
1948 my $digest = Digest::SHA->new('sha1');
1949 foreach my $cmd (@{$ruleset->{$chain}}) {
1950 $digest->add("$cmd\n");
1951 }
1952 my $sig = $digest->b64digest;
1953 $statushash->{$chain}->{sig} = $sig;
1954
1955 my $oldsig = $active_chains->{$chain};
1956 if (!defined($oldsig)) {
1957 $statushash->{$chain}->{action} = 'create';
1958 } else {
1959 if ($oldsig eq $sig) {
1960 $statushash->{$chain}->{action} = 'exists';
1961 } else {
1962 $statushash->{$chain}->{action} = 'update';
1963 }
1964 }
1965 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
1966 foreach my $cmd (@{$ruleset->{$chain}}) {
1967 print "\t$cmd\n" if $verbose;
1968 }
1969 }
1970
1971 foreach my $chain (sort keys %$active_chains) {
1972 if (!defined($ruleset->{$chain})) {
1973 my $sig = $active_chains->{$chain};
1974 $statushash->{$chain}->{action} = 'delete';
1975 $statushash->{$chain}->{sig} = $sig;
1976 print "delete $chain ($sig)\n" if $verbose;
1977 }
1978 }
1979
1980 return $statushash;
1981 }
1982
1983 sub print_ruleset {
1984 my ($ruleset) = @_;
1985
1986 get_ruleset_status($ruleset, 1);
1987 }
1988
1989 sub print_sig_rule {
1990 my ($chain, $sig) = @_;
1991
1992 # We just use this to store a SHA1 checksum used to detect changes
1993 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
1994 }
1995
1996 sub get_rulset_cmdlist {
1997 my ($ruleset, $verbose) = @_;
1998
1999 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2000
2001 my $statushash = get_ruleset_status($ruleset, $verbose);
2002
2003 # create missing chains first
2004 foreach my $chain (sort keys %$ruleset) {
2005 my $stat = $statushash->{$chain};
2006 die "internal error" if !$stat;
2007 next if $stat->{action} ne 'create';
2008
2009 $cmdlist .= ":$chain - [0:0]\n";
2010 }
2011
2012 my $rule = "INPUT -j PVEFW-INPUT";
2013 if (!PVE::Firewall::iptables_rule_exist($rule)) {
2014 $cmdlist .= "-A $rule\n";
2015 }
2016 $rule = "OUTPUT -j PVEFW-OUTPUT";
2017 if (!PVE::Firewall::iptables_rule_exist($rule)) {
2018 $cmdlist .= "-A $rule\n";
2019 }
2020
2021 $rule = "FORWARD -j PVEFW-FORWARD";
2022 if (!PVE::Firewall::iptables_rule_exist($rule)) {
2023 $cmdlist .= "-A $rule\n";
2024 }
2025
2026 foreach my $chain (sort keys %$ruleset) {
2027 my $stat = $statushash->{$chain};
2028 die "internal error" if !$stat;
2029
2030 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
2031 $cmdlist .= "-F $chain\n";
2032 foreach my $cmd (@{$ruleset->{$chain}}) {
2033 $cmdlist .= "$cmd\n";
2034 }
2035 $cmdlist .= print_sig_rule($chain, $stat->{sig});
2036 } elsif ($stat->{action} eq 'delete') {
2037 die "internal error"; # this should not happen
2038 } elsif ($stat->{action} eq 'exists') {
2039 # do nothing
2040 } else {
2041 die "internal error - unknown status '$stat->{action}'";
2042 }
2043 }
2044
2045 foreach my $chain (keys %$statushash) {
2046 next if $statushash->{$chain}->{action} ne 'delete';
2047 $cmdlist .= "-F $chain\n";
2048 }
2049 foreach my $chain (keys %$statushash) {
2050 next if $statushash->{$chain}->{action} ne 'delete';
2051 next if $chain eq 'PVEFW-INPUT';
2052 next if $chain eq 'PVEFW-OUTPUT';
2053 next if $chain eq 'PVEFW-FORWARD';
2054 $cmdlist .= "-X $chain\n";
2055 }
2056
2057 $cmdlist .= "COMMIT\n";
2058
2059 return $cmdlist;
2060 }
2061
2062 sub apply_ruleset {
2063 my ($ruleset, $hostfw_conf, $verbose) = @_;
2064
2065 enable_bridge_firewall();
2066
2067 update_nf_conntrack_max($hostfw_conf);
2068
2069 my $cmdlist = get_rulset_cmdlist($ruleset, $verbose);
2070
2071 print $cmdlist if $verbose;
2072
2073 iptables_restore_cmdlist($cmdlist);
2074
2075 # test: re-read status and check if everything is up to date
2076 my $statushash = get_ruleset_status($ruleset);
2077
2078 my $errors;
2079 foreach my $chain (sort keys %$ruleset) {
2080 my $stat = $statushash->{$chain};
2081 if ($stat->{action} ne 'exists') {
2082 warn "unable to update chain '$chain'\n";
2083 $errors = 1;
2084 }
2085 }
2086
2087 die "unable to apply firewall changes\n" if $errors;
2088 }
2089
2090 sub update_nf_conntrack_max {
2091 my ($hostfw_conf) = @_;
2092
2093 my $max = 65536; # reasonable default
2094
2095 my $options = $hostfw_conf->{options} || {};
2096
2097 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
2098 $max = $options->{nf_conntrack_max};
2099 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2100 }
2101
2102 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2103 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2104
2105 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
2106
2107 if ($current != $max) {
2108 my $hashsize = int($max/4);
2109 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
2110 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
2111 }
2112 }
2113
2114 sub update {
2115 my ($start, $verbose) = @_;
2116
2117 my $code = sub {
2118 my $status = read_pvefw_status();
2119
2120 my ($ruleset, $hostfw_conf) = PVE::Firewall::compile();
2121
2122 if ($start || $status eq 'active') {
2123
2124 save_pvefw_status('active') if ($status ne 'active');
2125
2126 apply_ruleset($ruleset, $hostfw_conf, $verbose);
2127 } else {
2128 print "Firewall not active (status = $status)\n" if $verbose;
2129 }
2130 };
2131
2132 run_locked($code);
2133 }
2134
2135
2136 1;