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