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