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