]> git.proxmox.com Git - pve-firewall.git/blame - src/PVE/Firewall.pm
verify macro parameters when updating a rule using API
[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;
fcba0beb 697 foreach my $item (split(/,/, $str)) {
7ca36671
DM
698 $count++;
699 if ($item =~ m/^(\d+):(\d+)$/) {
700 my ($port1, $port2) = ($1, $2);
701 die "invalid port '$port1'\n" if $port1 > 65535;
702 die "invalid port '$port2'\n" if $port2 > 65535;
703 } elsif ($item =~ m/^(\d+)$/) {
704 my $port = $1;
705 die "invalid port '$port'\n" if $port > 65535;
706 } else {
707 die "invalid port '$item'\n" if !$services->{byname}->{$item};
fcba0beb
DM
708 }
709 }
710
7ca36671 711 return $count;
fcba0beb
DM
712}
713
54cd19a8
DM
714PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
715sub pve_fw_verify_port_spec {
716 my ($portstr) = @_;
717
7ca36671 718 parse_port_name_number_or_range($portstr);
54cd19a8
DM
719
720 return $portstr;
721}
722
723PVE::JSONSchema::register_format('pve-fw-v4addr-spec', \&pve_fw_verify_v4addr_spec);
724sub pve_fw_verify_v4addr_spec {
725 my ($list) = @_;
726
727 parse_address_list($list);
728
729 return $list;
730}
731
732PVE::JSONSchema::register_format('pve-fw-protocol-spec', \&pve_fw_verify_protocol_spec);
733sub pve_fw_verify_protocol_spec {
734 my ($proto) = @_;
735
736 my $protocols = get_etc_protocols();
737
738 die "unknown protocol '$proto'\n" if $proto &&
739 !(defined($protocols->{byname}->{$proto}) ||
740 defined($protocols->{byid}->{$proto}));
741
742 return $proto;
743}
744
745
d1c53b3e 746# helper function for API
d1c53b3e 747
9c7e0858
DM
748my $rule_properties = {
749 pos => {
750 description => "Update rule at position <pos>.",
751 type => 'integer',
752 minimum => 0,
753 optional => 1,
754 },
755 digest => {
756 type => 'string',
757 optional => 1,
54cd19a8
DM
758 maxLength => 27,
759 minLength => 27,
9c7e0858
DM
760 },
761 type => {
762 type => 'string',
763 optional => 1,
764 enum => ['in', 'out', 'group'],
765 },
766 action => {
767 type => 'string',
768 optional => 1,
54cd19a8 769 enum => ['ACCEPT', 'DROP', 'REJECT'],
9c7e0858 770 },
e5076eee
DM
771 macro => {
772 type => 'string',
773 optional => 1,
54cd19a8 774 maxLength => 128,
e5076eee 775 },
54cd19a8 776 iface => get_standard_option('pve-iface', { optional => 1 }),
9c7e0858 777 source => {
54cd19a8 778 type => 'string', format => 'pve-fw-v4addr-spec',
9c7e0858
DM
779 optional => 1,
780 },
781 dest => {
54cd19a8 782 type => 'string', format => 'pve-fw-v4addr-spec',
9c7e0858
DM
783 optional => 1,
784 },
785 proto => {
54cd19a8 786 type => 'string', format => 'pve-fw-protocol-spec',
9c7e0858
DM
787 optional => 1,
788 },
789 enable => {
790 type => 'boolean',
791 optional => 1,
792 },
793 sport => {
54cd19a8 794 type => 'string', format => 'pve-fw-port-spec',
9c7e0858
DM
795 optional => 1,
796 },
797 dport => {
54cd19a8 798 type => 'string', format => 'pve-fw-port-spec',
9c7e0858
DM
799 optional => 1,
800 },
801 comment => {
802 type => 'string',
803 optional => 1,
804 },
805};
806
ce36326d
DM
807sub cleanup_fw_rule {
808 my ($rule, $digest, $pos) = @_;
809
810 my $r = {};
811
812 foreach my $k (keys %$rule) {
813 next if !$rule_properties->{$k};
814 my $v = $rule->{$k};
815 next if !defined($v);
816 $r->{$k} = $v;
817 $r->{digest} = $digest;
818 $r->{pos} = $pos;
819 }
820
821 return $r;
822}
823
9c7e0858
DM
824sub add_rule_properties {
825 my ($properties) = @_;
826
827 foreach my $k (keys %$rule_properties) {
3655b01f
DM
828 my $h = $rule_properties->{$k};
829 # copy data, so that we can modify later without side effects
830 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
9c7e0858 831 }
cbb5d6f3 832
9c7e0858
DM
833 return $properties;
834}
835
5b7974df
DM
836sub delete_rule_properties {
837 my ($rule, $delete_str) = @_;
838
839 foreach my $opt (PVE::Tools::split_list($delete_str)) {
840 raise_param_exc({ 'delete' => "no such property ('$opt')"})
841 if !defined($rule_properties->{$opt});
842 raise_param_exc({ 'delete' => "unable to delete required property '$opt'"})
843 if $opt eq 'type' || $opt eq 'action';
844 delete $rule->{$opt};
845 }
846
847 return $rule;
848}
849
9a2745a0
DM
850my $apply_macro = sub {
851 my ($macro_name, $param, $verify) = @_;
852
853 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
854 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
855
856 my $rules = [];
857
858 foreach my $templ (@$macro_rules) {
859 my $rule = {};
860 my $param_used = {};
861 foreach my $k (keys %$templ) {
862 my $v = $templ->{$k};
863 if ($v eq 'PARAM') {
864 $v = $param->{$k};
865 $param_used->{$k} = 1;
866 } elsif ($v eq 'DEST') {
867 $v = $param->{dest};
868 $param_used->{dest} = 1;
869 } elsif ($v eq 'SOURCE') {
870 $v = $param->{source};
871 $param_used->{source} = 1;
872 }
873
874 if (!defined($v)) {
875 my $msg = "missing parameter '$k' in macro '$macro_name'";
876 raise_param_exc({ macro => $msg }) if $verify;
877 die "$msg\n";
878 }
879 $rule->{$k} = $v;
880 }
881 foreach my $k (keys %$param) {
882 next if $k eq 'macro';
883 next if !defined($param->{$k});
884 next if $param_used->{$k};
885 if (defined($rule->{$k})) {
886 if ($rule->{$k} ne $param->{$k}) {
887 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
888 raise_param_exc({ $k => $msg }) if $verify;
889 die "$msg\n";
890 }
891 } else {
892 $rule->{$k} = $param->{$k};
893 }
894 }
895 push @$rules, $rule;
896 }
897
898 return $rules;
899};
900
7ca36671
DM
901sub verify_rule {
902 my ($rule, $allow_groups) = @_;
903
904 my $type = $rule->{type};
905
906 raise_param_exc({ type => "missing property"}) if !$type;
907 raise_param_exc({ action => "missing property"}) if !$rule->{action};
908
909 if ($type eq 'in' || $type eq 'out') {
910 raise_param_exc({ action => "unknown action '$rule->{action}'"})
911 if $rule->{action} !~ m/^(ACCEPT|DROP|REJECT)$/;
912 } elsif ($type eq 'group') {
913 raise_param_exc({ type => "security groups not allowed"})
914 if !$allow_groups;
915 raise_param_exc({ action => "invalid characters in security group name"})
916 if $rule->{action} !~ m/^[A-Za-z0-9_\-]+$/;
917 } else {
918 raise_param_exc({ type => "unknown rule type '$type'"});
919 }
920
921 # fixme: verify $rule->{iface}?
922
923 if ($rule->{macro}) {
924 my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
925 raise_param_exc({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
926 $rule->{macro} = $preferred_name;
927 }
928
929 if ($rule->{dport}) {
930 eval { parse_port_name_number_or_range($rule->{dport}); };
931 raise_param_exc({ dport => $@ }) if $@;
932 }
933
934 if ($rule->{sport}) {
935 eval { parse_port_name_number_or_range($rule->{sport}); };
936 raise_param_exc({ sport => $@ }) if $@;
937 }
938
939 if ($rule->{source}) {
940 eval { parse_address_list($rule->{source}); };
941 raise_param_exc({ source => $@ }) if $@;
942 }
943
944 if ($rule->{dest}) {
945 eval { parse_address_list($rule->{dest}); };
946 raise_param_exc({ dest => $@ }) if $@;
947 }
948
9a2745a0
DM
949 if ($rule->{macro}) {
950 &$apply_macro($rule->{macro}, $rule, 1);
951 }
952
7ca36671
DM
953 return $rule;
954}
955
9c7e0858
DM
956sub copy_rule_data {
957 my ($rule, $param) = @_;
958
959 foreach my $k (keys %$rule_properties) {
960 if (defined(my $v = $param->{$k})) {
961 if ($v eq '' || $v eq '-') {
962 delete $rule->{$k};
963 } else {
964 $rule->{$k} = $v;
965 }
966 } else {
967 delete $rule->{$k};
968 }
969 }
7ca36671
DM
970
971 # verify rule now
972
9c7e0858
DM
973 return $rule;
974}
975
976# core functions
780bcc0f
DM
977my $bridge_firewall_enabled = 0;
978
979sub enable_bridge_firewall {
980
981 return if $bridge_firewall_enabled; # only once
982
5f0a912c
DM
983 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
984 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
780bcc0f 985
6a8a75db
DM
986 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
987 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
988
780bcc0f
DM
989 $bridge_firewall_enabled = 1;
990}
991
8cebfa6f 992my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
dddd9413 993
b16e818e
DM
994sub iptables_restore_cmdlist {
995 my ($cmdlist) = @_;
3a616aa0 996
3fa83edf 997 run_command("/sbin/iptables-restore -n", input => $cmdlist);
3a616aa0
AD
998}
999
34cdedfa
AD
1000sub ipset_restore_cmdlist {
1001 my ($cmdlist) = @_;
1002
dd7a13fd 1003 run_command("/usr/sbin/ipset restore", input => $cmdlist);
34cdedfa
AD
1004}
1005
de2a57cd
DM
1006sub iptables_get_chains {
1007
1008 my $res = {};
1009
1010 # check what chains we want to track
1011 my $is_pvefw_chain = sub {
1012 my $name = shift;
1013
dec84fcd
DM
1014 return 1 if $name =~ m/^PVEFW-\S+$/;
1015
de2a57cd 1016 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
954f24b1
DM
1017
1018 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1019
9e15114a
DM
1020 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1021
da6fc60b 1022 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
f50656c2 1023 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
de2a57cd
DM
1024
1025 return undef;
1026 };
1027
1028 my $table = '';
1029
c4a2e5ae
DM
1030 my $hooks = {};
1031
de2a57cd
DM
1032 my $parser = sub {
1033 my $line = shift;
1034
1035 return if $line =~ m/^#/;
1036 return if $line =~ m/^\s*$/;
1037
1038 if ($line =~ m/^\*(\S+)$/) {
1039 $table = $1;
1040 return;
1041 }
1042
1043 return if $table ne 'filter';
1044
1045 if ($line =~ m/^:(\S+)\s/) {
1046 my $chain = $1;
1047 return if !&$is_pvefw_chain($chain);
3fa83edf 1048 $res->{$chain} = "unknown";
09d5f68e 1049 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
3fa83edf 1050 my ($chain, $sig) = ($1, $2);
de2a57cd 1051 return if !&$is_pvefw_chain($chain);
3fa83edf 1052 $res->{$chain} = $sig;
c4a2e5ae
DM
1053 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1054 $hooks->{$1} = 1;
de2a57cd
DM
1055 } else {
1056 # simply ignore the rest
1057 return;
1058 }
1059 };
1060
1061 run_command("/sbin/iptables-save", outfunc => $parser);
1062
c4a2e5ae 1063 return wantarray ? ($res, $hooks) : $res;
de2a57cd
DM
1064}
1065
9bf7d929
DM
1066sub iptables_chain_digest {
1067 my ($rules) = @_;
1068 my $digest = Digest::SHA->new('sha1');
1069 foreach my $rule (@$rules) { # order is important
1070 $digest->add($rule);
1071 }
1072 return $digest->b64digest;
1073}
1074
3f95d14a
DM
1075sub ipset_chain_digest {
1076 my ($rules) = @_;
4bd0a9c4 1077
3f95d14a
DM
1078 my $digest = Digest::SHA->new('sha1');
1079 foreach my $rule (sort @$rules) { # note: sorted
1080 $digest->add($rule);
1081 }
1082 return $digest->b64digest;
1083}
1084
34cdedfa
AD
1085sub ipset_get_chains {
1086
1087 my $res = {};
1088 my $chains = {};
1089
1090 my $parser = sub {
1091 my $line = shift;
1092
1093 return if $line =~ m/^#/;
1094 return if $line =~ m/^\s*$/;
4b96e877 1095 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
81a0bf43
DM
1096 my $chain = $1;
1097 $line =~ s/\s+$//; # delete trailing white space
1098 push @{$chains->{$chain}}, $line;
34cdedfa
AD
1099 } else {
1100 # simply ignore the rest
1101 return;
1102 }
1103 };
1104
3f95d14a 1105 run_command("/usr/sbin/ipset save", outfunc => $parser);
34cdedfa 1106
3f95d14a
DM
1107 # compute digest for each chain
1108 foreach my $chain (keys %$chains) {
1109 $res->{$chain} = ipset_chain_digest($chains->{$chain});
34cdedfa
AD
1110 }
1111
1112 return $res;
1113}
1114
eba0fb64 1115sub ruleset_generate_cmdstr {
ba791b1f 1116 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
3a616aa0 1117
00bb4391 1118 return if defined($rule->{enable}) && !$rule->{enable};
11bac5c2 1119
e5076eee
DM
1120 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1121
1122 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
1123 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
e5076eee 1124
41524a58 1125 my @cmd = ();
3a616aa0 1126
eba0fb64
DM
1127 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1128 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1129
ba791b1f
AD
1130 my $source = $rule->{source};
1131 my $dest = $rule->{dest};
1132
cbb5d6f3
DM
1133 if ($source) {
1134 if ($source =~ m/^(\+)(\S+)$/) {
936af352 1135 die "no such ipset $2" if !$cluster_conf->{ipset}->{$2};
4b96e877 1136 push @cmd, "-m set --match-set PVEFW-$2 src";
ba791b1f 1137
ac8242cc 1138 } elsif ($source =~ m/\-/){
ba791b1f
AD
1139 push @cmd, "-m iprange --src-range $source";
1140
cbb5d6f3 1141 } else {
ba791b1f
AD
1142 push @cmd, "-s $source";
1143 }
1144 }
1145
cbb5d6f3
DM
1146 if ($dest) {
1147 if ($dest =~ m/^(\+)(\S+)$/) {
936af352 1148 die "no such ipset $2" if !$cluster_conf->{ipset}->{$2};
4b96e877 1149 push @cmd, "-m set --match-set PVEFW-$2 dst";
ba791b1f 1150
cbb5d6f3 1151 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
ba791b1f
AD
1152 push @cmd, "-m iprange --dst-range $dest";
1153
cbb5d6f3 1154 } else {
ba791b1f
AD
1155 push @cmd, "-s $dest";
1156 }
1157 }
4b586518 1158
181390b0 1159 if ($rule->{proto}) {
41524a58 1160 push @cmd, "-p $rule->{proto}";
e3a1d391 1161
181390b0 1162 my $multiport = 0;
e5076eee
DM
1163 $multiport++ if $nbdport > 1;
1164 $multiport++ if $nbsport > 1;
e3a1d391 1165
41524a58 1166 push @cmd, "--match multiport" if $multiport;
4b586518 1167
cbb5d6f3 1168 die "multiport: option '--sports' cannot be used together with '--dports'\n"
181390b0
DM
1169 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1170
1171 if ($rule->{dport}) {
1172 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
1173 # Note: we use dport to store --icmp-type
1174 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
41524a58 1175 push @cmd, "-m icmp --icmp-type $rule->{dport}";
181390b0 1176 } else {
e5076eee 1177 if ($nbdport > 1) {
181390b0 1178 if ($multiport == 2) {
41524a58 1179 push @cmd, "--ports $rule->{dport}";
181390b0 1180 } else {
41524a58 1181 push @cmd, "--dports $rule->{dport}";
181390b0 1182 }
e3a1d391 1183 } else {
41524a58 1184 push @cmd, "--dport $rule->{dport}";
e3a1d391 1185 }
4b586518
DM
1186 }
1187 }
4b586518 1188
181390b0 1189 if ($rule->{sport}) {
e5076eee 1190 if ($nbsport > 1) {
41524a58 1191 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
181390b0 1192 } else {
41524a58 1193 push @cmd, "--sport $rule->{sport}";
181390b0 1194 }
4b586518 1195 }
181390b0
DM
1196 } elsif ($rule->{dport} || $rule->{sport}) {
1197 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport};
1198 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport};
4b586518
DM
1199 }
1200
41524a58 1201 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
4e6112f9
DM
1202
1203 if (my $action = $rule->{action}) {
cbb5d6f3 1204 $action = $actions->{$action} if defined($actions->{$action});
4e6112f9 1205 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
41524a58 1206 push @cmd, $goto ? "-g $action" : "-j $action";
181390b0 1207 }
3a616aa0 1208
eba0fb64
DM
1209 return scalar(@cmd) ? join(' ', @cmd) : undef;
1210}
1211
1212sub ruleset_generate_rule {
ba791b1f 1213 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
eba0fb64 1214
e5076eee
DM
1215 my $rules;
1216
1217 if ($rule->{macro}) {
1218 $rules = &$apply_macro($rule->{macro}, $rule);
1219 } else {
1220 $rules = [ $rule ];
1221 }
1222
cbb5d6f3 1223 foreach my $tmp (@$rules) {
ba791b1f 1224 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
e5076eee
DM
1225 ruleset_addrule($ruleset, $chain, $cmdstr);
1226 }
41524a58 1227 }
3fa83edf 1228}
0f168d7b 1229
eba0fb64
DM
1230sub ruleset_generate_rule_insert {
1231 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1232
e5076eee
DM
1233 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1234
eba0fb64
DM
1235 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
1236 ruleset_insertrule($ruleset, $chain, $cmdstr);
1237 }
1238}
3fa83edf
DM
1239
1240sub ruleset_create_chain {
1241 my ($ruleset, $chain) = @_;
3a616aa0 1242
d050c724 1243 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
782c4cde 1244 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
d050c724 1245
3fa83edf
DM
1246 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1247
1248 $ruleset->{$chain} = [];
3a616aa0
AD
1249}
1250
3fa83edf
DM
1251sub ruleset_chain_exist {
1252 my ($ruleset, $chain) = @_;
3a616aa0 1253
3fa83edf
DM
1254 return $ruleset->{$chain} ? 1 : undef;
1255}
3a616aa0 1256
3fa83edf
DM
1257sub ruleset_addrule {
1258 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1259
3fa83edf 1260 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1261
3fa83edf
DM
1262 push @{$ruleset->{$chain}}, "-A $chain $rule";
1263}
3a616aa0 1264
3fa83edf
DM
1265sub ruleset_insertrule {
1266 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1267
3fa83edf 1268 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1269
3fa83edf
DM
1270 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1271}
3a616aa0 1272
782c4cde
DM
1273sub get_log_rule_base {
1274 my ($chain, $vmid, $msg, $loglevel) = @_;
cbb5d6f3 1275
782c4cde
DM
1276 die "internal error - no log level" if !defined($loglevel);
1277
1278 $vmid = 0 if !defined($vmid);
1279
cbb5d6f3 1280 # Note: we use special format for prefix to pass further
782c4cde
DM
1281 # info to log daemon (VMID, LOGVELEL and CHAIN)
1282
1283 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1284}
1285
1286sub ruleset_addlog {
1287 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1288
1289 return if !defined($loglevel);
1290
1291 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1292
1293 $logrule = "$rule $logrule" if defined($rule);
1294
1295 ruleset_addrule($ruleset, $chain, $logrule)
1296}
1297
3fa83edf 1298sub generate_bridge_chains {
530c005e
DM
1299 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
1300
1301 my $options = $hostfw_conf->{options} || {};
1302
1303 die "error: detected direct route to bridge '$bridge'\n"
1304 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
2f3d8d76 1305
5927497d
DM
1306 if (!ruleset_chain_exist($ruleset, "$bridge-FW")) {
1307 ruleset_create_chain($ruleset, "$bridge-FW");
3cc81077
DM
1308 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o $bridge -m physdev --physdev-is-out -j $bridge-FW");
1309 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i $bridge -m physdev --physdev-is-in -j $bridge-FW");
3fa83edf 1310 }
3a616aa0 1311
3fa83edf
DM
1312 if (!ruleset_chain_exist($ruleset, "$bridge-OUT")) {
1313 ruleset_create_chain($ruleset, "$bridge-OUT");
3cc81077
DM
1314 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-in -j $bridge-OUT");
1315 ruleset_insertrule($ruleset, "PVEFW-INPUT", "-i $bridge -m physdev --physdev-is-in -j $bridge-OUT");
9fcad984
AD
1316 }
1317
1318 if (!ruleset_chain_exist($ruleset, "$bridge-IN")) {
1319 ruleset_create_chain($ruleset, "$bridge-IN");
3cc81077 1320 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j $bridge-IN");
fdb0bf20 1321 ruleset_addrule($ruleset, "$bridge-FW", "-m mark --mark 1 -j ACCEPT");
7323008d 1322 # accept traffic to unmanaged bridge ports
3cc81077 1323 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j ACCEPT ");
3fa83edf
DM
1324 }
1325}
3a616aa0 1326
ead850e8 1327sub ruleset_add_chain_policy {
782c4cde 1328 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
ead850e8
DM
1329
1330 if ($policy eq 'ACCEPT') {
1331
1332 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1333 { ACCEPT => $accept_action});
1334
1335 } elsif ($policy eq 'DROP') {
1336
1337 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1338
782c4cde 1339 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1340
1341 ruleset_addrule($ruleset, $chain, "-j DROP");
1342 } elsif ($policy eq 'REJECT') {
1343 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1344
782c4cde 1345 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1346
1347 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1348 } else {
1349 # should not happen
1350 die "internal error: unknown policy '$policy'";
1351 }
1352}
1353
9e15114a
DM
1354sub ruleset_create_vm_chain {
1355 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
3a616aa0 1356
9e15114a 1357 ruleset_create_chain($ruleset, $chain);
b47ecc88 1358 my $accept = generate_nfqueue($options);
3a616aa0 1359
bee633ab 1360 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
9e15114a 1361 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
bee633ab
DM
1362 }
1363
ce15d90b 1364 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
76a2d1e7 1365 if ($direction eq 'OUT') {
cbb5d6f3 1366 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
0f168d7b 1367 proto => 'udp', sport => 68, dport => 67 });
76a2d1e7 1368 } else {
cbb5d6f3 1369 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
0f168d7b 1370 proto => 'udp', sport => 67, dport => 68 });
76a2d1e7 1371 }
ce15d90b
DM
1372 }
1373
bee633ab 1374 if ($options->{tcpflags}) {
9e15114a 1375 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
bee633ab
DM
1376 }
1377
9e15114a 1378 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
cbb5d6f3 1379 if ($direction eq 'OUT') {
b47ecc88 1380 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -g PVEFW-SET-ACCEPT-MARK");
cbb5d6f3 1381 } else {
b47ecc88
AD
1382 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1383 }
cbb5d6f3 1384
b21aca2c
DM
1385 if ($direction eq 'OUT') {
1386 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
9e15114a 1387 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
b21aca2c 1388 }
9e15114a 1389 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
c29f55c9 1390 }
9e15114a
DM
1391}
1392
1393sub ruleset_generate_vm_rules {
fca39c2c 1394 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
9e15114a
DM
1395
1396 my $lc_direction = lc($direction);
c29f55c9 1397
92e976b3
DM
1398 foreach my $rule (@$rules) {
1399 next if $rule->{iface} && $rule->{iface} ne $netid;
ea9e5116 1400 next if !$rule->{enable};
92e976b3 1401 if ($rule->{type} eq 'group') {
cbb5d6f3 1402 my $group_chain = "GROUP-$rule->{action}-$direction";
92e976b3 1403 if(!ruleset_chain_exist($ruleset, $group_chain)){
fca39c2c 1404 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
92e976b3 1405 }
9e15114a 1406 ruleset_addrule($ruleset, $chain, "-j $group_chain");
b47ecc88
AD
1407 if ($direction eq 'OUT'){
1408 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j RETURN");
1409 }else{
1410 my $accept = generate_nfqueue($options);
1411 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $accept");
1412 }
1413
92e976b3
DM
1414 } else {
1415 next if $rule->{type} ne $lc_direction;
1416 if ($direction eq 'OUT') {
cbb5d6f3 1417 ruleset_generate_rule($ruleset, $chain, $rule,
ba791b1f 1418 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
4e6112f9 1419 } else {
b47ecc88 1420 my $accept = generate_nfqueue($options);
ba791b1f 1421 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject" }, undef, $cluster_conf);
3a616aa0 1422 }
4e6112f9 1423 }
3a616aa0 1424 }
9e15114a
DM
1425}
1426
b47ecc88
AD
1427sub generate_nfqueue {
1428 my ($options) = @_;
1429
1430 my $action = "";
1431 if($options->{ips}){
1432 $action = "NFQUEUE";
1433 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1434 if(defined($3) && defined($1)) {
1435 $action .= " --queue-balance $1:$3";
1436 }elsif (defined($1)) {
1437 $action .= " --queue-num $1";
1438 }
1439 }
1440 $action .= " --queue-bypass";
1441 }else{
1442 $action = "ACCEPT";
1443 }
1444
1445 return $action;
1446}
1447
da6fc60b
AD
1448sub ruleset_generate_vm_ipsrules {
1449 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1450
1451 if ($options->{ips} && $direction eq 'IN') {
1452 my $nfqueue = generate_nfqueue($options);
1453
1454 if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
1455 ruleset_create_chain($ruleset, "PVEFW-IPS");
1456 }
1457
1458 if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
1459 ruleset_create_chain($ruleset, "$bridge-IPS");
1460 ruleset_insertrule($ruleset, "PVEFW-IPS", "-o $bridge -m physdev --physdev-is-out -j $bridge-IPS");
1461 }
1462
1463 ruleset_addrule($ruleset, "$bridge-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
1464 }
1465}
1466
9e15114a 1467sub generate_venet_rules_direction {
fca39c2c 1468 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
9e15114a 1469
5176619e 1470 parse_address_list($ip); # make sure we have a valid $ip list
9e15114a
DM
1471
1472 my $lc_direction = lc($direction);
1473
1474 my $rules = $vmfw_conf->{rules};
1475
1476 my $options = $vmfw_conf->{options};
1477 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1478
1479 my $chain = "venet0-$vmid-$direction";
1480
1481 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1482
fca39c2c 1483 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
9e15114a
DM
1484
1485 # implement policy
1486 my $policy;
1487
1488 if ($direction eq 'OUT') {
1489 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1490 } else {
1491 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1492 }
1493
b47ecc88
AD
1494 my $accept = generate_nfqueue($options);
1495 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1496 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
9e15114a 1497
38485daa 1498 # plug into FORWARD, INPUT and OUTPUT chain
eba0fb64
DM
1499 if ($direction eq 'OUT') {
1500 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD", {
1501 action => $chain,
1502 source => $ip,
1503 iface_in => 'venet0'});
38485daa
DM
1504
1505 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT", {
1506 action => $chain,
1507 source => $ip,
1508 iface_in => 'venet0'});
eba0fb64
DM
1509 } else {
1510 ruleset_generate_rule($ruleset, "PVEFW-FORWARD", {
1511 action => $chain,
1512 dest => $ip,
1513 iface_out => 'venet0'});
38485daa
DM
1514
1515 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT", {
1516 action => $chain,
1517 dest => $ip,
1518 iface_out => 'venet0'});
eba0fb64 1519 }
9e15114a
DM
1520}
1521
1522sub generate_tap_rules_direction {
fca39c2c 1523 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
9e15114a
DM
1524
1525 my $lc_direction = lc($direction);
1526
1527 my $rules = $vmfw_conf->{rules};
1528
1529 my $options = $vmfw_conf->{options};
1530 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1531
1532 my $tapchain = "$iface-$direction";
1533
1534 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1535
fca39c2c 1536 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
3a616aa0 1537
da6fc60b
AD
1538 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1539
ccae0b50
DM
1540 # implement policy
1541 my $policy;
1542
1543 if ($direction eq 'OUT') {
72f63fde 1544 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
ccae0b50 1545 } else {
72f63fde 1546 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
ccae0b50
DM
1547 }
1548
b47ecc88
AD
1549 my $accept = generate_nfqueue($options);
1550 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
782c4cde 1551 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
3a616aa0 1552
3fa83edf 1553 # plug the tap chain to bridge chain
3cc81077
DM
1554 if ($direction eq 'IN') {
1555 ruleset_insertrule($ruleset, "$bridge-IN",
1556 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
1557 } else {
1558 ruleset_insertrule($ruleset, "$bridge-OUT",
1559 "-m physdev --physdev-in $iface -j $tapchain");
1560 }
3a616aa0
AD
1561}
1562
d18c1e2b 1563sub enable_host_firewall {
fca39c2c 1564 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
0bd5f137 1565
51bae274 1566 # fixme: allow security groups
0bd5f137 1567
92e976b3
DM
1568 my $options = $hostfw_conf->{options};
1569 my $rules = $hostfw_conf->{rules};
178a63be 1570
3fa83edf 1571 # host inbound firewall
dec84fcd
DM
1572 my $chain = "PVEFW-HOST-IN";
1573 ruleset_create_chain($ruleset, $chain);
0bd5f137 1574
178a63be
DM
1575 my $loglevel = get_option_log_level($options, "log_level_in");
1576
4ac863a6
DM
1577 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1578 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1579 }
1580
fb424a00
DM
1581 if ($options->{tcpflags}) {
1582 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1583 }
1584
7fab95bc
DM
1585 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1586 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
dec84fcd
DM
1587 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
1588 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
97156ecc 1589 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
dec84fcd 1590 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
0bd5f137 1591
23e888f8
DM
1592 # we use RETURN because we need to check also tap rules
1593 my $accept_action = 'RETURN';
1594
92e976b3
DM
1595 foreach my $rule (@$rules) {
1596 next if $rule->{type} ne 'in';
ba791b1f 1597 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
0bd5f137
AD
1598 }
1599
23e888f8 1600 # implement input policy
72f63fde 1601 my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
782c4cde 1602 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
0bd5f137 1603
3fa83edf 1604 # host outbound firewall
aadd745e 1605 $chain = "PVEFW-HOST-OUT";
dec84fcd
DM
1606 ruleset_create_chain($ruleset, $chain);
1607
178a63be
DM
1608 $loglevel = get_option_log_level($options, "log_level_out");
1609
7fab95bc
DM
1610 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1611 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
dec84fcd
DM
1612 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
1613 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
97156ecc 1614 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
dec84fcd 1615 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
0bd5f137 1616
23e888f8
DM
1617 # we use RETURN because we may want to check other thigs later
1618 $accept_action = 'RETURN';
1619
92e976b3
DM
1620 foreach my $rule (@$rules) {
1621 next if $rule->{type} ne 'out';
ba791b1f 1622 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
0bd5f137
AD
1623 }
1624
23e888f8 1625 # implement output policy
72f63fde 1626 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
782c4cde 1627 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
6158271d 1628
dec84fcd
DM
1629 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1630 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
9d31b418
AD
1631}
1632
1633sub generate_group_rules {
fca39c2c 1634 my ($ruleset, $cluster_conf, $group) = @_;
c6f5cc88 1635 die "no such security group '$group'\n" if !$cluster_conf->{groups}->{$group};
9d31b418 1636
c6f5cc88 1637 my $rules = $cluster_conf->{groups}->{$group};
6158271d 1638
3fa83edf 1639 my $chain = "GROUP-${group}-IN";
9d31b418 1640
3fa83edf 1641 ruleset_create_chain($ruleset, $chain);
b47ecc88 1642 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 1643
92e976b3
DM
1644 foreach my $rule (@$rules) {
1645 next if $rule->{type} ne 'in';
ba791b1f 1646 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418
AD
1647 }
1648
3fa83edf 1649 $chain = "GROUP-${group}-OUT";
9d31b418 1650
3fa83edf 1651 ruleset_create_chain($ruleset, $chain);
4e6112f9 1652 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 1653
92e976b3
DM
1654 foreach my $rule (@$rules) {
1655 next if $rule->{type} ne 'out';
1656 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1657 # check also other tap rules later
cbb5d6f3 1658 ruleset_generate_rule($ruleset, $chain, $rule,
ba791b1f 1659 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
9d31b418 1660 }
9d31b418
AD
1661}
1662
51bae274
DM
1663my $MAX_NETS = 32;
1664my $valid_netdev_names = {};
1665for (my $i = 0; $i < $MAX_NETS; $i++) {
1666 $valid_netdev_names->{"net$i"} = 1;
1667}
5e1267a5 1668
51bae274
DM
1669sub parse_fw_rule {
1670 my ($line, $need_iface, $allow_groups) = @_;
5e1267a5 1671
92e976b3 1672 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
51bae274 1673
11bac5c2 1674 # we can add single line comments to the end of the rule
30c1ae52 1675 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
11bac5c2
DM
1676
1677 # we can disable a rule when prefixed with '|'
ea9e5116
DM
1678 my $enable = 1;
1679
1680 $enable = 0 if $line =~ s/^\|//;
51bae274
DM
1681
1682 my @data = split(/\s+/, $line);
92e976b3 1683 my $expected_elements = $need_iface ? 8 : 7;
51bae274
DM
1684
1685 die "wrong number of rule elements\n" if scalar(@data) > $expected_elements;
1686
1687 if ($need_iface) {
92e976b3 1688 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
51bae274 1689 } else {
92e976b3 1690 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
51bae274
DM
1691 }
1692
92e976b3 1693 die "incomplete rule\n" if ! ($type && $action);
51bae274 1694
961b4928 1695 my $macro;
961b4928 1696
92e976b3
DM
1697 $type = lc($type);
1698
1699 if ($type eq 'in' || $type eq 'out') {
1700 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1701 # OK
1702 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
e5076eee
DM
1703 $action = $2;
1704 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1705 die "unknown macro '$1'\n" if !$preferred_name;
1706 $macro = $preferred_name;
92e976b3
DM
1707 } else {
1708 die "unknown action '$action'\n";
1709 }
1710 } elsif ($type eq 'group') {
1711 die "wrong number of rule elements\n" if scalar(@data) != 3;
1712 die "groups disabled\n" if !$allow_groups;
1713
cbb5d6f3 1714 die "invalid characters in group name\n" if $action !~ m/^[A-Za-z0-9_\-]+$/;
51bae274 1715 } else {
92e976b3 1716 die "unknown rule type '$type'\n";
51bae274
DM
1717 }
1718
1719 if ($need_iface) {
1720 $iface = undef if $iface && $iface eq '-';
51bae274
DM
1721 }
1722
1723 $proto = undef if $proto && $proto eq '-';
54cd19a8 1724 pve_fw_verify_protocol_spec($proto) if $proto;
51bae274
DM
1725
1726 $source = undef if $source && $source eq '-';
1727 $dest = undef if $dest && $dest eq '-';
1728
1729 $dport = undef if $dport && $dport eq '-';
1730 $sport = undef if $sport && $sport eq '-';
1731
e5076eee
DM
1732 parse_port_name_number_or_range($dport) if defined($dport);
1733 parse_port_name_number_or_range($sport) if defined($sport);
ba791b1f 1734
d72beb8e
DM
1735 parse_address_list($source) if $source;
1736 parse_address_list($dest) if $dest;
51bae274 1737
e5076eee 1738 return {
92e976b3 1739 type => $type,
ea9e5116 1740 enable => $enable,
11bac5c2 1741 comment => $comment,
51bae274 1742 action => $action,
e5076eee 1743 macro => $macro,
51bae274
DM
1744 iface => $iface,
1745 source => $source,
1746 dest => $dest,
51bae274
DM
1747 proto => $proto,
1748 dport => $dport,
1749 sport => $sport,
51bae274
DM
1750 };
1751}
1752
2d404ffc 1753sub parse_vmfw_option {
85c6eaed
DM
1754 my ($line) = @_;
1755
1756 my ($opt, $value);
1757
178a63be
DM
1758 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1759
b47ecc88 1760 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
9c6b6efd
DM
1761 $opt = lc($1);
1762 $value = int($2);
178a63be
DM
1763 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1764 $opt = lc($1);
1765 $value = $2 ? lc($3) : '';
72f63fde 1766 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
85c6eaed
DM
1767 $opt = lc($1);
1768 $value = uc($3);
b47ecc88
AD
1769 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1770 $opt = lc($1);
1771 $value = $2;
9c6b6efd 1772 } else {
85c6eaed
DM
1773 chomp $line;
1774 die "can't parse option '$line'\n"
1775 }
1776
1777 return ($opt, $value);
1778}
1779
2d404ffc
DM
1780sub parse_hostfw_option {
1781 my ($line) = @_;
1782
1783 my ($opt, $value);
1784
1785 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1786
cc10e5d7 1787 if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
2d404ffc
DM
1788 $opt = lc($1);
1789 $value = int($2);
178a63be 1790 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2d404ffc
DM
1791 $opt = lc($1);
1792 $value = $2 ? lc($3) : '';
72f63fde 1793 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2d404ffc
DM
1794 $opt = lc($1);
1795 $value = uc($3);
490cdead
DM
1796 } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
1797 $opt = lc($1);
1798 $value = int($2);
2d404ffc
DM
1799 } else {
1800 chomp $line;
1801 die "can't parse option '$line'\n"
1802 }
1803
1804 return ($opt, $value);
1805}
1806
c6f5cc88
DM
1807sub parse_clusterfw_option {
1808 my ($line) = @_;
1809
1810 my ($opt, $value);
1811
1812 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1813 $opt = lc($1);
1814 $value = int($2);
1815 } else {
1816 chomp $line;
1817 die "can't parse option '$line'\n"
1818 }
1819
1820 return ($opt, $value);
1821}
1822
51bae274
DM
1823sub parse_vm_fw_rules {
1824 my ($filename, $fh) = @_;
1825
92e976b3 1826 my $res = { rules => [], options => {}};
51bae274
DM
1827
1828 my $section;
1829
e7b35711
DM
1830 my $digest = Digest::SHA->new('sha1');
1831
5e1267a5 1832 while (defined(my $line = <$fh>)) {
e7b35711
DM
1833 $digest->add($line);
1834
5e1267a5
DM
1835 next if $line =~ m/^#/;
1836 next if $line =~ m/^\s*$/;
1837
961b4928
DM
1838 my $linenr = $fh->input_line_number();
1839 my $prefix = "$filename (line $linenr)";
1840
85c6eaed 1841 if ($line =~ m/^\[(\S+)\]\s*$/i) {
5e1267a5 1842 $section = lc($1);
85c6eaed 1843 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
5e1267a5
DM
1844 next;
1845 }
51bae274 1846 if (!$section) {
961b4928 1847 warn "$prefix: skip line - no section";
5e1267a5
DM
1848 next;
1849 }
1850
85c6eaed
DM
1851 next if !$res->{$section}; # skip undefined section
1852
1853 if ($section eq 'options') {
6158271d 1854 eval {
2d404ffc 1855 my ($opt, $value) = parse_vmfw_option($line);
85c6eaed
DM
1856 $res->{options}->{$opt} = $value;
1857 };
1858 warn "$prefix: $@" if $@;
1859 next;
1860 }
1861
e5076eee
DM
1862 my $rule;
1863 eval { $rule = parse_fw_rule($line, 1, 1); };
51bae274 1864 if (my $err = $@) {
961b4928 1865 warn "$prefix: $err";
5e1267a5
DM
1866 next;
1867 }
1868
e5076eee 1869 push @{$res->{$section}}, $rule;
51bae274
DM
1870 }
1871
e7b35711
DM
1872 $res->{digest} = $digest->b64digest;
1873
51bae274
DM
1874 return $res;
1875}
1876
1877sub parse_host_fw_rules {
1878 my ($filename, $fh) = @_;
1879
92e976b3 1880 my $res = { rules => [], options => {}};
51bae274
DM
1881
1882 my $section;
1883
8b27beb9
DM
1884 my $digest = Digest::SHA->new('sha1');
1885
51bae274 1886 while (defined(my $line = <$fh>)) {
8b27beb9
DM
1887 $digest->add($line);
1888
51bae274
DM
1889 next if $line =~ m/^#/;
1890 next if $line =~ m/^\s*$/;
1891
961b4928
DM
1892 my $linenr = $fh->input_line_number();
1893 my $prefix = "$filename (line $linenr)";
1894
2d404ffc 1895 if ($line =~ m/^\[(\S+)\]\s*$/i) {
51bae274 1896 $section = lc($1);
2d404ffc 1897 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
5e1267a5
DM
1898 next;
1899 }
51bae274 1900 if (!$section) {
961b4928 1901 warn "$prefix: skip line - no section";
5e1267a5
DM
1902 next;
1903 }
1904
2d404ffc
DM
1905 next if !$res->{$section}; # skip undefined section
1906
1907 if ($section eq 'options') {
1908 eval {
2d404ffc
DM
1909 my ($opt, $value) = parse_hostfw_option($line);
1910 $res->{options}->{$opt} = $value;
1911 };
1912 warn "$prefix: $@" if $@;
1913 next;
1914 }
1915
e5076eee
DM
1916 my $rule;
1917 eval { $rule = parse_fw_rule($line, 1, 1); };
ecbea048 1918 if (my $err = $@) {
961b4928 1919 warn "$prefix: $err";
ecbea048 1920 next;
ecbea048 1921 }
cbb5d6f3 1922
e5076eee 1923 push @{$res->{$section}}, $rule;
51bae274 1924 }
ecbea048 1925
cbb5d6f3 1926$res->{digest} = $digest->b64digest;
8b27beb9 1927
51bae274
DM
1928 return $res;
1929}
4cdbb3b7 1930
c6f5cc88 1931sub parse_cluster_fw_rules {
51bae274 1932 my ($filename, $fh) = @_;
5e1267a5 1933
51bae274
DM
1934 my $section;
1935 my $group;
1936
c4a2e5ae 1937 my $res = { rules => [], options => {}, groups => {}, ipset => {} };
6158271d 1938
d1c53b3e
DM
1939 my $digest = Digest::SHA->new('sha1');
1940
51bae274 1941 while (defined(my $line = <$fh>)) {
d1c53b3e
DM
1942 $digest->add($line);
1943
51bae274
DM
1944 next if $line =~ m/^#/;
1945 next if $line =~ m/^\s*$/;
1946
961b4928
DM
1947 my $linenr = $fh->input_line_number();
1948 my $prefix = "$filename (line $linenr)";
1949
c6f5cc88
DM
1950 if ($line =~ m/^\[options\]$/i) {
1951 $section = 'options';
1952 next;
1953 }
1954
92e976b3 1955 if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
c6f5cc88 1956 $section = 'groups';
92e976b3 1957 $group = lc($1);
51bae274
DM
1958 next;
1959 }
34cdedfa 1960
c6f5cc88
DM
1961 if ($line =~ m/^\[rules\]$/i) {
1962 $section = 'rules';
1963 next;
1964 }
cbb5d6f3 1965
936af352 1966 if ($line =~ m/^\[ipset\s+(\S+)\]\s*$/i) {
34cdedfa
AD
1967 $section = 'ipset';
1968 $group = lc($1);
34cdedfa
AD
1969 next;
1970 }
1971
c6f5cc88 1972 if (!$section) {
cbb5d6f3 1973 warn "$prefix: skip line - no section\n";
51bae274
DM
1974 next;
1975 }
1976
c6f5cc88
DM
1977 if ($section eq 'options') {
1978 eval {
1979 my ($opt, $value) = parse_clusterfw_option($line);
1980 $res->{options}->{$opt} = $value;
1981 };
1982 warn "$prefix: $@" if $@;
1983 } elsif ($section eq 'rules') {
1984 my $rule;
1985 eval { $rule = parse_fw_rule($line, 1, 1); };
1986 if (my $err = $@) {
1987 warn "$prefix: $err";
1988 next;
1989 }
1990 push @{$res->{$section}}, $rule;
1991 } elsif ($section eq 'groups') {
34cdedfa
AD
1992 my $rule;
1993 eval { $rule = parse_fw_rule($line, 0, 0); };
1994 if (my $err = $@) {
1995 warn "$prefix: $err";
1996 next;
1997 }
3f95d14a 1998 push @{$res->{$section}->{$group}}, $rule;
3f95d14a
DM
1999 } elsif ($section eq 'ipset') {
2000 chomp $line;
cbb5d6f3 2001 $line =~ m/^(\!)?\s*((\d+)\.(\d+)\.(\d+)\.(\d+)(\/(\d+))?)/;
2a052ee3 2002 my $nomatch = $1;
cbb5d6f3 2003 my $ip = $2;
2a052ee3
AD
2004
2005 if(!$ip){
cbb5d6f3 2006 warn "$prefix: $line is not an valid ip address\n";
34cdedfa
AD
2007 next;
2008 }
2a052ee3 2009 if (!Net::IP->new($ip)) {
cbb5d6f3 2010 warn "$prefix: $line is not an valid ip address\n";
2a052ee3
AD
2011 next;
2012 }
2a052ee3 2013
cbb5d6f3
DM
2014 if ($nomatch) {
2015 if ($feature_ipset_nomatch) {
2016 push @{$res->{$section}->{$group}}, "$ip nomatch";
2017 } else {
2018 warn "$prefix: ignore $line - nomatch not supported by kernel\n";
2019 }
2020 } else {
2021 push @{$res->{$section}->{$group}}, $ip;
2022 }
51bae274 2023 }
5e1267a5
DM
2024 }
2025
d1c53b3e 2026 $res->{digest} = $digest->b64digest;
5e1267a5
DM
2027 return $res;
2028}
2029
06320eb0
DM
2030sub run_locked {
2031 my ($code, @param) = @_;
2032
2033 my $timeout = 10;
2034
2035 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2036
2037 die $@ if $@;
2038
2039 return $res;
2040}
2041
5e1267a5
DM
2042sub read_local_vm_config {
2043
2044 my $openvz = {};
5e1267a5
DM
2045 my $qemu = {};
2046
c8301d63 2047 my $vmdata = { openvz => $openvz, qemu => $qemu };
5e1267a5 2048
c8301d63
DM
2049 my $vmlist = PVE::Cluster::get_vmlist();
2050 return $vmdata if !$vmlist || !$vmlist->{ids};
2051 my $ids = $vmlist->{ids};
2052
2053 foreach my $vmid (keys %$ids) {
2054 next if !$vmid; # skip VE0
2055 my $d = $ids->{$vmid};
2056 next if !$d->{node} || $d->{node} ne $nodename;
2057 next if !$d->{type};
2058 if ($d->{type} eq 'openvz') {
d9fee004
DM
2059 if ($have_pve_manager) {
2060 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2061 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2062 $openvz->{$vmid} = $conf;
2063 }
c8301d63
DM
2064 }
2065 } elsif ($d->{type} eq 'qemu') {
d9fee004
DM
2066 if ($have_qemu_server) {
2067 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2068 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2069 $qemu->{$vmid} = $conf;
2070 }
c8301d63 2071 }
5e1267a5
DM
2072 }
2073 }
d9fee004 2074
5e1267a5
DM
2075 return $vmdata;
2076};
2077
e7b35711
DM
2078sub load_vmfw_conf {
2079 my ($vmid) = @_;
2080
2081 my $vmfw_conf = {};
2082
2083 my $filename = "/etc/pve/firewall/$vmid.fw";
2084 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2085 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2086 }
2087
2088 return $vmfw_conf;
2089}
2090
464f933e
DM
2091my $format_rules = sub {
2092 my ($rules, $need_iface) = @_;
2093
2094 my $raw = '';
2095
2096 foreach my $rule (@$rules) {
2097 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2098 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2099 $raw .= uc($rule->{type});
7ca36671
DM
2100 if ($rule->{macro}) {
2101 $raw .= " $rule->{macro}($rule->{action})";
2102 } else {
2103 $raw .= " " . $rule->{action};
2104 }
464f933e
DM
2105 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
2106 $raw .= " " . ($rule->{source} || '-');
2107 $raw .= " " . ($rule->{dest} || '-');
2108 $raw .= " " . ($rule->{proto} || '-');
2109 $raw .= " " . ($rule->{dport} || '-');
2110 $raw .= " " . ($rule->{sport} || '-');
cbb5d6f3 2111 $raw .= " # " . encode('utf8', $rule->{comment})
464f933e
DM
2112 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2113 $raw .= "\n";
2114 } else {
2115 die "implement me '$rule->{type}'";
2116 }
2117 }
2118
2119 return $raw;
2120};
2121
2122my $format_options = sub {
68c90e21
DM
2123 my ($options) = @_;
2124
2125 my $raw = '';
464f933e
DM
2126
2127 $raw .= "[OPTIONS]\n\n";
2128 foreach my $opt (keys %$options) {
2129 $raw .= "$opt: $options->{$opt}\n";
2130 }
2131 $raw .= "\n";
68c90e21
DM
2132
2133 return $raw;
464f933e
DM
2134};
2135
2136sub save_vmfw_conf {
2137 my ($vmid, $vmfw_conf) = @_;
2138
2139 my $raw = '';
2140
2141 my $options = $vmfw_conf->{options};
68c90e21 2142 $raw .= &$format_options($options) if scalar(keys %$options);
cbb5d6f3 2143
464f933e
DM
2144 my $rules = $vmfw_conf->{rules};
2145 if (scalar(@$rules)) {
2146 $raw .= "[RULES]\n\n";
2147 $raw .= &$format_rules($rules, 1);
2148 $raw .= "\n";
2149 }
2150
2151 my $filename = "/etc/pve/firewall/$vmid.fw";
2152 PVE::Tools::file_set_contents($filename, $raw);
2153}
2154
6fc63ffd 2155sub read_vm_firewall_configs {
5e1267a5 2156 my ($vmdata) = @_;
6fc63ffd 2157 my $vmfw_configs = {};
c8301d63 2158
5e1267a5 2159 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
e7b35711
DM
2160 my $vmfw_conf = load_vmfw_conf($vmid);
2161 next if !$vmfw_conf->{options}; # skip if file does not exists
2162 $vmfw_configs->{$vmid} = $vmfw_conf;
5e1267a5
DM
2163 }
2164
6fc63ffd 2165 return $vmfw_configs;
5e1267a5
DM
2166}
2167
2d404ffc
DM
2168sub get_option_log_level {
2169 my ($options, $k) = @_;
2170
2171 my $v = $options->{$k};
178a63be 2172 $v = $default_log_level if !defined($v);
2d404ffc
DM
2173
2174 return undef if $v eq '' || $v eq 'nolog';
2175
2176 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2177
2178 return $v if ($v >= 0) && ($v <= 7);
2179
2180 warn "unknown log level ($k = '$v')\n";
2181
2182 return undef;
2183}
2184
d8f2505e 2185sub generate_std_chains {
2d404ffc 2186 my ($ruleset, $options) = @_;
cbb5d6f3 2187
2d404ffc
DM
2188 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2189
2190 # same as shorewall smurflog.
782c4cde
DM
2191 my $chain = 'PVEFW-smurflog';
2192
2193 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2194 push @{$pve_std_chains->{$chain}}, "-j DROP";
2d404ffc
DM
2195
2196 # same as shorewall logflags action.
2197 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
782c4cde
DM
2198 $chain = 'PVEFW-logflags';
2199 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2200 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2201 push @{$pve_std_chains->{$chain}}, "-j DROP";
d8f2505e
DM
2202
2203 foreach my $chain (keys %$pve_std_chains) {
2204 ruleset_create_chain($ruleset, $chain);
2205 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2206 if (ref($rule)) {
2207 ruleset_generate_rule($ruleset, $chain, $rule);
2208 } else {
2209 ruleset_addrule($ruleset, $chain, $rule);
2210 }
2211 }
2212 }
2213}
2214
34cdedfa 2215sub generate_ipset_chains {
dd7a13fd 2216 my ($ipset_ruleset, $fw_conf) = @_;
34cdedfa 2217
dd7a13fd 2218 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
4b96e877 2219 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
34cdedfa
AD
2220 }
2221}
2222
2223sub generate_ipset {
2224 my ($ipset_ruleset, $name, $options) = @_;
2225
dd7a13fd
DM
2226 my $hashsize = scalar(@$options);
2227 if ($hashsize <= 64) {
2a052ee3 2228 $hashsize = 64;
dd7a13fd 2229 } else {
2a052ee3
AD
2230 $hashsize = round_powerof2($hashsize);
2231 }
2232
dd7a13fd 2233 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
34cdedfa 2234
dd7a13fd 2235 foreach my $ip (@$options) {
34cdedfa
AD
2236 push @{$ipset_ruleset->{$name}}, "add $name $ip";
2237 }
2a052ee3
AD
2238}
2239
2240sub round_powerof2 {
dd7a13fd 2241 my ($int) = @_;
2a052ee3 2242
dd7a13fd
DM
2243 $int--;
2244 $int |= $int >> $_ foreach (1,2,4,8,16);
2245 return ++$int;
34cdedfa
AD
2246}
2247
6b9f68a2
DM
2248sub save_pvefw_status {
2249 my ($status) = @_;
2250
2251 die "unknown status '$status' - internal error"
2252 if $status !~ m/^(stopped|active)$/;
2253
2254 mkdir dirname($pve_fw_status_filename);
2255 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2256}
2257
2258sub read_pvefw_status {
2259
2260 my $status = 'unknown';
2261
2262 return 'stopped' if ! -f $pve_fw_status_filename;
2263
2264 eval {
2265 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2266 };
2267 warn $@ if $@;
2268
2269 return $status;
2270}
2271
530c005e
DM
2272# fixme: move to pve-common PVE::ProcFSTools
2273sub read_proc_net_route {
2274 my $filename = "/proc/net/route";
2275
2276 my $res = {};
2277
2278 my $fh = IO::File->new ($filename, "r");
2279 return $res if !$fh;
2280
2281 my $int_to_quad = sub {
2282 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2283 };
2284
2285 while (defined(my $line = <$fh>)) {
2286 next if $line =~/^Iface\s+Destination/; # skip head
2287 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2288 push @{$res->{$iface}}, {
2289 dest => &$int_to_quad(hex($dest)),
2290 gateway => &$int_to_quad(hex($gateway)),
2291 mask => &$int_to_quad(hex($mask)),
2292 metric => $metric,
2293 mtu => $mtu,
2294 };
2295 }
2296
2297 return $res;
2298}
2299
fca39c2c 2300sub load_clusterfw_conf {
530c005e 2301
fca39c2c
DM
2302 my $cluster_conf = {};
2303 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
c6f5cc88 2304 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
51bae274 2305 }
5e1267a5 2306
fca39c2c 2307 return $cluster_conf;
e5d76bde
DM
2308}
2309
fca39c2c
DM
2310sub save_clusterfw_conf {
2311 my ($cluster_conf) = @_;
9c7e0858
DM
2312
2313 my $raw = '';
9c7e0858 2314
c6f5cc88 2315 my $options = $cluster_conf->{options};
68c90e21 2316 $raw .= &$format_options($options) if scalar(keys %$options);
9c7e0858 2317
c6f5cc88
DM
2318 # fixme: save ipset
2319
2320 my $rules = $cluster_conf->{rules};
2321 if (scalar(@$rules)) {
2322 $raw .= "[RULES]\n\n";
63c91681 2323 $raw .= &$format_rules($rules, 1);
c6f5cc88
DM
2324 $raw .= "\n";
2325 }
2326
2327 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2328 my $rules = $cluster_conf->{groups}->{$group};
2329 $raw .= "[group $group]\n\n";
63c91681 2330 $raw .= &$format_rules($rules, 0);
9c7e0858
DM
2331 $raw .= "\n";
2332 }
2333
fca39c2c 2334 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
9c7e0858
DM
2335}
2336
8b27beb9
DM
2337sub load_hostfw_conf {
2338
2339 my $hostfw_conf = {};
63c91681
DM
2340 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2341 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
8b27beb9
DM
2342 }
2343 return $hostfw_conf;
2344}
2345
63c91681
DM
2346sub save_hostfw_conf {
2347 my ($hostfw_conf) = @_;
2348
2349 my $raw = '';
2350
2351 my $options = $hostfw_conf->{options};
68c90e21 2352 $raw .= &$format_options($options) if scalar(keys %$options);
cbb5d6f3 2353
63c91681
DM
2354 my $rules = $hostfw_conf->{rules};
2355 if (scalar(@$rules)) {
2356 $raw .= "[RULES]\n\n";
2357 $raw .= &$format_rules($rules, 1);
2358 $raw .= "\n";
2359 }
2360
2361 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2362}
2363
e5d76bde
DM
2364sub compile {
2365 my $vmdata = read_local_vm_config();
2366 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2367
2368 my $routing_table = read_proc_net_route();
2369
fca39c2c 2370 my $cluster_conf = load_clusterfw_conf();
e5d76bde 2371
34cdedfa 2372 my $ipset_ruleset = {};
fca39c2c 2373 generate_ipset_chains($ipset_ruleset, $cluster_conf);
34cdedfa 2374
3fa83edf
DM
2375 my $ruleset = {};
2376
dec84fcd
DM
2377 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2378 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
5b1df9a0 2379
fadb13dd 2380 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3fa83edf 2381
8b27beb9
DM
2382 my $hostfw_conf = load_hostfw_conf();
2383 my $hostfw_options = $hostfw_conf->{options} || {};
fadb13dd 2384
92e976b3 2385 generate_std_chains($ruleset, $hostfw_options);
fadb13dd 2386
6d2ab017 2387 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2d404ffc 2388
fca39c2c 2389 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
3fa83edf 2390
6158271d 2391 # generate firewall rules for QEMU VMs
3fa83edf
DM
2392 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2393 my $conf = $vmdata->{qemu}->{$vmid};
6fc63ffd 2394 my $vmfw_conf = $vmfw_configs->{$vmid};
fa9c4a6f
DM
2395 next if !$vmfw_conf;
2396 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
3fa83edf
DM
2397
2398 foreach my $netid (keys %$conf) {
2399 next if $netid !~ m/^net(\d+)$/;
2400 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2401 next if !$net;
2402 my $iface = "tap${vmid}i$1";
5e1267a5 2403
3fa83edf
DM
2404 my $bridge = $net->{bridge};
2405 next if !$bridge; # fixme: ?
2406
2407 $bridge .= "v$net->{tag}" if $net->{tag};
2408
530c005e 2409 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
3fa83edf 2410
c29f55c9 2411 my $macaddr = $net->{macaddr};
cbb5d6f3 2412 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
782c4cde 2413 $vmfw_conf, $vmid, $bridge, 'IN');
cbb5d6f3 2414 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
782c4cde 2415 $vmfw_conf, $vmid, $bridge, 'OUT');
3fa83edf
DM
2416 }
2417 }
c8301d63
DM
2418
2419 # generate firewall rules for OpenVZ containers
2420 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2421 my $conf = $vmdata->{openvz}->{$vmid};
2422
2423 my $vmfw_conf = $vmfw_configs->{$vmid};
2424 next if !$vmfw_conf;
2425 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2426
2427 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2428 my $ip = $conf->{ip_address}->{value};
fca39c2c
DM
2429 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN');
2430 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT');
c8301d63
DM
2431 }
2432
2433 if ($conf->{netif} && $conf->{netif}->{value}) {
2434 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
c8301d63
DM
2435 foreach my $netid (keys %$netif) {
2436 my $d = $netif->{$netid};
2437 my $bridge = $d->{bridge};
2438 if (!$bridge) {
2439 warn "no bridge device for CT $vmid iface '$netid'\n";
2440 next; # fixme?
2441 }
cbb5d6f3 2442
530c005e
DM
2443 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2444
12d0f130 2445 my $macaddr = $d->{mac};
c8301d63 2446 my $iface = $d->{host_ifname};
cbb5d6f3 2447 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
782c4cde 2448 $vmfw_conf, $vmid, $bridge, 'IN');
cbb5d6f3 2449 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
782c4cde 2450 $vmfw_conf, $vmid, $bridge, 'OUT');
c8301d63
DM
2451 }
2452 }
2453 }
c0413e35 2454
cc10e5d7 2455 if($hostfw_options->{optimize}){
da6fc60b 2456
e9d9a73e 2457 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
da6fc60b 2458 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
cc10e5d7
AD
2459 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2460 }
2461
eba0fb64
DM
2462 # fixme: what log level should we use here?
2463 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2464
c98c037d
DM
2465 # fixme: should we really block inter-bridge traffic?
2466
2467 # always allow traffic from containers?
2468 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2469
eba0fb64 2470 # disable interbridge routing
cbb5d6f3 2471 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
eba0fb64 2472 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
cbb5d6f3
DM
2473 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2474 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2475 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
eba0fb64
DM
2476 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2477
34cdedfa 2478 return wantarray ? ($ruleset, $hostfw_conf, $ipset_ruleset) : $ruleset;
3fa83edf
DM
2479}
2480
2481sub get_ruleset_status {
4bd0a9c4 2482 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3fa83edf
DM
2483
2484 my $statushash = {};
2485
2486 foreach my $chain (sort keys %$ruleset) {
4bd0a9c4 2487 my $sig = &$digest_fn($ruleset->{$chain});
9bf7d929 2488
3fa83edf
DM
2489 $statushash->{$chain}->{sig} = $sig;
2490
2491 my $oldsig = $active_chains->{$chain};
2492 if (!defined($oldsig)) {
2493 $statushash->{$chain}->{action} = 'create';
2494 } else {
2495 if ($oldsig eq $sig) {
2496 $statushash->{$chain}->{action} = 'exists';
2497 } else {
2498 $statushash->{$chain}->{action} = 'update';
2499 }
2500 }
2501 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2502 foreach my $cmd (@{$ruleset->{$chain}}) {
2503 print "\t$cmd\n" if $verbose;
2504 }
2505 }
2506
2507 foreach my $chain (sort keys %$active_chains) {
2508 if (!defined($ruleset->{$chain})) {
2509 my $sig = $active_chains->{$chain};
2510 $statushash->{$chain}->{action} = 'delete';
2511 $statushash->{$chain}->{sig} = $sig;
2512 print "delete $chain ($sig)\n" if $verbose;
2513 }
6158271d 2514 }
2a052ee3 2515
3fa83edf
DM
2516 return $statushash;
2517}
2518
3fa83edf
DM
2519sub print_sig_rule {
2520 my ($chain, $sig) = @_;
2521
09d5f68e
DM
2522 # We just use this to store a SHA1 checksum used to detect changes
2523 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
b6360c3f
DM
2524}
2525
df7cb349 2526sub get_ruleset_cmdlist {
a84f4d96 2527 my ($ruleset, $verbose) = @_;
3fa83edf 2528
3fa83edf 2529 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
cbb5d6f3 2530
4bd0a9c4
DM
2531 my ($active_chains, $hooks) = iptables_get_chains();
2532 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3fa83edf
DM
2533
2534 # create missing chains first
2535 foreach my $chain (sort keys %$ruleset) {
2536 my $stat = $statushash->{$chain};
2537 die "internal error" if !$stat;
2538 next if $stat->{action} ne 'create';
886aba9c 2539
3fa83edf
DM
2540 $cmdlist .= ":$chain - [0:0]\n";
2541 }
2542
4bd0a9c4
DM
2543 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2544 if (!$hooks->{$h}) {
2545 $cmdlist .= "-A $h -j PVEFW-$h\n";
2546 }
3fa83edf
DM
2547 }
2548
2549 foreach my $chain (sort keys %$ruleset) {
2550 my $stat = $statushash->{$chain};
2551 die "internal error" if !$stat;
2552
2553 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
2554 $cmdlist .= "-F $chain\n";
2555 foreach my $cmd (@{$ruleset->{$chain}}) {
2556 $cmdlist .= "$cmd\n";
2557 }
2558 $cmdlist .= print_sig_rule($chain, $stat->{sig});
2559 } elsif ($stat->{action} eq 'delete') {
f5d28682 2560 die "internal error"; # this should not happen
3fa83edf
DM
2561 } elsif ($stat->{action} eq 'exists') {
2562 # do nothing
2563 } else {
2564 die "internal error - unknown status '$stat->{action}'";
2565 }
2566 }
2567
f5d28682
DM
2568 foreach my $chain (keys %$statushash) {
2569 next if $statushash->{$chain}->{action} ne 'delete';
2570 $cmdlist .= "-F $chain\n";
2571 }
2572 foreach my $chain (keys %$statushash) {
2573 next if $statushash->{$chain}->{action} ne 'delete';
fadb13dd
DM
2574 next if $chain eq 'PVEFW-INPUT';
2575 next if $chain eq 'PVEFW-OUTPUT';
2576 next if $chain eq 'PVEFW-FORWARD';
f5d28682
DM
2577 $cmdlist .= "-X $chain\n";
2578 }
2579
3f95d14a 2580 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
4bd0a9c4 2581
3fa83edf
DM
2582 $cmdlist .= "COMMIT\n";
2583
3f95d14a 2584 return wantarray ? ($cmdlist, $changes) : $cmdlist;
6b9f68a2
DM
2585}
2586
34cdedfa 2587sub get_ipset_cmdlist {
dd7a13fd 2588 my ($ruleset, $verbose) = @_;
34cdedfa
AD
2589
2590 my $cmdlist = "";
2591
dd7a13fd
DM
2592 my $delete_cmdlist = "";
2593
4bd0a9c4
DM
2594 my $active_chains = ipset_get_chains();
2595 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
34cdedfa 2596
dd7a13fd
DM
2597 foreach my $chain (sort keys %$ruleset) {
2598 my $stat = $statushash->{$chain};
2599 die "internal error" if !$stat;
2a052ee3 2600
dd7a13fd
DM
2601 if ($stat->{action} eq 'create') {
2602 foreach my $cmd (@{$ruleset->{$chain}}) {
34cdedfa
AD
2603 $cmdlist .= "$cmd\n";
2604 }
dd7a13fd 2605 }
34cdedfa 2606
dd7a13fd
DM
2607 if ($stat->{action} eq 'update') {
2608 my $chain_swap = $chain."_swap";
cbb5d6f3 2609
dd7a13fd
DM
2610 foreach my $cmd (@{$ruleset->{$chain}}) {
2611 $cmd =~ s/$chain/$chain_swap/;
2612 $cmdlist .= "$cmd\n";
34cdedfa 2613 }
dd7a13fd
DM
2614 $cmdlist .= "swap $chain_swap $chain\n";
2615 $cmdlist .= "flush $chain_swap\n";
2616 $cmdlist .= "destroy $chain_swap\n";
2a052ee3 2617 }
34cdedfa 2618
dd7a13fd 2619 }
3f95d14a 2620
dd7a13fd
DM
2621 foreach my $chain (keys %$statushash) {
2622 next if $statushash->{$chain}->{action} ne 'delete';
2a052ee3 2623
dd7a13fd
DM
2624 $delete_cmdlist .= "flush $chain\n";
2625 $delete_cmdlist .= "destroy $chain\n";
34cdedfa
AD
2626 }
2627
dd7a13fd 2628 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
cbb5d6f3 2629
dd7a13fd 2630 return ($cmdlist, $delete_cmdlist, $changes);
34cdedfa
AD
2631}
2632
6b9f68a2 2633sub apply_ruleset {
34cdedfa 2634 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
6b9f68a2
DM
2635
2636 enable_bridge_firewall();
2637
edb75ba9
DM
2638 update_nf_conntrack_max($hostfw_conf);
2639
cbb5d6f3 2640 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
81a0bf43 2641 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
6b9f68a2 2642
81a0bf43 2643 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
2a052ee3 2644
81a0bf43
DM
2645 if ($verbose) {
2646 if ($ipset_changes) {
2647 print "ipset changes:\n";
2648 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2649 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2650 }
3f95d14a 2651
81a0bf43
DM
2652 if ($changes) {
2653 print "iptables changes:\n";
2654 print $cmdlist;
2655 }
2656 }
3fa83edf 2657
2a052ee3 2658 ipset_restore_cmdlist($ipset_create_cmdlist);
34cdedfa 2659
3fa83edf
DM
2660 iptables_restore_cmdlist($cmdlist);
2661
dd7a13fd 2662 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2a052ee3 2663
6158271d 2664 # test: re-read status and check if everything is up to date
4bd0a9c4 2665 my $active_chains = iptables_get_chains();
81a0bf43 2666 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3fa83edf
DM
2667
2668 my $errors;
2669 foreach my $chain (sort keys %$ruleset) {
2670 my $stat = $statushash->{$chain};
2671 if ($stat->{action} ne 'exists') {
2672 warn "unable to update chain '$chain'\n";
2673 $errors = 1;
2674 }
2675 }
b6360c3f 2676
3fa83edf 2677 die "unable to apply firewall changes\n" if $errors;
b6360c3f
DM
2678}
2679
490cdead
DM
2680sub update_nf_conntrack_max {
2681 my ($hostfw_conf) = @_;
2682
2683 my $max = 65536; # reasonable default
2684
2685 my $options = $hostfw_conf->{options} || {};
2686
2687 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
2688 $max = $options->{nf_conntrack_max};
2689 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2690 }
2691
2692 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2693 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2694
2695 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
2696
2697 if ($current != $max) {
2698 my $hashsize = int($max/4);
2699 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
2700 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
2701 }
2702}
2703
c4a2e5ae
DM
2704sub remove_pvefw_chains {
2705
2706 my ($chash, $hooks) = iptables_get_chains();
2707 my $cmdlist = "*filter\n";
2708
2709 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2710 if ($hooks->{$h}) {
2711 $cmdlist .= "-D $h -j PVEFW-$h\n";
2712 }
2713 }
cbb5d6f3 2714
c4a2e5ae
DM
2715 foreach my $chain (keys %$chash) {
2716 $cmdlist .= "-F $chain\n";
2717 }
2718
2719 foreach my $chain (keys %$chash) {
2720 $cmdlist .= "-X $chain\n";
2721 }
2722 $cmdlist .= "COMMIT\n";
2723
2724 iptables_restore_cmdlist($cmdlist);
2725}
2726
6b9f68a2
DM
2727sub update {
2728 my ($start, $verbose) = @_;
2729
2730 my $code = sub {
2731 my $status = read_pvefw_status();
2732
3f95d14a 2733 my ($ruleset, $hostfw_conf, $ipset_ruleset) = compile();
490cdead 2734
6b9f68a2
DM
2735 if ($start || $status eq 'active') {
2736
2737 save_pvefw_status('active') if ($status ne 'active');
2738
34cdedfa 2739 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
6b9f68a2
DM
2740 } else {
2741 print "Firewall not active (status = $status)\n" if $verbose;
2742 }
2743 };
2744
2745 run_locked($code);
2746}
2747
2748
b6360c3f 27491;