]> git.proxmox.com Git - pve-firewall.git/blame - src/pve-firewall
add better inline documentation
[pve-firewall.git] / src / pve-firewall
CommitLineData
e2beb7aa
DM
1#!/usr/bin/perl
2
3use strict;
4use warnings;
5use PVE::SafeSyslog;
a3d58ffc
DM
6use PVE::Daemon;
7
e2beb7aa
DM
8use Time::HiRes qw (gettimeofday);
9use PVE::Tools qw(dir_glob_foreach file_read_firstline);
a3d58ffc 10use PVE::ProcFSTools;
e2beb7aa
DM
11use PVE::INotify;
12use PVE::Cluster qw(cfs_read_file);
13use PVE::RPCEnvironment;
14use PVE::CLIHandler;
15use PVE::Firewall;
814de832
DM
16use PVE::FirewallSimulator;
17use Data::Dumper;
e2beb7aa 18
a3d58ffc 19use base qw(PVE::Daemon);
e2beb7aa 20
cf10b505
DM
21$SIG{'__WARN__'} = sub {
22 my $err = $@;
23 my $t = $_[0];
24 chomp $t;
25 print STDERR "$t\n";
26 syslog('warning', "%s", $t);
27 $@ = $err;
28};
29
a3d58ffc 30my $cmdline = [$0, @ARGV];
e2beb7aa 31
a3d58ffc 32my %daemon_options = (restart_on_error => 5, stop_wait_time => 5);
e2beb7aa 33
8e471378 34my $daemon = __PACKAGE__->new('pve-firewall', $cmdline, %daemon_options);
e2beb7aa
DM
35
36my $rpcenv = PVE::RPCEnvironment->init('cli');
37
38$rpcenv->init_request();
39$rpcenv->set_language($ENV{LANG});
40$rpcenv->set_user('root@pam');
41
814de832
DM
42my $nodename = PVE::INotify::nodename();
43
a3d58ffc 44sub init {
e2beb7aa 45
a3d58ffc
DM
46 PVE::Cluster::cfs_update();
47
48 PVE::Firewall::init();
e2beb7aa
DM
49}
50
51my $restart_request = 0;
52my $next_update = 0;
53
54my $cycle = 0;
55my $updatetime = 10;
56
57my $initial_memory_usage;
58
a3d58ffc
DM
59sub shutdown {
60 my ($self) = @_;
e2beb7aa 61
a3d58ffc 62 syslog('info' , "server closing");
e2beb7aa 63
a3d58ffc
DM
64 # wait for children
65 1 while (waitpid(-1, POSIX::WNOHANG()) > 0);
e2beb7aa 66
a3d58ffc 67 syslog('info' , "clear firewall rules");
e2beb7aa 68
a3d58ffc
DM
69 eval { PVE::Firewall::remove_pvefw_chains(); };
70 warn $@ if $@;
e2beb7aa 71
a3d58ffc
DM
72 $self->exit_daemon(0);
73}
e2beb7aa 74
a3d58ffc
DM
75sub hup {
76 my ($self) = @_;
e2beb7aa 77
a3d58ffc
DM
78 $restart_request = 1;
79}
e2beb7aa 80
a3d58ffc
DM
81sub run {
82 my ($self) = @_;
e2beb7aa 83
a3d58ffc 84 local $SIG{'__WARN__'} = 'IGNORE'; # do not fill up logs
e2beb7aa 85
a3d58ffc 86 for (;;) { # forever
e2beb7aa 87
a3d58ffc 88 $next_update = time() + $updatetime;
e2beb7aa 89
a3d58ffc
DM
90 my ($ccsec, $cusec) = gettimeofday ();
91 eval {
92 PVE::Cluster::cfs_update();
93 PVE::Firewall::update();
e2beb7aa 94 };
e2beb7aa 95 my $err = $@;
a3d58ffc 96
e2beb7aa 97 if ($err) {
a3d58ffc 98 syslog('err', "status update error: $err");
e2beb7aa 99 }
e2beb7aa 100
a3d58ffc
DM
101 my ($ccsec_end, $cusec_end) = gettimeofday ();
102 my $cptime = ($ccsec_end-$ccsec) + ($cusec_end - $cusec)/1000000;
e2beb7aa 103
a3d58ffc
DM
104 syslog('info', sprintf("firewall update time (%.3f seconds)", $cptime))
105 if ($cptime > 5);
e2beb7aa 106
a3d58ffc 107 $cycle++;
e2beb7aa 108
a3d58ffc
DM
109 my $mem = PVE::ProcFSTools::read_memory_usage();
110
111 if (!defined($initial_memory_usage) || ($cycle < 10)) {
112 $initial_memory_usage = $mem->{resident};
113 } else {
114 my $diff = $mem->{resident} - $initial_memory_usage;
115 if ($diff > 5*1024*1024) {
116 syslog ('info', "restarting server after $cycle cycles to " .
117 "reduce memory usage (free $mem->{resident} ($diff) bytes)");
118 $self->restart_daemon();
e2beb7aa
DM
119 }
120 }
121
a3d58ffc
DM
122 my $wcount = 0;
123 while ((time() < $next_update) &&
124 ($wcount < $updatetime) && # protect against time wrap
125 !$restart_request) { $wcount++; sleep (1); };
126
127 $self->restart_daemon() if $restart_request;
128 }
129}
130
88e44ee4 131$daemon->register_start_command("Start the Proxmox VE firewall service.");
a6811508 132$daemon->register_restart_command(1, "Restart the Proxmox VE firewall service.");
88e44ee4 133$daemon->register_stop_command("Stop firewall. This removes all Proxmox VE " .
a3d58ffc
DM
134 "related iptable rules. " .
135 "The host is unprotected afterwards.");
e2beb7aa
DM
136
137__PACKAGE__->register_method ({
138 name => 'status',
139 path => 'status',
140 method => 'GET',
141 description => "Get firewall status.",
142 parameters => {
143 additionalProperties => 0,
144 properties => {},
145 },
146 returns => {
147 type => 'object',
148 additionalProperties => 0,
149 properties => {
150 status => {
151 type => 'string',
55fad3b7
DM
152 enum => ['unknown', 'stopped', 'running'],
153 },
154 enable => {
155 description => "Firewall is enabled (in 'cluster.fw')",
156 type => 'boolean',
e2beb7aa
DM
157 },
158 changes => {
159 description => "Set when there are pending changes.",
160 type => 'boolean',
161 optional => 1,
162 }
163 },
164 },
165 code => sub {
166 my ($param) = @_;
167
168 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
169
170 my $code = sub {
171
a3d58ffc 172 my $status = $daemon->running() ? 'running' : 'stopped';
e2beb7aa
DM
173
174 my $res = { status => $status };
55fad3b7
DM
175
176 my $verbose = 1; # show syntax errors
177 my $cluster_conf = PVE::Firewall::load_clusterfw_conf(undef, $verbose);
178 $res->{enable} = $cluster_conf->{options}->{enable} ? 1 : 0;
179
180 if ($status eq 'running') {
d4cda423 181
638c755a 182 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile($cluster_conf, undef, undef, $verbose);
e2beb7aa 183
d4cda423
DM
184 $verbose = 0; # do not show iptables details
185 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, $verbose);
55fad3b7 186 my ($test, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, $verbose);
17da5c0f
AD
187 my (undef, $ruleset_changesv6) = PVE::Firewall::get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
188
189 $res->{changes} = ($ipset_changes || $ruleset_changes || $ruleset_changesv6) ? 1 : 0;
e2beb7aa
DM
190 }
191
192 return $res;
193 };
194
195 return PVE::Firewall::run_locked($code);
196 }});
197
198__PACKAGE__->register_method ({
199 name => 'compile',
200 path => 'compile',
3324948a 201 method => 'GET',
16adff04 202 description => "Compile and print firewall rules. This is useful for testing.",
e2beb7aa
DM
203 parameters => {
204 additionalProperties => 0,
205 properties => {},
206 },
207 returns => { type => 'null' },
208
209 code => sub {
210 my ($param) = @_;
211
212 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
213
214 my $code = sub {
e2beb7aa 215
d4cda423
DM
216 my $verbose = 1;
217
55fad3b7 218 my $cluster_conf = PVE::Firewall::load_clusterfw_conf(undef, $verbose);
638c755a 219 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile($cluster_conf, undef, undef, $verbose);
d4cda423 220
1cc9bd90 221 print "ipset cmdlist:\n";
d4cda423 222 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, $verbose);
1cc9bd90
DM
223
224 print "\niptables cmdlist:\n";
d4cda423 225 my (undef, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, $verbose);
1cc9bd90
DM
226
227 print "\nip6tables cmdlist:\n";
17da5c0f 228 my (undef, $ruleset_changesv6) = PVE::Firewall::get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
55fad3b7 229
17da5c0f 230 if ($ipset_changes || $ruleset_changes || $ruleset_changesv6) {
e2beb7aa
DM
231 print "detected changes\n";
232 } else {
233 print "no changes\n";
234 }
55fad3b7
DM
235 if (!$cluster_conf->{options}->{enable}) {
236 print "firewall disabled\n";
237 }
238
e2beb7aa
DM
239 };
240
241 PVE::Firewall::run_locked($code);
242
243 return undef;
244 }});
245
e7fb6ff2
DM
246__PACKAGE__->register_method ({
247 name => 'localnet',
248 path => 'localnet',
249 method => 'GET',
250 description => "Print information about local network.",
251 parameters => {
252 additionalProperties => 0,
253 properties => {},
254 },
255 returns => { type => 'null' },
256 code => sub {
257 my ($param) = @_;
258
259 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
260
261 my $nodename = PVE::INotify::nodename();
262 print "local hostname: $nodename\n";
263
264 my $ip = PVE::Cluster::remote_node_ip($nodename);
265 print "local IP address: $ip\n";
266
267 my $cluster_conf = PVE::Firewall::load_clusterfw_conf();
268
269 my $localnet = PVE::Firewall::local_network() || '127.0.0.0/8';
270 print "network auto detect: $localnet\n";
271 if ($cluster_conf->{aliases}->{local_network}) {
272 print "using user defined local_network: $cluster_conf->{aliases}->{local_network}->{cidr}\n";
273 } else {
274 print "using detected local_network: $localnet\n";
275 }
276
277 return undef;
278 }});
279
814de832
DM
280__PACKAGE__->register_method ({
281 name => 'simulate',
282 path => 'simulate',
3324948a 283 method => 'GET',
c9902e5a 284 description => "Simulate firewall rules. This does not simulate kernel 'routing' table. Instead, this simply assumes that routing from source zone to destination zone is possible.",
814de832
DM
285 parameters => {
286 additionalProperties => 0,
287 properties => {
288 verbose => {
289 description => "Verbose output.",
290 type => 'boolean',
291 optional => 1,
292 default => 0,
293 },
294 from => {
295 description => "Source zone.",
296 type => 'string',
297 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
298 optional => 1,
299 default => 'outside',
300 },
301 to => {
302 description => "Destination zone.",
303 type => 'string',
304 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
305 optional => 1,
306 default => 'host',
307 },
308 protocol => {
309 description => "Protocol.",
310 type => 'string',
311 pattern => '(tcp|udp)',
312 optional => 1,
313 default => 'tcp',
314 },
315 dport => {
316 description => "Destination port.",
317 type => 'integer',
318 minValue => 1,
319 maxValue => 65535,
320 optional => 1,
321 },
322 sport => {
323 description => "Source port.",
324 type => 'integer',
325 minValue => 1,
326 maxValue => 65535,
327 optional => 1,
328 },
329 source => {
330 description => "Source IP address.",
331 type => 'string', format => 'ipv4',
332 optional => 1,
333 },
334 dest => {
335 description => "Destination IP address.",
336 type => 'string', format => 'ipv4',
337 optional => 1,
338 },
339 },
340 },
341 returns => { type => 'null' },
342 code => sub {
343 my ($param) = @_;
344
815b4ebf
DM
345 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
346
638c755a 347 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile(undef, undef, undef, $param->{verbose});
814de832
DM
348
349 PVE::FirewallSimulator::debug($param->{verbose} || 0);
350
351 my $host_ip = PVE::Cluster::remote_node_ip($nodename);
352
353 PVE::FirewallSimulator::reset_trace();
354 print Dumper($ruleset) if $param->{verbose};
355
356 my $test = {
357 from => $param->{from},
358 to => $param->{to},
359 proto => $param->{protocol} || 'tcp',
360 source => $param->{source},
361 dest => $param->{dest},
362 dport => $param->{dport},
363 sport => $param->{sport},
364 };
365
366 if (!defined($test->{to})) {
367 $test->{to} = 'host';
368 PVE::FirewallSimulator::add_trace("Set Zone: to => '$test->{to}'\n");
369 }
370 if (!defined($test->{from})) {
371 $test->{from} = 'outside',
372 PVE::FirewallSimulator::add_trace("Set Zone: from => '$test->{from}'\n");
373 }
374
375 my $vmdata = PVE::Firewall::read_local_vm_config();
376
377 print "Test packet:\n";
378
379 foreach my $k (qw(from to proto source dest dport sport)) {
380 printf(" %-8s: %s\n", $k, $test->{$k}) if defined($test->{$k});
381 }
382
383 $test->{action} = 'QUERY';
384
385 my $res = PVE::FirewallSimulator::simulate_firewall($ruleset, $ipset_ruleset,
386 $host_ip, $vmdata, $test);
387
388 print "ACTION: $res\n";
389
390 return undef;
391 }});
e2beb7aa
DM
392
393my $cmddef = {
394 start => [ __PACKAGE__, 'start', []],
a3d58ffc 395 restart => [ __PACKAGE__, 'restart', []],
e2beb7aa
DM
396 stop => [ __PACKAGE__, 'stop', []],
397 compile => [ __PACKAGE__, 'compile', []],
814de832 398 simulate => [ __PACKAGE__, 'simulate', []],
e7fb6ff2 399 localnet => [ __PACKAGE__, 'localnet', []],
e2beb7aa
DM
400 status => [ __PACKAGE__, 'status', [], undef, sub {
401 my $res = shift;
55fad3b7
DM
402 my $status = ($res->{enable} ? "enabled" : "disabled") . '/' . $res->{status};
403
e2beb7aa 404 if ($res->{changes}) {
55fad3b7 405 print "Status: $status (pending changes)\n";
e2beb7aa 406 } else {
55fad3b7 407 print "Status: $status\n";
e2beb7aa
DM
408 }
409 }],
410 };
411
412my $cmd = shift;
413
414PVE::CLIHandler::handle_cmd($cmddef, $0, $cmd, \@ARGV, undef, $0);
415
416exit (0);
417
418__END__
419
420=head1 NAME
421
16adff04 422pve-firewall - PVE Firewall Daemon
e2beb7aa
DM
423
424=head1 SYNOPSIS
425
16adff04 426=include synopsis
e2beb7aa
DM
427
428=head1 DESCRIPTION
429
430This service updates iptables rules periodically.
431
16adff04 432=include pve_copyright