]> git.proxmox.com Git - pve-firewall.git/blob - src/PVE/Firewall.pm
e060244e9d26439f3cffc5df0c270bec8c42ebfe
[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 my $nbaor = 0;
617 foreach my $aor (split(/,/, $str)) {
618 if($nbaor > 0 && $aor =~ m/-/){
619 die "you can use a range in a list";
620 }
621 if (!Net::IP->new($aor)) {
622 my $err = Net::IP::Error();
623 die "invalid IP address: $err\n";
624 }else{
625 $nbaor++;
626 }
627 }
628 }
629
630 sub parse_port_name_number_or_range {
631 my ($str) = @_;
632
633 my $services = PVE::Firewall::get_etc_services();
634 my $nbports = 0;
635 foreach my $item (split(/,/, $str)) {
636 my $portlist = "";
637 my $oldpon = undef;
638 $nbports++;
639 foreach my $pon (split(':', $item, 2)) {
640 $pon = $services->{byname}->{$pon}->{port} if $services->{byname}->{$pon}->{port};
641 if ($pon =~ m/^\d+$/){
642 die "invalid port '$pon'\n" if $pon < 0 && $pon > 65535;
643 die "port '$pon' must be bigger than port '$oldpon' \n" if $oldpon && ($pon < $oldpon);
644 $oldpon = $pon;
645 }else{
646 die "invalid port $services->{byname}->{$pon}\n" if !$services->{byname}->{$pon};
647 }
648 }
649 }
650
651 return ($nbports);
652 }
653
654 PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
655 sub pve_fw_verify_port_spec {
656 my ($portstr) = @_;
657
658 parse_port_name_number_or_range($portstr);
659
660 return $portstr;
661 }
662
663 PVE::JSONSchema::register_format('pve-fw-v4addr-spec', \&pve_fw_verify_v4addr_spec);
664 sub pve_fw_verify_v4addr_spec {
665 my ($list) = @_;
666
667 parse_address_list($list);
668
669 return $list;
670 }
671
672 PVE::JSONSchema::register_format('pve-fw-protocol-spec', \&pve_fw_verify_protocol_spec);
673 sub pve_fw_verify_protocol_spec {
674 my ($proto) = @_;
675
676 my $protocols = get_etc_protocols();
677
678 die "unknown protocol '$proto'\n" if $proto &&
679 !(defined($protocols->{byname}->{$proto}) ||
680 defined($protocols->{byid}->{$proto}));
681
682 return $proto;
683 }
684
685
686 # helper function for API
687
688 my $rule_properties = {
689 pos => {
690 description => "Update rule at position <pos>.",
691 type => 'integer',
692 minimum => 0,
693 optional => 1,
694 },
695 digest => {
696 type => 'string',
697 optional => 1,
698 maxLength => 27,
699 minLength => 27,
700 },
701 type => {
702 type => 'string',
703 optional => 1,
704 enum => ['in', 'out', 'group'],
705 },
706 action => {
707 type => 'string',
708 optional => 1,
709 enum => ['ACCEPT', 'DROP', 'REJECT'],
710 },
711 macro => {
712 type => 'string',
713 optional => 1,
714 maxLength => 128,
715 },
716 iface => get_standard_option('pve-iface', { optional => 1 }),
717 source => {
718 type => 'string', format => 'pve-fw-v4addr-spec',
719 optional => 1,
720 },
721 dest => {
722 type => 'string', format => 'pve-fw-v4addr-spec',
723 optional => 1,
724 },
725 proto => {
726 type => 'string', format => 'pve-fw-protocol-spec',
727 optional => 1,
728 },
729 enable => {
730 type => 'boolean',
731 optional => 1,
732 },
733 sport => {
734 type => 'string', format => 'pve-fw-port-spec',
735 optional => 1,
736 },
737 dport => {
738 type => 'string', format => 'pve-fw-port-spec',
739 optional => 1,
740 },
741 comment => {
742 type => 'string',
743 optional => 1,
744 },
745 };
746
747 sub cleanup_fw_rule {
748 my ($rule, $digest, $pos) = @_;
749
750 my $r = {};
751
752 foreach my $k (keys %$rule) {
753 next if !$rule_properties->{$k};
754 my $v = $rule->{$k};
755 next if !defined($v);
756 $r->{$k} = $v;
757 $r->{digest} = $digest;
758 $r->{pos} = $pos;
759 }
760
761 return $r;
762 }
763
764 sub add_rule_properties {
765 my ($properties) = @_;
766
767 foreach my $k (keys %$rule_properties) {
768 $properties->{$k} = $rule_properties->{$k};
769 }
770
771 return $properties;
772 }
773
774 sub copy_rule_data {
775 my ($rule, $param) = @_;
776
777 foreach my $k (keys %$rule_properties) {
778 if (defined(my $v = $param->{$k})) {
779 if ($v eq '' || $v eq '-') {
780 delete $rule->{$k};
781 } else {
782 $rule->{$k} = $v;
783 }
784 } else {
785 delete $rule->{$k};
786 }
787 }
788 return $rule;
789 }
790
791 # core functions
792 my $bridge_firewall_enabled = 0;
793
794 sub enable_bridge_firewall {
795
796 return if $bridge_firewall_enabled; # only once
797
798 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
799 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
800
801 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
802 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
803
804 $bridge_firewall_enabled = 1;
805 }
806
807 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
808
809 sub iptables_restore_cmdlist {
810 my ($cmdlist) = @_;
811
812 run_command("/sbin/iptables-restore -n", input => $cmdlist);
813 }
814
815 sub ipset_restore_cmdlist {
816 my ($cmdlist) = @_;
817
818 run_command("/usr/sbin/ipset restore", input => $cmdlist);
819 }
820
821 sub iptables_get_chains {
822
823 my $res = {};
824
825 # check what chains we want to track
826 my $is_pvefw_chain = sub {
827 my $name = shift;
828
829 return 1 if $name =~ m/^PVEFW-\S+$/;
830
831 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
832
833 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
834
835 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
836
837 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
838 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
839
840 return undef;
841 };
842
843 my $table = '';
844
845 my $hooks = {};
846
847 my $parser = sub {
848 my $line = shift;
849
850 return if $line =~ m/^#/;
851 return if $line =~ m/^\s*$/;
852
853 if ($line =~ m/^\*(\S+)$/) {
854 $table = $1;
855 return;
856 }
857
858 return if $table ne 'filter';
859
860 if ($line =~ m/^:(\S+)\s/) {
861 my $chain = $1;
862 return if !&$is_pvefw_chain($chain);
863 $res->{$chain} = "unknown";
864 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
865 my ($chain, $sig) = ($1, $2);
866 return if !&$is_pvefw_chain($chain);
867 $res->{$chain} = $sig;
868 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
869 $hooks->{$1} = 1;
870 } else {
871 # simply ignore the rest
872 return;
873 }
874 };
875
876 run_command("/sbin/iptables-save", outfunc => $parser);
877
878 return wantarray ? ($res, $hooks) : $res;
879 }
880
881 sub iptables_chain_digest {
882 my ($rules) = @_;
883 my $digest = Digest::SHA->new('sha1');
884 foreach my $rule (@$rules) { # order is important
885 $digest->add($rule);
886 }
887 return $digest->b64digest;
888 }
889
890 sub ipset_chain_digest {
891 my ($rules) = @_;
892
893 my $digest = Digest::SHA->new('sha1');
894 foreach my $rule (sort @$rules) { # note: sorted
895 $digest->add($rule);
896 }
897 return $digest->b64digest;
898 }
899
900 sub ipset_get_chains {
901
902 my $res = {};
903 my $chains = {};
904
905 my $parser = sub {
906 my $line = shift;
907
908 return if $line =~ m/^#/;
909 return if $line =~ m/^\s*$/;
910 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
911 my $chain = $1;
912 $line =~ s/\s+$//; # delete trailing white space
913 push @{$chains->{$chain}}, $line;
914 } else {
915 # simply ignore the rest
916 return;
917 }
918 };
919
920 run_command("/usr/sbin/ipset save", outfunc => $parser);
921
922 # compute digest for each chain
923 foreach my $chain (keys %$chains) {
924 $res->{$chain} = ipset_chain_digest($chains->{$chain});
925 }
926
927 return $res;
928 }
929
930 sub ruleset_generate_cmdstr {
931 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
932
933 return if defined($rule->{enable}) && !$rule->{enable};
934
935 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
936
937 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
938 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
939
940 my @cmd = ();
941
942 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
943 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
944
945 my $source = $rule->{source};
946 my $dest = $rule->{dest};
947
948 if ($source) {
949 if ($source =~ m/^(\+)(\S+)$/) {
950 die "no such ipset $2" if !$cluster_conf->{ipset}->{$2};
951 push @cmd, "-m set --match-set PVEFW-$2 src";
952
953 } elsif ($source =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
954 push @cmd, "-m iprange --src-range $source";
955
956 } else {
957 push @cmd, "-s $source";
958 }
959 }
960
961 if ($dest) {
962 if ($dest =~ m/^(\+)(\S+)$/) {
963 die "no such ipset $2" if !$cluster_conf->{ipset}->{$2};
964 push @cmd, "-m set --match-set PVEFW-$2 dst";
965
966 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
967 push @cmd, "-m iprange --dst-range $dest";
968
969 } else {
970 push @cmd, "-s $dest";
971 }
972 }
973
974 if ($rule->{proto}) {
975 push @cmd, "-p $rule->{proto}";
976
977 my $multiport = 0;
978 $multiport++ if $nbdport > 1;
979 $multiport++ if $nbsport > 1;
980
981 push @cmd, "--match multiport" if $multiport;
982
983 die "multiport: option '--sports' cannot be used together with '--dports'\n"
984 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
985
986 if ($rule->{dport}) {
987 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
988 # Note: we use dport to store --icmp-type
989 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
990 push @cmd, "-m icmp --icmp-type $rule->{dport}";
991 } else {
992 if ($nbdport > 1) {
993 if ($multiport == 2) {
994 push @cmd, "--ports $rule->{dport}";
995 } else {
996 push @cmd, "--dports $rule->{dport}";
997 }
998 } else {
999 push @cmd, "--dport $rule->{dport}";
1000 }
1001 }
1002 }
1003
1004 if ($rule->{sport}) {
1005 if ($nbsport > 1) {
1006 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1007 } else {
1008 push @cmd, "--sport $rule->{sport}";
1009 }
1010 }
1011 } elsif ($rule->{dport} || $rule->{sport}) {
1012 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport};
1013 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport};
1014 }
1015
1016 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
1017
1018 if (my $action = $rule->{action}) {
1019 $action = $actions->{$action} if defined($actions->{$action});
1020 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1021 push @cmd, $goto ? "-g $action" : "-j $action";
1022 }
1023
1024 return scalar(@cmd) ? join(' ', @cmd) : undef;
1025 }
1026
1027 my $apply_macro = sub {
1028 my ($macro_name, $param) = @_;
1029
1030 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1031 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1032
1033 my $rules = [];
1034
1035 foreach my $templ (@$macro_rules) {
1036 my $rule = {};
1037 my $param_used = {};
1038 foreach my $k (keys %$templ) {
1039 my $v = $templ->{$k};
1040 if ($v eq 'PARAM') {
1041 $v = $param->{$k};
1042 $param_used->{$k} = 1;
1043 } elsif ($v eq 'DEST') {
1044 $v = $param->{dest};
1045 $param_used->{dest} = 1;
1046 } elsif ($v eq 'SOURCE') {
1047 $v = $param->{source};
1048 $param_used->{source} = 1;
1049 }
1050
1051 die "missing parameter '$k' in macro '$macro_name'\n" if !defined($v);
1052 $rule->{$k} = $v;
1053 }
1054 foreach my $k (keys %$param) {
1055 next if $k eq 'macro';
1056 next if !defined($param->{$k});
1057 next if $param_used->{$k};
1058 if (defined($rule->{$k})) {
1059 die "parameter '$k' already define in macro (value = '$rule->{$k}')\n"
1060 if $rule->{$k} ne $param->{$k};
1061 } else {
1062 $rule->{$k} = $param->{$k};
1063 }
1064 }
1065 push @$rules, $rule;
1066 }
1067
1068 return $rules;
1069 };
1070
1071 sub ruleset_generate_rule {
1072 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1073
1074 my $rules;
1075
1076 if ($rule->{macro}) {
1077 $rules = &$apply_macro($rule->{macro}, $rule);
1078 } else {
1079 $rules = [ $rule ];
1080 }
1081
1082 foreach my $tmp (@$rules) {
1083 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1084 ruleset_addrule($ruleset, $chain, $cmdstr);
1085 }
1086 }
1087 }
1088
1089 sub ruleset_generate_rule_insert {
1090 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1091
1092 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1093
1094 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
1095 ruleset_insertrule($ruleset, $chain, $cmdstr);
1096 }
1097 }
1098
1099 sub ruleset_create_chain {
1100 my ($ruleset, $chain) = @_;
1101
1102 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1103 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1104
1105 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1106
1107 $ruleset->{$chain} = [];
1108 }
1109
1110 sub ruleset_chain_exist {
1111 my ($ruleset, $chain) = @_;
1112
1113 return $ruleset->{$chain} ? 1 : undef;
1114 }
1115
1116 sub ruleset_addrule {
1117 my ($ruleset, $chain, $rule) = @_;
1118
1119 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1120
1121 push @{$ruleset->{$chain}}, "-A $chain $rule";
1122 }
1123
1124 sub ruleset_insertrule {
1125 my ($ruleset, $chain, $rule) = @_;
1126
1127 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1128
1129 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1130 }
1131
1132 sub get_log_rule_base {
1133 my ($chain, $vmid, $msg, $loglevel) = @_;
1134
1135 die "internal error - no log level" if !defined($loglevel);
1136
1137 $vmid = 0 if !defined($vmid);
1138
1139 # Note: we use special format for prefix to pass further
1140 # info to log daemon (VMID, LOGVELEL and CHAIN)
1141
1142 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1143 }
1144
1145 sub ruleset_addlog {
1146 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1147
1148 return if !defined($loglevel);
1149
1150 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1151
1152 $logrule = "$rule $logrule" if defined($rule);
1153
1154 ruleset_addrule($ruleset, $chain, $logrule)
1155 }
1156
1157 sub generate_bridge_chains {
1158 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
1159
1160 my $options = $hostfw_conf->{options} || {};
1161
1162 die "error: detected direct route to bridge '$bridge'\n"
1163 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
1164
1165 if (!ruleset_chain_exist($ruleset, "$bridge-FW")) {
1166 ruleset_create_chain($ruleset, "$bridge-FW");
1167 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o $bridge -m physdev --physdev-is-out -j $bridge-FW");
1168 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i $bridge -m physdev --physdev-is-in -j $bridge-FW");
1169 }
1170
1171 if (!ruleset_chain_exist($ruleset, "$bridge-OUT")) {
1172 ruleset_create_chain($ruleset, "$bridge-OUT");
1173 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-in -j $bridge-OUT");
1174 ruleset_insertrule($ruleset, "PVEFW-INPUT", "-i $bridge -m physdev --physdev-is-in -j $bridge-OUT");
1175 }
1176
1177 if (!ruleset_chain_exist($ruleset, "$bridge-IN")) {
1178 ruleset_create_chain($ruleset, "$bridge-IN");
1179 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j $bridge-IN");
1180 ruleset_addrule($ruleset, "$bridge-FW", "-m mark --mark 1 -j ACCEPT");
1181 # accept traffic to unmanaged bridge ports
1182 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j ACCEPT ");
1183 }
1184 }
1185
1186 sub ruleset_add_chain_policy {
1187 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1188
1189 if ($policy eq 'ACCEPT') {
1190
1191 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1192 { ACCEPT => $accept_action});
1193
1194 } elsif ($policy eq 'DROP') {
1195
1196 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1197
1198 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1199
1200 ruleset_addrule($ruleset, $chain, "-j DROP");
1201 } elsif ($policy eq 'REJECT') {
1202 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1203
1204 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1205
1206 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1207 } else {
1208 # should not happen
1209 die "internal error: unknown policy '$policy'";
1210 }
1211 }
1212
1213 sub ruleset_create_vm_chain {
1214 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1215
1216 ruleset_create_chain($ruleset, $chain);
1217 my $accept = generate_nfqueue($options);
1218
1219 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1220 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1221 }
1222
1223 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1224 if ($direction eq 'OUT') {
1225 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1226 proto => 'udp', sport => 68, dport => 67 });
1227 } else {
1228 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1229 proto => 'udp', sport => 67, dport => 68 });
1230 }
1231 }
1232
1233 if ($options->{tcpflags}) {
1234 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1235 }
1236
1237 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1238 if ($direction eq 'OUT') {
1239 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -g PVEFW-SET-ACCEPT-MARK");
1240 } else {
1241 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1242 }
1243
1244 if ($direction eq 'OUT') {
1245 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1246 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
1247 }
1248 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1249 }
1250 }
1251
1252 sub ruleset_generate_vm_rules {
1253 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1254
1255 my $lc_direction = lc($direction);
1256
1257 foreach my $rule (@$rules) {
1258 next if $rule->{iface} && $rule->{iface} ne $netid;
1259 next if !$rule->{enable};
1260 if ($rule->{type} eq 'group') {
1261 my $group_chain = "GROUP-$rule->{action}-$direction";
1262 if(!ruleset_chain_exist($ruleset, $group_chain)){
1263 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
1264 }
1265 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1266 if ($direction eq 'OUT'){
1267 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j RETURN");
1268 }else{
1269 my $accept = generate_nfqueue($options);
1270 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $accept");
1271 }
1272
1273 } else {
1274 next if $rule->{type} ne $lc_direction;
1275 if ($direction eq 'OUT') {
1276 ruleset_generate_rule($ruleset, $chain, $rule,
1277 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1278 } else {
1279 my $accept = generate_nfqueue($options);
1280 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1281 }
1282 }
1283 }
1284 }
1285
1286 sub generate_nfqueue {
1287 my ($options) = @_;
1288
1289 my $action = "";
1290 if($options->{ips}){
1291 $action = "NFQUEUE";
1292 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1293 if(defined($3) && defined($1)) {
1294 $action .= " --queue-balance $1:$3";
1295 }elsif (defined($1)) {
1296 $action .= " --queue-num $1";
1297 }
1298 }
1299 $action .= " --queue-bypass";
1300 }else{
1301 $action = "ACCEPT";
1302 }
1303
1304 return $action;
1305 }
1306
1307 sub ruleset_generate_vm_ipsrules {
1308 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1309
1310 if ($options->{ips} && $direction eq 'IN') {
1311 my $nfqueue = generate_nfqueue($options);
1312
1313 if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
1314 ruleset_create_chain($ruleset, "PVEFW-IPS");
1315 }
1316
1317 if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
1318 ruleset_create_chain($ruleset, "$bridge-IPS");
1319 ruleset_insertrule($ruleset, "PVEFW-IPS", "-o $bridge -m physdev --physdev-is-out -j $bridge-IPS");
1320 }
1321
1322 ruleset_addrule($ruleset, "$bridge-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
1323 }
1324 }
1325
1326 sub generate_venet_rules_direction {
1327 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1328
1329 parse_address_list($ip); # make sure we have a valid $ip list
1330
1331 my $lc_direction = lc($direction);
1332
1333 my $rules = $vmfw_conf->{rules};
1334
1335 my $options = $vmfw_conf->{options};
1336 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1337
1338 my $chain = "venet0-$vmid-$direction";
1339
1340 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1341
1342 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1343
1344 # implement policy
1345 my $policy;
1346
1347 if ($direction eq 'OUT') {
1348 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1349 } else {
1350 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1351 }
1352
1353 my $accept = generate_nfqueue($options);
1354 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1355 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1356
1357 # plug into FORWARD, INPUT and OUTPUT chain
1358 if ($direction eq 'OUT') {
1359 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD", {
1360 action => $chain,
1361 source => $ip,
1362 iface_in => 'venet0'});
1363
1364 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT", {
1365 action => $chain,
1366 source => $ip,
1367 iface_in => 'venet0'});
1368 } else {
1369 ruleset_generate_rule($ruleset, "PVEFW-FORWARD", {
1370 action => $chain,
1371 dest => $ip,
1372 iface_out => 'venet0'});
1373
1374 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT", {
1375 action => $chain,
1376 dest => $ip,
1377 iface_out => 'venet0'});
1378 }
1379 }
1380
1381 sub generate_tap_rules_direction {
1382 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1383
1384 my $lc_direction = lc($direction);
1385
1386 my $rules = $vmfw_conf->{rules};
1387
1388 my $options = $vmfw_conf->{options};
1389 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1390
1391 my $tapchain = "$iface-$direction";
1392
1393 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1394
1395 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1396
1397 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1398
1399 # implement policy
1400 my $policy;
1401
1402 if ($direction eq 'OUT') {
1403 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1404 } else {
1405 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1406 }
1407
1408 my $accept = generate_nfqueue($options);
1409 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1410 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1411
1412 # plug the tap chain to bridge chain
1413 if ($direction eq 'IN') {
1414 ruleset_insertrule($ruleset, "$bridge-IN",
1415 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
1416 } else {
1417 ruleset_insertrule($ruleset, "$bridge-OUT",
1418 "-m physdev --physdev-in $iface -j $tapchain");
1419 }
1420 }
1421
1422 sub enable_host_firewall {
1423 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1424
1425 # fixme: allow security groups
1426
1427 my $options = $hostfw_conf->{options};
1428 my $rules = $hostfw_conf->{rules};
1429
1430 # host inbound firewall
1431 my $chain = "PVEFW-HOST-IN";
1432 ruleset_create_chain($ruleset, $chain);
1433
1434 my $loglevel = get_option_log_level($options, "log_level_in");
1435
1436 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1437 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1438 }
1439
1440 if ($options->{tcpflags}) {
1441 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1442 }
1443
1444 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1445 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
1446 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
1447 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
1448 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
1449 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
1450
1451 # we use RETURN because we need to check also tap rules
1452 my $accept_action = 'RETURN';
1453
1454 foreach my $rule (@$rules) {
1455 next if $rule->{type} ne 'in';
1456 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1457 }
1458
1459 # implement input policy
1460 my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1461 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1462
1463 # host outbound firewall
1464 $chain = "PVEFW-HOST-OUT";
1465 ruleset_create_chain($ruleset, $chain);
1466
1467 $loglevel = get_option_log_level($options, "log_level_out");
1468
1469 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1470 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
1471 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
1472 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
1473 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
1474 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
1475
1476 # we use RETURN because we may want to check other thigs later
1477 $accept_action = 'RETURN';
1478
1479 foreach my $rule (@$rules) {
1480 next if $rule->{type} ne 'out';
1481 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1482 }
1483
1484 # implement output policy
1485 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1486 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1487
1488 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1489 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
1490 }
1491
1492 sub generate_group_rules {
1493 my ($ruleset, $cluster_conf, $group) = @_;
1494 die "no such security group '$group'\n" if !$cluster_conf->{groups}->{$group};
1495
1496 my $rules = $cluster_conf->{groups}->{$group};
1497
1498 my $chain = "GROUP-${group}-IN";
1499
1500 ruleset_create_chain($ruleset, $chain);
1501 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1502
1503 foreach my $rule (@$rules) {
1504 next if $rule->{type} ne 'in';
1505 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1506 }
1507
1508 $chain = "GROUP-${group}-OUT";
1509
1510 ruleset_create_chain($ruleset, $chain);
1511 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1512
1513 foreach my $rule (@$rules) {
1514 next if $rule->{type} ne 'out';
1515 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1516 # check also other tap rules later
1517 ruleset_generate_rule($ruleset, $chain, $rule,
1518 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1519 }
1520 }
1521
1522 my $MAX_NETS = 32;
1523 my $valid_netdev_names = {};
1524 for (my $i = 0; $i < $MAX_NETS; $i++) {
1525 $valid_netdev_names->{"net$i"} = 1;
1526 }
1527
1528 sub parse_fw_rule {
1529 my ($line, $need_iface, $allow_groups) = @_;
1530
1531 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
1532
1533 # we can add single line comments to the end of the rule
1534 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1535
1536 # we can disable a rule when prefixed with '|'
1537 my $enable = 1;
1538
1539 $enable = 0 if $line =~ s/^\|//;
1540
1541 my @data = split(/\s+/, $line);
1542 my $expected_elements = $need_iface ? 8 : 7;
1543
1544 die "wrong number of rule elements\n" if scalar(@data) > $expected_elements;
1545
1546 if ($need_iface) {
1547 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1548 } else {
1549 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1550 }
1551
1552 die "incomplete rule\n" if ! ($type && $action);
1553
1554 my $macro;
1555
1556 $type = lc($type);
1557
1558 if ($type eq 'in' || $type eq 'out') {
1559 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1560 # OK
1561 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1562 $action = $2;
1563 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1564 die "unknown macro '$1'\n" if !$preferred_name;
1565 $macro = $preferred_name;
1566 } else {
1567 die "unknown action '$action'\n";
1568 }
1569 } elsif ($type eq 'group') {
1570 die "wrong number of rule elements\n" if scalar(@data) != 3;
1571 die "groups disabled\n" if !$allow_groups;
1572
1573 die "invalid characters in group name\n" if $action !~ m/^[A-Za-z0-9_\-]+$/;
1574 } else {
1575 die "unknown rule type '$type'\n";
1576 }
1577
1578 if ($need_iface) {
1579 $iface = undef if $iface && $iface eq '-';
1580 }
1581
1582 $proto = undef if $proto && $proto eq '-';
1583 pve_fw_verify_protocol_spec($proto) if $proto;
1584
1585 $source = undef if $source && $source eq '-';
1586 $dest = undef if $dest && $dest eq '-';
1587
1588 $dport = undef if $dport && $dport eq '-';
1589 $sport = undef if $sport && $sport eq '-';
1590
1591 parse_port_name_number_or_range($dport) if defined($dport);
1592 parse_port_name_number_or_range($sport) if defined($sport);
1593
1594 parse_address_list($source) if $source && $source !~ m/^(\+)(\S+)$/;
1595 parse_address_list($dest) if $dest && $dest !~ m/^(\+)(\S+)$/;
1596
1597 return {
1598 type => $type,
1599 enable => $enable,
1600 comment => $comment,
1601 action => $action,
1602 macro => $macro,
1603 iface => $iface,
1604 source => $source,
1605 dest => $dest,
1606 proto => $proto,
1607 dport => $dport,
1608 sport => $sport,
1609 };
1610 }
1611
1612 sub parse_vmfw_option {
1613 my ($line) = @_;
1614
1615 my ($opt, $value);
1616
1617 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1618
1619 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
1620 $opt = lc($1);
1621 $value = int($2);
1622 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1623 $opt = lc($1);
1624 $value = $2 ? lc($3) : '';
1625 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1626 $opt = lc($1);
1627 $value = uc($3);
1628 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1629 $opt = lc($1);
1630 $value = $2;
1631 } else {
1632 chomp $line;
1633 die "can't parse option '$line'\n"
1634 }
1635
1636 return ($opt, $value);
1637 }
1638
1639 sub parse_hostfw_option {
1640 my ($line) = @_;
1641
1642 my ($opt, $value);
1643
1644 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1645
1646 if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1647 $opt = lc($1);
1648 $value = int($2);
1649 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1650 $opt = lc($1);
1651 $value = $2 ? lc($3) : '';
1652 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1653 $opt = lc($1);
1654 $value = uc($3);
1655 } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
1656 $opt = lc($1);
1657 $value = int($2);
1658 } else {
1659 chomp $line;
1660 die "can't parse option '$line'\n"
1661 }
1662
1663 return ($opt, $value);
1664 }
1665
1666 sub parse_clusterfw_option {
1667 my ($line) = @_;
1668
1669 my ($opt, $value);
1670
1671 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1672 $opt = lc($1);
1673 $value = int($2);
1674 } else {
1675 chomp $line;
1676 die "can't parse option '$line'\n"
1677 }
1678
1679 return ($opt, $value);
1680 }
1681
1682 sub parse_vm_fw_rules {
1683 my ($filename, $fh) = @_;
1684
1685 my $res = { rules => [], options => {}};
1686
1687 my $section;
1688
1689 my $digest = Digest::SHA->new('sha1');
1690
1691 while (defined(my $line = <$fh>)) {
1692 $digest->add($line);
1693
1694 next if $line =~ m/^#/;
1695 next if $line =~ m/^\s*$/;
1696
1697 my $linenr = $fh->input_line_number();
1698 my $prefix = "$filename (line $linenr)";
1699
1700 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1701 $section = lc($1);
1702 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1703 next;
1704 }
1705 if (!$section) {
1706 warn "$prefix: skip line - no section";
1707 next;
1708 }
1709
1710 next if !$res->{$section}; # skip undefined section
1711
1712 if ($section eq 'options') {
1713 eval {
1714 my ($opt, $value) = parse_vmfw_option($line);
1715 $res->{options}->{$opt} = $value;
1716 };
1717 warn "$prefix: $@" if $@;
1718 next;
1719 }
1720
1721 my $rule;
1722 eval { $rule = parse_fw_rule($line, 1, 1); };
1723 if (my $err = $@) {
1724 warn "$prefix: $err";
1725 next;
1726 }
1727
1728 push @{$res->{$section}}, $rule;
1729 }
1730
1731 $res->{digest} = $digest->b64digest;
1732
1733 return $res;
1734 }
1735
1736 sub parse_host_fw_rules {
1737 my ($filename, $fh) = @_;
1738
1739 my $res = { rules => [], options => {}};
1740
1741 my $section;
1742
1743 my $digest = Digest::SHA->new('sha1');
1744
1745 while (defined(my $line = <$fh>)) {
1746 $digest->add($line);
1747
1748 next if $line =~ m/^#/;
1749 next if $line =~ m/^\s*$/;
1750
1751 my $linenr = $fh->input_line_number();
1752 my $prefix = "$filename (line $linenr)";
1753
1754 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1755 $section = lc($1);
1756 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1757 next;
1758 }
1759 if (!$section) {
1760 warn "$prefix: skip line - no section";
1761 next;
1762 }
1763
1764 next if !$res->{$section}; # skip undefined section
1765
1766 if ($section eq 'options') {
1767 eval {
1768 my ($opt, $value) = parse_hostfw_option($line);
1769 $res->{options}->{$opt} = $value;
1770 };
1771 warn "$prefix: $@" if $@;
1772 next;
1773 }
1774
1775 my $rule;
1776 eval { $rule = parse_fw_rule($line, 1, 1); };
1777 if (my $err = $@) {
1778 warn "$prefix: $err";
1779 next;
1780 }
1781
1782 push @{$res->{$section}}, $rule;
1783 }
1784
1785 $res->{digest} = $digest->b64digest;
1786
1787 return $res;
1788 }
1789
1790 sub parse_cluster_fw_rules {
1791 my ($filename, $fh) = @_;
1792
1793 my $section;
1794 my $group;
1795
1796 my $res = { rules => [], options => {}, groups => {}, ipset => {} };
1797
1798 my $digest = Digest::SHA->new('sha1');
1799
1800 while (defined(my $line = <$fh>)) {
1801 $digest->add($line);
1802
1803 next if $line =~ m/^#/;
1804 next if $line =~ m/^\s*$/;
1805
1806 my $linenr = $fh->input_line_number();
1807 my $prefix = "$filename (line $linenr)";
1808
1809 if ($line =~ m/^\[options\]$/i) {
1810 $section = 'options';
1811 next;
1812 }
1813
1814 if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
1815 $section = 'groups';
1816 $group = lc($1);
1817 next;
1818 }
1819
1820 if ($line =~ m/^\[rules\]$/i) {
1821 $section = 'rules';
1822 next;
1823 }
1824
1825 if ($line =~ m/^\[ipset\s+(\S+)\]\s*$/i) {
1826 $section = 'ipset';
1827 $group = lc($1);
1828 next;
1829 }
1830
1831 if (!$section) {
1832 warn "$prefix: skip line - no section\n";
1833 next;
1834 }
1835
1836 if ($section eq 'options') {
1837 eval {
1838 my ($opt, $value) = parse_clusterfw_option($line);
1839 $res->{options}->{$opt} = $value;
1840 };
1841 warn "$prefix: $@" if $@;
1842 } elsif ($section eq 'rules') {
1843 my $rule;
1844 eval { $rule = parse_fw_rule($line, 1, 1); };
1845 if (my $err = $@) {
1846 warn "$prefix: $err";
1847 next;
1848 }
1849 push @{$res->{$section}}, $rule;
1850 } elsif ($section eq 'groups') {
1851 my $rule;
1852 eval { $rule = parse_fw_rule($line, 0, 0); };
1853 if (my $err = $@) {
1854 warn "$prefix: $err";
1855 next;
1856 }
1857 push @{$res->{$section}->{$group}}, $rule;
1858 } elsif ($section eq 'ipset') {
1859 chomp $line;
1860 $line =~ m/^(\!)?\s*((\d+)\.(\d+)\.(\d+)\.(\d+)(\/(\d+))?)/;
1861 my $nomatch = $1;
1862 my $ip = $2;
1863
1864 if(!$ip){
1865 warn "$prefix: $line is not an valid ip address\n";
1866 next;
1867 }
1868 if (!Net::IP->new($ip)) {
1869 warn "$prefix: $line is not an valid ip address\n";
1870 next;
1871 }
1872
1873 if ($nomatch) {
1874 if ($feature_ipset_nomatch) {
1875 push @{$res->{$section}->{$group}}, "$ip nomatch";
1876 } else {
1877 warn "$prefix: ignore $line - nomatch not supported by kernel\n";
1878 }
1879 } else {
1880 push @{$res->{$section}->{$group}}, $ip;
1881 }
1882 }
1883 }
1884
1885 $res->{digest} = $digest->b64digest;
1886 return $res;
1887 }
1888
1889 sub run_locked {
1890 my ($code, @param) = @_;
1891
1892 my $timeout = 10;
1893
1894 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
1895
1896 die $@ if $@;
1897
1898 return $res;
1899 }
1900
1901 sub read_local_vm_config {
1902
1903 my $openvz = {};
1904 my $qemu = {};
1905
1906 my $vmdata = { openvz => $openvz, qemu => $qemu };
1907
1908 my $vmlist = PVE::Cluster::get_vmlist();
1909 return $vmdata if !$vmlist || !$vmlist->{ids};
1910 my $ids = $vmlist->{ids};
1911
1912 foreach my $vmid (keys %$ids) {
1913 next if !$vmid; # skip VE0
1914 my $d = $ids->{$vmid};
1915 next if !$d->{node} || $d->{node} ne $nodename;
1916 next if !$d->{type};
1917 if ($d->{type} eq 'openvz') {
1918 if ($have_pve_manager) {
1919 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
1920 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
1921 $openvz->{$vmid} = $conf;
1922 }
1923 }
1924 } elsif ($d->{type} eq 'qemu') {
1925 if ($have_qemu_server) {
1926 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
1927 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
1928 $qemu->{$vmid} = $conf;
1929 }
1930 }
1931 }
1932 }
1933
1934 return $vmdata;
1935 };
1936
1937 sub load_vmfw_conf {
1938 my ($vmid) = @_;
1939
1940 my $vmfw_conf = {};
1941
1942 my $filename = "/etc/pve/firewall/$vmid.fw";
1943 if (my $fh = IO::File->new($filename, O_RDONLY)) {
1944 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
1945 }
1946
1947 return $vmfw_conf;
1948 }
1949
1950 my $format_rules = sub {
1951 my ($rules, $need_iface) = @_;
1952
1953 my $raw = '';
1954
1955 foreach my $rule (@$rules) {
1956 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1957 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
1958 $raw .= uc($rule->{type});
1959 $raw .= " " . $rule->{action};
1960 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
1961 $raw .= " " . ($rule->{source} || '-');
1962 $raw .= " " . ($rule->{dest} || '-');
1963 $raw .= " " . ($rule->{proto} || '-');
1964 $raw .= " " . ($rule->{dport} || '-');
1965 $raw .= " " . ($rule->{sport} || '-');
1966 $raw .= " # " . encode('utf8', $rule->{comment})
1967 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
1968 $raw .= "\n";
1969 } else {
1970 die "implement me '$rule->{type}'";
1971 }
1972 }
1973
1974 return $raw;
1975 };
1976
1977 my $format_options = sub {
1978 my ($options) = @_;
1979
1980 my $raw = '';
1981
1982 $raw .= "[OPTIONS]\n\n";
1983 foreach my $opt (keys %$options) {
1984 $raw .= "$opt: $options->{$opt}\n";
1985 }
1986 $raw .= "\n";
1987
1988 return $raw;
1989 };
1990
1991 sub save_vmfw_conf {
1992 my ($vmid, $vmfw_conf) = @_;
1993
1994 my $raw = '';
1995
1996 my $options = $vmfw_conf->{options};
1997 $raw .= &$format_options($options) if scalar(keys %$options);
1998
1999 my $rules = $vmfw_conf->{rules};
2000 if (scalar(@$rules)) {
2001 $raw .= "[RULES]\n\n";
2002 $raw .= &$format_rules($rules, 1);
2003 $raw .= "\n";
2004 }
2005
2006 my $filename = "/etc/pve/firewall/$vmid.fw";
2007 PVE::Tools::file_set_contents($filename, $raw);
2008 }
2009
2010 sub read_vm_firewall_configs {
2011 my ($vmdata) = @_;
2012 my $vmfw_configs = {};
2013
2014 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2015 my $vmfw_conf = load_vmfw_conf($vmid);
2016 next if !$vmfw_conf->{options}; # skip if file does not exists
2017 $vmfw_configs->{$vmid} = $vmfw_conf;
2018 }
2019
2020 return $vmfw_configs;
2021 }
2022
2023 sub get_option_log_level {
2024 my ($options, $k) = @_;
2025
2026 my $v = $options->{$k};
2027 $v = $default_log_level if !defined($v);
2028
2029 return undef if $v eq '' || $v eq 'nolog';
2030
2031 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2032
2033 return $v if ($v >= 0) && ($v <= 7);
2034
2035 warn "unknown log level ($k = '$v')\n";
2036
2037 return undef;
2038 }
2039
2040 sub generate_std_chains {
2041 my ($ruleset, $options) = @_;
2042
2043 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2044
2045 # same as shorewall smurflog.
2046 my $chain = 'PVEFW-smurflog';
2047
2048 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2049 push @{$pve_std_chains->{$chain}}, "-j DROP";
2050
2051 # same as shorewall logflags action.
2052 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
2053 $chain = 'PVEFW-logflags';
2054 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2055 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2056 push @{$pve_std_chains->{$chain}}, "-j DROP";
2057
2058 foreach my $chain (keys %$pve_std_chains) {
2059 ruleset_create_chain($ruleset, $chain);
2060 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2061 if (ref($rule)) {
2062 ruleset_generate_rule($ruleset, $chain, $rule);
2063 } else {
2064 ruleset_addrule($ruleset, $chain, $rule);
2065 }
2066 }
2067 }
2068 }
2069
2070 sub generate_ipset_chains {
2071 my ($ipset_ruleset, $fw_conf) = @_;
2072
2073 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2074 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
2075 }
2076 }
2077
2078 sub generate_ipset {
2079 my ($ipset_ruleset, $name, $options) = @_;
2080
2081 my $hashsize = scalar(@$options);
2082 if ($hashsize <= 64) {
2083 $hashsize = 64;
2084 } else {
2085 $hashsize = round_powerof2($hashsize);
2086 }
2087
2088 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2089
2090 foreach my $ip (@$options) {
2091 push @{$ipset_ruleset->{$name}}, "add $name $ip";
2092 }
2093 }
2094
2095 sub round_powerof2 {
2096 my ($int) = @_;
2097
2098 $int--;
2099 $int |= $int >> $_ foreach (1,2,4,8,16);
2100 return ++$int;
2101 }
2102
2103 sub save_pvefw_status {
2104 my ($status) = @_;
2105
2106 die "unknown status '$status' - internal error"
2107 if $status !~ m/^(stopped|active)$/;
2108
2109 mkdir dirname($pve_fw_status_filename);
2110 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2111 }
2112
2113 sub read_pvefw_status {
2114
2115 my $status = 'unknown';
2116
2117 return 'stopped' if ! -f $pve_fw_status_filename;
2118
2119 eval {
2120 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2121 };
2122 warn $@ if $@;
2123
2124 return $status;
2125 }
2126
2127 # fixme: move to pve-common PVE::ProcFSTools
2128 sub read_proc_net_route {
2129 my $filename = "/proc/net/route";
2130
2131 my $res = {};
2132
2133 my $fh = IO::File->new ($filename, "r");
2134 return $res if !$fh;
2135
2136 my $int_to_quad = sub {
2137 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2138 };
2139
2140 while (defined(my $line = <$fh>)) {
2141 next if $line =~/^Iface\s+Destination/; # skip head
2142 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2143 push @{$res->{$iface}}, {
2144 dest => &$int_to_quad(hex($dest)),
2145 gateway => &$int_to_quad(hex($gateway)),
2146 mask => &$int_to_quad(hex($mask)),
2147 metric => $metric,
2148 mtu => $mtu,
2149 };
2150 }
2151
2152 return $res;
2153 }
2154
2155 sub load_clusterfw_conf {
2156
2157 my $cluster_conf = {};
2158 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
2159 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
2160 }
2161
2162 return $cluster_conf;
2163 }
2164
2165 sub save_clusterfw_conf {
2166 my ($cluster_conf) = @_;
2167
2168 my $raw = '';
2169
2170 my $options = $cluster_conf->{options};
2171 $raw .= &$format_options($options) if scalar(keys %$options);
2172
2173 # fixme: save ipset
2174
2175 my $rules = $cluster_conf->{rules};
2176 if (scalar(@$rules)) {
2177 $raw .= "[RULES]\n\n";
2178 $raw .= &$format_rules($rules, 1);
2179 $raw .= "\n";
2180 }
2181
2182 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2183 my $rules = $cluster_conf->{groups}->{$group};
2184 $raw .= "[group $group]\n\n";
2185 $raw .= &$format_rules($rules, 0);
2186 $raw .= "\n";
2187 }
2188
2189 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2190 }
2191
2192 sub load_hostfw_conf {
2193
2194 my $hostfw_conf = {};
2195 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2196 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
2197 }
2198 return $hostfw_conf;
2199 }
2200
2201 sub save_hostfw_conf {
2202 my ($hostfw_conf) = @_;
2203
2204 my $raw = '';
2205
2206 my $options = $hostfw_conf->{options};
2207 $raw .= &$format_options($options) if scalar(keys %$options);
2208
2209 my $rules = $hostfw_conf->{rules};
2210 if (scalar(@$rules)) {
2211 $raw .= "[RULES]\n\n";
2212 $raw .= &$format_rules($rules, 1);
2213 $raw .= "\n";
2214 }
2215
2216 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2217 }
2218
2219 sub compile {
2220 my $vmdata = read_local_vm_config();
2221 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2222
2223 my $routing_table = read_proc_net_route();
2224
2225 my $cluster_conf = load_clusterfw_conf();
2226
2227 my $ipset_ruleset = {};
2228 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2229
2230 my $ruleset = {};
2231
2232 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2233 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2234
2235 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2236
2237 my $hostfw_conf = load_hostfw_conf();
2238 my $hostfw_options = $hostfw_conf->{options} || {};
2239
2240 generate_std_chains($ruleset, $hostfw_options);
2241
2242 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2243
2244 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2245
2246 # generate firewall rules for QEMU VMs
2247 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2248 my $conf = $vmdata->{qemu}->{$vmid};
2249 my $vmfw_conf = $vmfw_configs->{$vmid};
2250 next if !$vmfw_conf;
2251 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2252
2253 foreach my $netid (keys %$conf) {
2254 next if $netid !~ m/^net(\d+)$/;
2255 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2256 next if !$net;
2257 my $iface = "tap${vmid}i$1";
2258
2259 my $bridge = $net->{bridge};
2260 next if !$bridge; # fixme: ?
2261
2262 $bridge .= "v$net->{tag}" if $net->{tag};
2263
2264 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2265
2266 my $macaddr = $net->{macaddr};
2267 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2268 $vmfw_conf, $vmid, $bridge, 'IN');
2269 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2270 $vmfw_conf, $vmid, $bridge, 'OUT');
2271 }
2272 }
2273
2274 # generate firewall rules for OpenVZ containers
2275 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2276 my $conf = $vmdata->{openvz}->{$vmid};
2277
2278 my $vmfw_conf = $vmfw_configs->{$vmid};
2279 next if !$vmfw_conf;
2280 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2281
2282 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2283 my $ip = $conf->{ip_address}->{value};
2284 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN');
2285 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT');
2286 }
2287
2288 if ($conf->{netif} && $conf->{netif}->{value}) {
2289 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2290 foreach my $netid (keys %$netif) {
2291 my $d = $netif->{$netid};
2292 my $bridge = $d->{bridge};
2293 if (!$bridge) {
2294 warn "no bridge device for CT $vmid iface '$netid'\n";
2295 next; # fixme?
2296 }
2297
2298 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2299
2300 my $macaddr = $d->{mac};
2301 my $iface = $d->{host_ifname};
2302 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2303 $vmfw_conf, $vmid, $bridge, 'IN');
2304 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2305 $vmfw_conf, $vmid, $bridge, 'OUT');
2306 }
2307 }
2308 }
2309
2310 if($hostfw_options->{optimize}){
2311
2312 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
2313 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
2314 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2315 }
2316
2317 # fixme: what log level should we use here?
2318 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2319
2320 # fixme: should we really block inter-bridge traffic?
2321
2322 # always allow traffic from containers?
2323 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2324
2325 # disable interbridge routing
2326 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
2327 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
2328 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2329 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2330 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
2331 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2332
2333 return wantarray ? ($ruleset, $hostfw_conf, $ipset_ruleset) : $ruleset;
2334 }
2335
2336 sub get_ruleset_status {
2337 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2338
2339 my $statushash = {};
2340
2341 foreach my $chain (sort keys %$ruleset) {
2342 my $sig = &$digest_fn($ruleset->{$chain});
2343
2344 $statushash->{$chain}->{sig} = $sig;
2345
2346 my $oldsig = $active_chains->{$chain};
2347 if (!defined($oldsig)) {
2348 $statushash->{$chain}->{action} = 'create';
2349 } else {
2350 if ($oldsig eq $sig) {
2351 $statushash->{$chain}->{action} = 'exists';
2352 } else {
2353 $statushash->{$chain}->{action} = 'update';
2354 }
2355 }
2356 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2357 foreach my $cmd (@{$ruleset->{$chain}}) {
2358 print "\t$cmd\n" if $verbose;
2359 }
2360 }
2361
2362 foreach my $chain (sort keys %$active_chains) {
2363 if (!defined($ruleset->{$chain})) {
2364 my $sig = $active_chains->{$chain};
2365 $statushash->{$chain}->{action} = 'delete';
2366 $statushash->{$chain}->{sig} = $sig;
2367 print "delete $chain ($sig)\n" if $verbose;
2368 }
2369 }
2370
2371 return $statushash;
2372 }
2373
2374 sub print_sig_rule {
2375 my ($chain, $sig) = @_;
2376
2377 # We just use this to store a SHA1 checksum used to detect changes
2378 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2379 }
2380
2381 sub get_ruleset_cmdlist {
2382 my ($ruleset, $verbose) = @_;
2383
2384 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2385
2386 my ($active_chains, $hooks) = iptables_get_chains();
2387 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2388
2389 # create missing chains first
2390 foreach my $chain (sort keys %$ruleset) {
2391 my $stat = $statushash->{$chain};
2392 die "internal error" if !$stat;
2393 next if $stat->{action} ne 'create';
2394
2395 $cmdlist .= ":$chain - [0:0]\n";
2396 }
2397
2398 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2399 if (!$hooks->{$h}) {
2400 $cmdlist .= "-A $h -j PVEFW-$h\n";
2401 }
2402 }
2403
2404 foreach my $chain (sort keys %$ruleset) {
2405 my $stat = $statushash->{$chain};
2406 die "internal error" if !$stat;
2407
2408 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
2409 $cmdlist .= "-F $chain\n";
2410 foreach my $cmd (@{$ruleset->{$chain}}) {
2411 $cmdlist .= "$cmd\n";
2412 }
2413 $cmdlist .= print_sig_rule($chain, $stat->{sig});
2414 } elsif ($stat->{action} eq 'delete') {
2415 die "internal error"; # this should not happen
2416 } elsif ($stat->{action} eq 'exists') {
2417 # do nothing
2418 } else {
2419 die "internal error - unknown status '$stat->{action}'";
2420 }
2421 }
2422
2423 foreach my $chain (keys %$statushash) {
2424 next if $statushash->{$chain}->{action} ne 'delete';
2425 $cmdlist .= "-F $chain\n";
2426 }
2427 foreach my $chain (keys %$statushash) {
2428 next if $statushash->{$chain}->{action} ne 'delete';
2429 next if $chain eq 'PVEFW-INPUT';
2430 next if $chain eq 'PVEFW-OUTPUT';
2431 next if $chain eq 'PVEFW-FORWARD';
2432 $cmdlist .= "-X $chain\n";
2433 }
2434
2435 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
2436
2437 $cmdlist .= "COMMIT\n";
2438
2439 return wantarray ? ($cmdlist, $changes) : $cmdlist;
2440 }
2441
2442 sub get_ipset_cmdlist {
2443 my ($ruleset, $verbose) = @_;
2444
2445 my $cmdlist = "";
2446
2447 my $delete_cmdlist = "";
2448
2449 my $active_chains = ipset_get_chains();
2450 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
2451
2452 foreach my $chain (sort keys %$ruleset) {
2453 my $stat = $statushash->{$chain};
2454 die "internal error" if !$stat;
2455
2456 if ($stat->{action} eq 'create') {
2457 foreach my $cmd (@{$ruleset->{$chain}}) {
2458 $cmdlist .= "$cmd\n";
2459 }
2460 }
2461
2462 if ($stat->{action} eq 'update') {
2463 my $chain_swap = $chain."_swap";
2464
2465 foreach my $cmd (@{$ruleset->{$chain}}) {
2466 $cmd =~ s/$chain/$chain_swap/;
2467 $cmdlist .= "$cmd\n";
2468 }
2469 $cmdlist .= "swap $chain_swap $chain\n";
2470 $cmdlist .= "flush $chain_swap\n";
2471 $cmdlist .= "destroy $chain_swap\n";
2472 }
2473
2474 }
2475
2476 foreach my $chain (keys %$statushash) {
2477 next if $statushash->{$chain}->{action} ne 'delete';
2478
2479 $delete_cmdlist .= "flush $chain\n";
2480 $delete_cmdlist .= "destroy $chain\n";
2481 }
2482
2483 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
2484
2485 return ($cmdlist, $delete_cmdlist, $changes);
2486 }
2487
2488 sub apply_ruleset {
2489 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2490
2491 enable_bridge_firewall();
2492
2493 update_nf_conntrack_max($hostfw_conf);
2494
2495 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2496 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
2497
2498 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
2499
2500 if ($verbose) {
2501 if ($ipset_changes) {
2502 print "ipset changes:\n";
2503 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2504 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2505 }
2506
2507 if ($changes) {
2508 print "iptables changes:\n";
2509 print $cmdlist;
2510 }
2511 }
2512
2513 ipset_restore_cmdlist($ipset_create_cmdlist);
2514
2515 iptables_restore_cmdlist($cmdlist);
2516
2517 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2518
2519 # test: re-read status and check if everything is up to date
2520 my $active_chains = iptables_get_chains();
2521 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
2522
2523 my $errors;
2524 foreach my $chain (sort keys %$ruleset) {
2525 my $stat = $statushash->{$chain};
2526 if ($stat->{action} ne 'exists') {
2527 warn "unable to update chain '$chain'\n";
2528 $errors = 1;
2529 }
2530 }
2531
2532 die "unable to apply firewall changes\n" if $errors;
2533 }
2534
2535 sub update_nf_conntrack_max {
2536 my ($hostfw_conf) = @_;
2537
2538 my $max = 65536; # reasonable default
2539
2540 my $options = $hostfw_conf->{options} || {};
2541
2542 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
2543 $max = $options->{nf_conntrack_max};
2544 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2545 }
2546
2547 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2548 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2549
2550 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
2551
2552 if ($current != $max) {
2553 my $hashsize = int($max/4);
2554 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
2555 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
2556 }
2557 }
2558
2559 sub remove_pvefw_chains {
2560
2561 my ($chash, $hooks) = iptables_get_chains();
2562 my $cmdlist = "*filter\n";
2563
2564 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2565 if ($hooks->{$h}) {
2566 $cmdlist .= "-D $h -j PVEFW-$h\n";
2567 }
2568 }
2569
2570 foreach my $chain (keys %$chash) {
2571 $cmdlist .= "-F $chain\n";
2572 }
2573
2574 foreach my $chain (keys %$chash) {
2575 $cmdlist .= "-X $chain\n";
2576 }
2577 $cmdlist .= "COMMIT\n";
2578
2579 iptables_restore_cmdlist($cmdlist);
2580 }
2581
2582 sub update {
2583 my ($start, $verbose) = @_;
2584
2585 my $code = sub {
2586 my $status = read_pvefw_status();
2587
2588 my ($ruleset, $hostfw_conf, $ipset_ruleset) = compile();
2589
2590 if ($start || $status eq 'active') {
2591
2592 save_pvefw_status('active') if ($status ne 'active');
2593
2594 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
2595 } else {
2596 print "Firewall not active (status = $status)\n" if $verbose;
2597 }
2598 };
2599
2600 run_locked($code);
2601 }
2602
2603
2604 1;