]> git.proxmox.com Git - pve-firewall.git/blame - src/pve-firewall
allow to read rule with errors
[pve-firewall.git] / src / pve-firewall
CommitLineData
e2beb7aa
DM
1#!/usr/bin/perl
2
3use strict;
4use warnings;
5use PVE::SafeSyslog;
6use POSIX ":sys_wait_h";
7use Fcntl ':flock';
8use Getopt::Long;
9use Time::HiRes qw (gettimeofday);
10use PVE::Tools qw(dir_glob_foreach file_read_firstline);
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
DM
18
19use base qw(PVE::CLIHandler);
20
21my $pve_firewall_pidfile = "/var/run/pve-firewall.pid";
22
23$SIG{'__WARN__'} = sub {
24 my $err = $@;
25 my $t = $_[0];
26 chomp $t;
27 print "$t\n";
28 syslog('warning', "WARNING: %s", $t);
29 $@ = $err;
30};
31
32initlog('pve-firewall');
33
34$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
35
36die "please run as root\n" if $> != 0;
37
38PVE::INotify::inotify_init();
39
40my $rpcenv = PVE::RPCEnvironment->init('cli');
41
42$rpcenv->init_request();
43$rpcenv->set_language($ENV{LANG});
44$rpcenv->set_user('root@pam');
45
814de832
DM
46my $nodename = PVE::INotify::nodename();
47
e2beb7aa
DM
48my $commandline = [$0, @ARGV];
49
50$0 = "pve-firewall";
51
52sub restart_server {
53 my ($waittime) = @_;
54
55 syslog('info', "server shutdown (restart)");
56
57 $ENV{RESTART_PVE_FIREWALL} = 1;
58
59 sleep($waittime) if $waittime; # avoid high server load due to restarts
60
3e998704
DM
61 PVE::INotify::inotify_close();
62
e2beb7aa
DM
63 exec (@$commandline);
64 exit (-1); # never reached?
65}
66
67sub cleanup {
68 unlink "$pve_firewall_pidfile.lock";
69 unlink $pve_firewall_pidfile;
70}
71
72sub lockpidfile {
73 my $pidfile = shift;
74 my $lkfn = "$pidfile.lock";
75
76 if (!open (FLCK, ">>$lkfn")) {
77 my $msg = "can't aquire lock on file '$lkfn' - $!";
78 syslog ('err', $msg);
79 die "ERROR: $msg\n";
80 }
81
82 if (!flock (FLCK, LOCK_EX|LOCK_NB)) {
83 close (FLCK);
84 my $msg = "can't aquire lock '$lkfn' - $!";
85 syslog ('err', $msg);
86 die "ERROR: $msg\n";
87 }
88}
89
90sub writepidfile {
91 my $pidfile = shift;
92
93 if (!open (PIDFH, ">$pidfile")) {
94 my $msg = "can't open pid file '$pidfile' - $!";
95 syslog ('err', $msg);
96 die "ERROR: $msg\n";
97 }
98 print PIDFH "$$\n";
99 close (PIDFH);
100}
101
102my $restart_request = 0;
103my $next_update = 0;
104
105my $cycle = 0;
106my $updatetime = 10;
107
108my $initial_memory_usage;
109
110sub run_server {
111 my ($param) = @_;
112
113 # try to get the lock
114 lockpidfile($pve_firewall_pidfile);
115
116 # run in background
117 my $spid;
118
119 my $restart = $ENV{RESTART_PVE_FIREWALL};
120
121 delete $ENV{RESTART_PVE_FIREWALL};
122
8b453a09
DM
123 PVE::Cluster::cfs_update();
124
125 PVE::Firewall::init();
126
e2beb7aa
DM
127 if (!$param->{debug}) {
128 open STDIN, '</dev/null' || die "can't read /dev/null";
129 open STDOUT, '>/dev/null' || die "can't write /dev/null";
130 }
131
132 if (!$restart && !$param->{debug}) {
133 $spid = fork();
134 if (!defined ($spid)) {
135 my $msg = "can't put server into background - fork failed";
136 syslog('err', $msg);
137 die "ERROR: $msg\n";
138 } elsif ($spid) { # parent
139 exit (0);
140 }
141 }
142
143 writepidfile($pve_firewall_pidfile);
144
145 open STDERR, '>&STDOUT' || die "can't close STDERR\n";
146
147 $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = sub {
148 syslog('info' , "server closing");
149
150 $SIG{INT} = 'DEFAULT';
151
152 # wait for children
153 1 while (waitpid(-1, POSIX::WNOHANG()) > 0);
154
155 syslog('info' , "clear firewall rules");
156 eval { PVE::Firewall::remove_pvefw_chains(); die "STOP";};
157 warn $@ if $@;
158
159 cleanup();
160
161 exit (0);
162 };
163
164 $SIG{HUP} = sub {
165 # wake up process, so this forces an immediate firewall rules update
166 syslog('info' , "received signal HUP (restart)");
167 $restart_request = 1;
168 };
169
170 if ($restart) {
171 syslog('info' , "restarting server");
172 } else {
173 syslog('info' , "starting server");
174 }
175
176 for (;;) { # forever
177
178 eval {
179
180 local $SIG{'__WARN__'} = 'IGNORE'; # do not fill up logs
181
182 $next_update = time() + $updatetime;
183
184 my ($ccsec, $cusec) = gettimeofday ();
185 eval {
186 PVE::Cluster::cfs_update();
187 PVE::Firewall::update();
188 };
189 my $err = $@;
190
191 if ($err) {
192 syslog('err', "status update error: $err");
193 }
194
195 my ($ccsec_end, $cusec_end) = gettimeofday ();
196 my $cptime = ($ccsec_end-$ccsec) + ($cusec_end - $cusec)/1000000;
197
198 syslog('info', sprintf("firewall update time (%.3f seconds)", $cptime))
199 if ($cptime > 5);
200
201 $cycle++;
202
203 my $mem = PVE::ProcFSTools::read_memory_usage();
204
205 if (!defined($initial_memory_usage) || ($cycle < 10)) {
206 $initial_memory_usage = $mem->{resident};
207 } else {
208 my $diff = $mem->{resident} - $initial_memory_usage;
209 if ($diff > 5*1024*1024) {
210 syslog ('info', "restarting server after $cycle cycles to " .
211 "reduce memory usage (free $mem->{resident} ($diff) bytes)");
212 restart_server();
213 }
214 }
215
216 my $wcount = 0;
217 while ((time() < $next_update) &&
218 ($wcount < $updatetime) && # protect against time wrap
219 !$restart_request) { $wcount++; sleep (1); };
220
221 restart_server() if $restart_request;
222 };
223
224 my $err = $@;
225
226 if ($err) {
227 syslog ('err', "ERROR: $err");
228 restart_server(5);
229 exit (0);
230 }
231 }
232}
233
234__PACKAGE__->register_method ({
235 name => 'start',
236 path => 'start',
237 method => 'POST',
238 description => "Start the Proxmox VE firewall service.",
239 parameters => {
240 additionalProperties => 0,
241 properties => {
242 debug => {
243 description => "Debug mode - stay in foreground",
244 type => "boolean",
245 optional => 1,
246 default => 0,
247 },
248 },
249 },
250 returns => { type => 'null' },
251
252 code => sub {
253 my ($param) = @_;
254
255 run_server($param);
256
257 return undef;
258 }});
259
260__PACKAGE__->register_method ({
261 name => 'stop',
262 path => 'stop',
263 method => 'POST',
16adff04 264 description => "Stop firewall. This removes all Proxmox VE related iptable rules. The host is unprotected afterwards.",
e2beb7aa
DM
265 parameters => {
266 additionalProperties => 0,
267 properties => {},
268 },
269 returns => { type => 'null' },
270
271 code => sub {
272 my ($param) = @_;
273
274 my $pid = int(PVE::Tools::file_read_firstline($pve_firewall_pidfile) || 0);
275
276 if ($pid) {
277 if (PVE::ProcFSTools::check_process_running($pid)) {
278 kill(15, $pid); # send TERM signal
279 # give max 5 seconds to shut down
280 for (my $i = 0; $i < 5; $i++) {
281 last if !PVE::ProcFSTools::check_process_running($pid);
282 sleep (1);
283 }
284
285 # to be sure
286 kill(9, $pid);
287 waitpid($pid, 0);
288 }
289 if (-f $pve_firewall_pidfile) {
290 # try to get the lock
291 lockpidfile($pve_firewall_pidfile);
292 cleanup();
293 }
294 }
295
296 return undef;
297 }});
298
299__PACKAGE__->register_method ({
300 name => 'status',
301 path => 'status',
302 method => 'GET',
303 description => "Get firewall status.",
304 parameters => {
305 additionalProperties => 0,
306 properties => {},
307 },
308 returns => {
309 type => 'object',
310 additionalProperties => 0,
311 properties => {
312 status => {
313 type => 'string',
314 enum => ['unknown', 'stopped', 'active'],
315 },
316 changes => {
317 description => "Set when there are pending changes.",
318 type => 'boolean',
319 optional => 1,
320 }
321 },
322 },
323 code => sub {
324 my ($param) = @_;
325
326 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
327
328 my $code = sub {
329
330 my $pid = int(PVE::Tools::file_read_firstline($pve_firewall_pidfile) || 0);
331 my $running = PVE::ProcFSTools::check_process_running($pid);
332
333 my $status = $running ? 'active' : 'stopped';
334
335 my $res = { status => $status };
336 if ($status eq 'active') {
337 my ($ruleset, $ipset_ruleset) = PVE::Firewall::compile();
338
339 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset);
340 my (undef, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset);
341
342 $res->{changes} = ($ipset_changes || $ruleset_changes) ? 1 : 0;
343 }
344
345 return $res;
346 };
347
348 return PVE::Firewall::run_locked($code);
349 }});
350
351__PACKAGE__->register_method ({
352 name => 'compile',
353 path => 'compile',
3324948a 354 method => 'GET',
16adff04 355 description => "Compile and print firewall rules. This is useful for testing.",
e2beb7aa
DM
356 parameters => {
357 additionalProperties => 0,
358 properties => {},
359 },
360 returns => { type => 'null' },
361
362 code => sub {
363 my ($param) = @_;
364
365 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
366
367 my $code = sub {
368 my ($ruleset, $ipset_ruleset) = PVE::Firewall::compile();
369
370 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, 1);
371 my (undef, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, 1);
372 if ($ipset_changes || $ruleset_changes) {
373 print "detected changes\n";
374 } else {
375 print "no changes\n";
376 }
377 };
378
379 PVE::Firewall::run_locked($code);
380
381 return undef;
382 }});
383
e7fb6ff2
DM
384__PACKAGE__->register_method ({
385 name => 'localnet',
386 path => 'localnet',
387 method => 'GET',
388 description => "Print information about local network.",
389 parameters => {
390 additionalProperties => 0,
391 properties => {},
392 },
393 returns => { type => 'null' },
394 code => sub {
395 my ($param) = @_;
396
397 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
398
399 my $nodename = PVE::INotify::nodename();
400 print "local hostname: $nodename\n";
401
402 my $ip = PVE::Cluster::remote_node_ip($nodename);
403 print "local IP address: $ip\n";
404
405 my $cluster_conf = PVE::Firewall::load_clusterfw_conf();
406
407 my $localnet = PVE::Firewall::local_network() || '127.0.0.0/8';
408 print "network auto detect: $localnet\n";
409 if ($cluster_conf->{aliases}->{local_network}) {
410 print "using user defined local_network: $cluster_conf->{aliases}->{local_network}->{cidr}\n";
411 } else {
412 print "using detected local_network: $localnet\n";
413 }
414
415 return undef;
416 }});
417
814de832
DM
418__PACKAGE__->register_method ({
419 name => 'simulate',
420 path => 'simulate',
3324948a 421 method => 'GET',
c9902e5a 422 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
423 parameters => {
424 additionalProperties => 0,
425 properties => {
426 verbose => {
427 description => "Verbose output.",
428 type => 'boolean',
429 optional => 1,
430 default => 0,
431 },
432 from => {
433 description => "Source zone.",
434 type => 'string',
435 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
436 optional => 1,
437 default => 'outside',
438 },
439 to => {
440 description => "Destination zone.",
441 type => 'string',
442 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
443 optional => 1,
444 default => 'host',
445 },
446 protocol => {
447 description => "Protocol.",
448 type => 'string',
449 pattern => '(tcp|udp)',
450 optional => 1,
451 default => 'tcp',
452 },
453 dport => {
454 description => "Destination port.",
455 type => 'integer',
456 minValue => 1,
457 maxValue => 65535,
458 optional => 1,
459 },
460 sport => {
461 description => "Source port.",
462 type => 'integer',
463 minValue => 1,
464 maxValue => 65535,
465 optional => 1,
466 },
467 source => {
468 description => "Source IP address.",
469 type => 'string', format => 'ipv4',
470 optional => 1,
471 },
472 dest => {
473 description => "Destination IP address.",
474 type => 'string', format => 'ipv4',
475 optional => 1,
476 },
477 },
478 },
479 returns => { type => 'null' },
480 code => sub {
481 my ($param) = @_;
482
815b4ebf
DM
483 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
484
814de832
DM
485 my ($ruleset, $ipset_ruleset) = PVE::Firewall::compile();
486
487 PVE::FirewallSimulator::debug($param->{verbose} || 0);
488
489 my $host_ip = PVE::Cluster::remote_node_ip($nodename);
490
491 PVE::FirewallSimulator::reset_trace();
492 print Dumper($ruleset) if $param->{verbose};
493
494 my $test = {
495 from => $param->{from},
496 to => $param->{to},
497 proto => $param->{protocol} || 'tcp',
498 source => $param->{source},
499 dest => $param->{dest},
500 dport => $param->{dport},
501 sport => $param->{sport},
502 };
503
504 if (!defined($test->{to})) {
505 $test->{to} = 'host';
506 PVE::FirewallSimulator::add_trace("Set Zone: to => '$test->{to}'\n");
507 }
508 if (!defined($test->{from})) {
509 $test->{from} = 'outside',
510 PVE::FirewallSimulator::add_trace("Set Zone: from => '$test->{from}'\n");
511 }
512
513 my $vmdata = PVE::Firewall::read_local_vm_config();
514
515 print "Test packet:\n";
516
517 foreach my $k (qw(from to proto source dest dport sport)) {
518 printf(" %-8s: %s\n", $k, $test->{$k}) if defined($test->{$k});
519 }
520
521 $test->{action} = 'QUERY';
522
523 my $res = PVE::FirewallSimulator::simulate_firewall($ruleset, $ipset_ruleset,
524 $host_ip, $vmdata, $test);
525
526 print "ACTION: $res\n";
527
528 return undef;
529 }});
e2beb7aa
DM
530
531my $cmddef = {
532 start => [ __PACKAGE__, 'start', []],
533 stop => [ __PACKAGE__, 'stop', []],
534 compile => [ __PACKAGE__, 'compile', []],
814de832 535 simulate => [ __PACKAGE__, 'simulate', []],
e7fb6ff2 536 localnet => [ __PACKAGE__, 'localnet', []],
e2beb7aa
DM
537 status => [ __PACKAGE__, 'status', [], undef, sub {
538 my $res = shift;
539 if ($res->{changes}) {
540 print "Status: $res->{status} (pending changes)\n";
541 } else {
542 print "Status: $res->{status}\n";
543 }
544 }],
545 };
546
547my $cmd = shift;
548
549PVE::CLIHandler::handle_cmd($cmddef, $0, $cmd, \@ARGV, undef, $0);
550
551exit (0);
552
553__END__
554
555=head1 NAME
556
16adff04 557pve-firewall - PVE Firewall Daemon
e2beb7aa
DM
558
559=head1 SYNOPSIS
560
16adff04 561=include synopsis
e2beb7aa
DM
562
563=head1 DESCRIPTION
564
565This service updates iptables rules periodically.
566
16adff04 567=include pve_copyright