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