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