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