]> git.proxmox.com Git - pve-firewall.git/blob - src/pve-firewall
6e5eb1633cb2ff033fa8b93c0671d09b4c58d6ec
[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 PVE::INotify::inotify_close();
62
63 exec (@$commandline);
64 exit (-1); # never reached?
65 }
66
67 sub cleanup {
68 unlink "$pve_firewall_pidfile.lock";
69 unlink $pve_firewall_pidfile;
70 }
71
72 sub 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
90 sub 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
102 my $restart_request = 0;
103 my $next_update = 0;
104
105 my $cycle = 0;
106 my $updatetime = 10;
107
108 my $initial_memory_usage;
109
110 sub 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
123 PVE::Cluster::cfs_update();
124
125 PVE::Firewall::init();
126
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',
264 description => "Stop firewall. This removes all Proxmox VE related iptable rules. The host is unprotected afterwards.",
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', 'running'],
315 },
316 enable => {
317 description => "Firewall is enabled (in 'cluster.fw')",
318 type => 'boolean',
319 },
320 changes => {
321 description => "Set when there are pending changes.",
322 type => 'boolean',
323 optional => 1,
324 }
325 },
326 },
327 code => sub {
328 my ($param) = @_;
329
330 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
331
332 my $code = sub {
333
334 my $pid = int(PVE::Tools::file_read_firstline($pve_firewall_pidfile) || 0);
335 my $running = PVE::ProcFSTools::check_process_running($pid);
336
337 my $status = $running ? 'running' : 'stopped';
338
339 my $res = { status => $status };
340
341 my $verbose = 1; # show syntax errors
342 my $cluster_conf = PVE::Firewall::load_clusterfw_conf(undef, $verbose);
343 $res->{enable} = $cluster_conf->{options}->{enable} ? 1 : 0;
344
345 if ($status eq 'running') {
346
347 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile($cluster_conf, undef, undef, $verbose);
348
349 $verbose = 0; # do not show iptables details
350 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, $verbose);
351 my ($test, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, $verbose);
352 my (undef, $ruleset_changesv6) = PVE::Firewall::get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
353
354 $res->{changes} = ($ipset_changes || $ruleset_changes || $ruleset_changesv6) ? 1 : 0;
355 }
356
357 return $res;
358 };
359
360 return PVE::Firewall::run_locked($code);
361 }});
362
363 __PACKAGE__->register_method ({
364 name => 'compile',
365 path => 'compile',
366 method => 'GET',
367 description => "Compile and print firewall rules. This is useful for testing.",
368 parameters => {
369 additionalProperties => 0,
370 properties => {},
371 },
372 returns => { type => 'null' },
373
374 code => sub {
375 my ($param) = @_;
376
377 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
378
379 my $code = sub {
380
381 my $verbose = 1;
382
383 my $cluster_conf = PVE::Firewall::load_clusterfw_conf(undef, $verbose);
384 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile($cluster_conf, undef, undef, $verbose);
385
386 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, $verbose);
387 my (undef, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, $verbose);
388 my (undef, $ruleset_changesv6) = PVE::Firewall::get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
389
390 if ($ipset_changes || $ruleset_changes || $ruleset_changesv6) {
391 print "detected changes\n";
392 } else {
393 print "no changes\n";
394 }
395 if (!$cluster_conf->{options}->{enable}) {
396 print "firewall disabled\n";
397 }
398
399 };
400
401 PVE::Firewall::run_locked($code);
402
403 return undef;
404 }});
405
406 __PACKAGE__->register_method ({
407 name => 'localnet',
408 path => 'localnet',
409 method => 'GET',
410 description => "Print information about local network.",
411 parameters => {
412 additionalProperties => 0,
413 properties => {},
414 },
415 returns => { type => 'null' },
416 code => sub {
417 my ($param) = @_;
418
419 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
420
421 my $nodename = PVE::INotify::nodename();
422 print "local hostname: $nodename\n";
423
424 my $ip = PVE::Cluster::remote_node_ip($nodename);
425 print "local IP address: $ip\n";
426
427 my $cluster_conf = PVE::Firewall::load_clusterfw_conf();
428
429 my $localnet = PVE::Firewall::local_network() || '127.0.0.0/8';
430 print "network auto detect: $localnet\n";
431 if ($cluster_conf->{aliases}->{local_network}) {
432 print "using user defined local_network: $cluster_conf->{aliases}->{local_network}->{cidr}\n";
433 } else {
434 print "using detected local_network: $localnet\n";
435 }
436
437 return undef;
438 }});
439
440 __PACKAGE__->register_method ({
441 name => 'simulate',
442 path => 'simulate',
443 method => 'GET',
444 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.",
445 parameters => {
446 additionalProperties => 0,
447 properties => {
448 verbose => {
449 description => "Verbose output.",
450 type => 'boolean',
451 optional => 1,
452 default => 0,
453 },
454 from => {
455 description => "Source zone.",
456 type => 'string',
457 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
458 optional => 1,
459 default => 'outside',
460 },
461 to => {
462 description => "Destination zone.",
463 type => 'string',
464 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
465 optional => 1,
466 default => 'host',
467 },
468 protocol => {
469 description => "Protocol.",
470 type => 'string',
471 pattern => '(tcp|udp)',
472 optional => 1,
473 default => 'tcp',
474 },
475 dport => {
476 description => "Destination port.",
477 type => 'integer',
478 minValue => 1,
479 maxValue => 65535,
480 optional => 1,
481 },
482 sport => {
483 description => "Source port.",
484 type => 'integer',
485 minValue => 1,
486 maxValue => 65535,
487 optional => 1,
488 },
489 source => {
490 description => "Source IP address.",
491 type => 'string', format => 'ipv4',
492 optional => 1,
493 },
494 dest => {
495 description => "Destination IP address.",
496 type => 'string', format => 'ipv4',
497 optional => 1,
498 },
499 },
500 },
501 returns => { type => 'null' },
502 code => sub {
503 my ($param) = @_;
504
505 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
506
507 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile(undef, undef, undef, $param->{verbose});
508
509 PVE::FirewallSimulator::debug($param->{verbose} || 0);
510
511 my $host_ip = PVE::Cluster::remote_node_ip($nodename);
512
513 PVE::FirewallSimulator::reset_trace();
514 print Dumper($ruleset) if $param->{verbose};
515
516 my $test = {
517 from => $param->{from},
518 to => $param->{to},
519 proto => $param->{protocol} || 'tcp',
520 source => $param->{source},
521 dest => $param->{dest},
522 dport => $param->{dport},
523 sport => $param->{sport},
524 };
525
526 if (!defined($test->{to})) {
527 $test->{to} = 'host';
528 PVE::FirewallSimulator::add_trace("Set Zone: to => '$test->{to}'\n");
529 }
530 if (!defined($test->{from})) {
531 $test->{from} = 'outside',
532 PVE::FirewallSimulator::add_trace("Set Zone: from => '$test->{from}'\n");
533 }
534
535 my $vmdata = PVE::Firewall::read_local_vm_config();
536
537 print "Test packet:\n";
538
539 foreach my $k (qw(from to proto source dest dport sport)) {
540 printf(" %-8s: %s\n", $k, $test->{$k}) if defined($test->{$k});
541 }
542
543 $test->{action} = 'QUERY';
544
545 my $res = PVE::FirewallSimulator::simulate_firewall($ruleset, $ipset_ruleset,
546 $host_ip, $vmdata, $test);
547
548 print "ACTION: $res\n";
549
550 return undef;
551 }});
552
553 my $cmddef = {
554 start => [ __PACKAGE__, 'start', []],
555 stop => [ __PACKAGE__, 'stop', []],
556 compile => [ __PACKAGE__, 'compile', []],
557 simulate => [ __PACKAGE__, 'simulate', []],
558 localnet => [ __PACKAGE__, 'localnet', []],
559 status => [ __PACKAGE__, 'status', [], undef, sub {
560 my $res = shift;
561 my $status = ($res->{enable} ? "enabled" : "disabled") . '/' . $res->{status};
562
563 if ($res->{changes}) {
564 print "Status: $status (pending changes)\n";
565 } else {
566 print "Status: $status\n";
567 }
568 }],
569 };
570
571 my $cmd = shift;
572
573 PVE::CLIHandler::handle_cmd($cmddef, $0, $cmd, \@ARGV, undef, $0);
574
575 exit (0);
576
577 __END__
578
579 =head1 NAME
580
581 pve-firewall - PVE Firewall Daemon
582
583 =head1 SYNOPSIS
584
585 =include synopsis
586
587 =head1 DESCRIPTION
588
589 This service updates iptables rules periodically.
590
591 =include pve_copyright