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