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