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