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