]>
git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
1 package PVE
::RPCEnvironment
;
5 use POSIX
qw(:sys_wait_h EINTR);
10 use PVE
::Exception
qw(raise raise_perm_exc);
16 use PVE
::AccessControl
;
18 # we use this singleton class to pass RPC related environment values
22 # save $SIG{CHLD} handler implementation.
23 # simply set $SIG{CHLD} = $worker_reaper;
24 # and register forked processes with &$register_worker(pid)
25 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
26 # has serious side effects, because perls built in system() and open()
27 # functions can't get the correct exit status of a child. So we cant use
28 # that (also see perlipc)
32 my $log_task_result = sub {
33 my ($upid, $user, $status) = @_;
35 my $msg = 'successful';
38 my $ec = $status >> 8;
39 my $ic = $status & 255;
40 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
43 my $tlist = active_workers
($upid);
44 PVE
::Cluster
::broadcast_tasklist
($tlist);
46 foreach my $t (@$tlist) {
47 if ($t->{upid
} eq $upid) {
52 if ($task && $task->{status
}) {
53 $msg = $task->{status
};
55 PVE
::Cluster
::log_msg
($pri, $user, "end task $upid $msg");
58 my $worker_reaper = sub {
60 foreach my $pid (keys %$WORKER_PIDS) {
61 my $waitpid = waitpid ($pid, WNOHANG
);
62 if (defined($waitpid) && ($waitpid == $pid)) {
63 my $info = $WORKER_PIDS->{$pid};
64 if ($info && $info->{upid
} && $info->{user
}) {
65 &$log_task_result($info->{upid
}, $info->{user
}, $?);
67 delete ($WORKER_PIDS->{$pid});
72 my $register_worker = sub {
73 my ($pid, $user, $upid) = @_;
77 # do not register if already finished
78 my $waitpid = waitpid ($pid, WNOHANG
);
79 if (defined($waitpid) && ($waitpid == $pid)) {
80 delete ($WORKER_PIDS->{$pid});
84 $WORKER_PIDS->{$pid} = {
92 my $compile_acl_path = sub {
93 my ($self, $user, $path) = @_;
95 my $cfg = $self->{user_cfg
};
97 return undef if !$cfg->{roles
};
99 die "internal error" if $user eq 'root@pam';
101 my $cache = $self->{aclcache
};
102 $cache->{$user} = {} if !$cache->{$user};
103 my $data = $cache->{$user};
105 if (!$data->{poolroles
}) {
106 $data->{poolroles
} = {};
108 foreach my $pool (keys %{$cfg->{pools
}}) {
109 my $d = $cfg->{pools
}->{$pool};
110 my @ra = PVE
::AccessControl
::roles
($cfg, $user, "/pool/$pool"); # pool roles
111 next if !scalar(@ra);
112 foreach my $vmid (keys %{$d->{vms
}}) {
114 $data->{poolroles
}->{"/vms/$vmid"}->{$role} = 1;
117 foreach my $storeid (keys %{$d->{storage
}}) {
119 $data->{poolroles
}->{"/storage/$storeid"}->{$role} = 1;
125 my @ra = PVE
::AccessControl
::roles
($cfg, $user, $path);
127 # apply roles inherited from pools
128 # Note: assume we do not want to propagate those privs
129 if ($data->{poolroles
}->{$path}) {
130 if (!($ra[0] && $ra[0] eq 'NoAccess')) {
131 if ($data->{poolroles
}->{$path}->{NoAccess
}) {
134 foreach my $role (keys %{$data->{poolroles
}->{$path}}) {
141 $data->{roles
}->{$path} = [ @ra ];
144 foreach my $role (@ra) {
145 if (my $privset = $cfg->{roles
}->{$role}) {
146 foreach my $p (keys %$privset) {
151 $data->{privs
}->{$path} = $privs;
157 my ($self, $user, $path) = @_;
159 if ($user eq 'root@pam') { # root can do anything
160 return ('Administrator');
163 $user = PVE
::AccessControl
::verify_username
($user, 1);
166 my $cache = $self->{aclcache
};
167 $cache->{$user} = {} if !$cache->{$user};
169 my $acl = $cache->{$user};
171 my $roles = $acl->{roles
}->{$path};
172 return @$roles if $roles;
174 &$compile_acl_path($self, $user, $path);
175 $roles = $acl->{roles
}->{$path} || [];
180 my ($self, $user, $path) = @_;
182 if ($user eq 'root@pam') { # root can do anything
183 my $cfg = $self->{user_cfg
};
184 return $cfg->{roles
}->{'Administrator'};
187 $user = PVE
::AccessControl
::verify_username
($user, 1);
190 my $cache = $self->{aclcache
};
191 $cache->{$user} = {} if !$cache->{$user};
193 my $acl = $cache->{$user};
195 my $perm = $acl->{privs
}->{$path};
196 return $perm if $perm;
198 return &$compile_acl_path($self, $user, $path);
202 my ($self, $user, $path, $privs, $noerr) = @_;
204 my $perm = $self->permissions($user, $path);
206 foreach my $priv (@$privs) {
207 PVE
::AccessControl
::verify_privname
($priv);
208 if (!$perm->{$priv}) {
209 return undef if $noerr;
210 raise_perm_exc
("$path, $priv");
218 my ($self, $user, $path, $privs, $noerr) = @_;
220 my $perm = $self->permissions($user, $path);
223 foreach my $priv (@$privs) {
224 PVE
::AccessControl
::verify_privname
($priv);
225 if ($perm->{$priv}) {
233 return undef if $noerr;
235 raise_perm_exc
("$path, " . join("|", @$privs));
239 my ($self, $username, $path, $privs, $any, $noerr) = @_;
241 return $self->check_any($username, $path, $privs, $noerr);
243 return $self->check($username, $path, $privs, $noerr);
247 sub check_user_enabled
{
248 my ($self, $user, $noerr) = @_;
250 my $cfg = $self->{user_cfg
};
251 return PVE
::AccessControl
::check_user_enabled
($cfg, $user, $noerr);
254 sub check_user_exist
{
255 my ($self, $user, $noerr) = @_;
257 my $cfg = $self->{user_cfg
};
258 return PVE
::AccessControl
::check_user_exist
($cfg, $user, $noerr);
261 sub check_pool_exist
{
262 my ($self, $pool, $noerr) = @_;
264 my $cfg = $self->{user_cfg
};
266 return 1 if $cfg->{pools
}->{$pool};
268 return undef if $noerr;
270 raise_perm_exc
("pool '$pool' does not exist");
274 my ($self, $user, $vmid, $pool, $privs, $any, $noerr) = @_;
276 my $cfg = $self->{user_cfg
};
279 return if $self->check_full($user, "/pool/$pool", $privs, $any, 1);
281 return $self->check_full($user, "/vms/$vmid", $privs, $any, $noerr);
284 sub check_volume_access
{
285 my ($self, $user, $storecfg, $vmid, $volid) = @_;
287 # test if we have read access to volid
289 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
291 my ($vtype, undef, $ownervm) = PVE
::Storage
::parse_volname
($storecfg, $volid);
292 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
293 # we simply allow access
294 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
295 # we are owner - allow access
296 } elsif ($vtype eq 'backup' && $ownervm) {
297 $self->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
298 $self->check($user, "/vms/$ownervm", ['VM.Backup']);
300 # allow if we are Datastore administrator
301 $self->check($user, "/storage/$sid", ['Datastore.Allocate']);
304 die "Only root can pass arbitrary filesystem paths."
305 if $user ne 'root@pam';
311 sub is_group_member
{
312 my ($self, $group, $user) = @_;
314 my $cfg = $self->{user_cfg
};
316 return 0 if !$cfg->{groups
}->{$group};
318 return defined($cfg->{groups
}->{$group}->{users
}->{$user});
322 my ($self, $user, $privs, $any) = @_;
324 my $cfg = $self->{user_cfg
};
327 foreach my $group (keys %{$cfg->{groups
}}) {
328 my $path = "/access/groups/$group";
329 if ($self->check_full($user, $path, $privs, $any, 1)) {
330 $groups->{$group} = $cfg->{groups
}->{$group};
337 sub group_member_join
{
338 my ($self, $grouplist) = @_;
342 my $cfg = $self->{user_cfg
};
343 foreach my $group (@$grouplist) {
344 my $data = $cfg->{groups
}->{$group};
346 foreach my $user (keys %{$data->{users
}}) {
354 sub check_perm_modify
{
355 my ($self, $username, $path, $noerr) = @_;
357 return $self->check($username, '/access', [ 'Permissions.Modify' ], $noerr) if !$path;
359 my $testperms = [ 'Permissions.Modify' ];
360 if ($path =~ m
|^/storage/.+$|) {
361 push @$testperms, 'Datastore.Allocate';
362 } elsif ($path =~ m
|^/vms/.+$|) {
363 push @$testperms, 'VM.Allocate';
364 } elsif ($path =~ m
|^/pool/.+$|) {
365 push @$testperms, 'Pool.Allocate';
368 return $self->check_any($username, $path, $testperms, $noerr);
371 sub exec_api2_perm_check
{
372 my ($self, $check, $username, $param, $noerr) = @_;
374 # syslog("info", "CHECK " . join(', ', @$check));
377 my $test = $check->[$ind++];
378 die "no permission test specified" if !$test;
380 if ($test eq 'and') {
381 while (my $subcheck = $check->[$ind++]) {
382 $self->exec_api2_perm_check($subcheck, $username, $param);
385 } elsif ($test eq 'or') {
386 while (my $subcheck = $check->[$ind++]) {
387 return 1 if $self->exec_api2_perm_check($subcheck, $username, $param, 1);
391 } elsif ($test eq 'perm') {
392 my ($t, $tmplpath, $privs, %options) = @$check;
393 my $any = $options{any
};
394 die "missing parameters" if !($tmplpath && $privs);
395 my $require_param = $options{require_param
};
396 if ($require_param && !defined($param->{$require_param})) {
400 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
401 $path = PVE
::AccessControl
::normalize_path
($path);
402 return $self->check_full($username, $path, $privs, $any, $noerr);
403 } elsif ($test eq 'userid-group') {
404 my $userid = $param->{userid
};
405 my ($t, $privs, %options) = @$check;
406 return 0 if !$options{groups_param
} && !$self->check_user_exist($userid, $noerr);
407 if (!$self->check_any($username, "/access/groups", $privs, 1)) {
408 my $groups = $self->filter_groups($username, $privs, 1);
409 if ($options{groups_param
}) {
410 my @group_param = PVE
::Tools
::split_list
($param->{groups
});
411 raise_perm_exc
("/access/groups, " . join("|", @$privs)) if !scalar(@group_param);
412 foreach my $pg (@group_param) {
413 raise_perm_exc
("/access/groups/$pg, " . join("|", @$privs))
417 my $allowed_users = $self->group_member_join([keys %$groups]);
418 if (!$allowed_users->{$userid}) {
425 } elsif ($test eq 'userid-param') {
426 my ($userid, undef, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
427 my ($t, $subtest) = @$check;
428 die "missing parameters" if !$subtest;
429 if ($subtest eq 'self') {
430 return 0 if !$self->check_user_exist($userid, $noerr);
431 return 1 if $username eq $userid;
434 } elsif ($subtest eq 'Realm.AllocateUser') {
435 my $path = "/access/realm/$realm";
436 return $self->check($username, $path, ['Realm.AllocateUser'], $noerr);
438 die "unknown userid-param test";
440 } elsif ($test eq 'perm-modify') {
441 my ($t, $tmplpath) = @$check;
442 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
443 $path = PVE
::AccessControl
::normalize_path
($path);
444 return $self->check_perm_modify($username, $path, $noerr);
446 die "unknown permission test";
450 sub check_api2_permissions
{
451 my ($self, $perm, $username, $param) = @_;
453 return 1 if !$username && $perm->{user
} eq 'world';
455 raise_perm_exc
("user != null") if !$username;
457 return 1 if $username eq 'root@pam';
459 raise_perm_exc
('user != root@pam') if !$perm;
461 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
463 return $self->exec_api2_perm_check($perm->{check
}, $username, $param)
469 # initialize environment - must be called once at program startup
471 my ($class, $type, %params) = @_;
473 $class = ref($class) || $class;
475 die "already initialized" if $pve_env;
477 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
479 $SIG{CHLD
} = $worker_reaper;
482 # cli ... command started fron command line
483 # pub ... access from public server (apache)
484 # priv ... access from private server (pvedaemon)
485 # ha ... access from HA resource manager agent (rgmanager)
496 foreach my $p (keys %params) {
497 if ($p eq 'atfork') {
498 $self->{$p} = $params{$p};
500 die "unknown option '$p'";
506 my ($sysname, $nodename) = POSIX
::uname
();
508 $nodename =~ s/\..*$//; # strip domain part, if any
510 $self->{nodename
} = $nodename;
518 die "not initialized" if !$pve_env;
523 # init_request - must be called before each RPC request
525 my ($self, %params) = @_;
527 PVE
::Cluster
::cfs_update
();
529 $self->{result_attributes
} = {};
531 my $userconfig; # we use this for regression tests
532 foreach my $p (keys %params) {
533 if ($p eq 'userconfig') {
534 $userconfig = $params{$p};
536 die "unknown parameter '$p'";
541 $self->{aclcache
} = {};
543 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
544 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
545 $self->{user_cfg
} = $cfg;
548 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
549 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
550 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
551 $self->{aclversion
} = $ucvers;
552 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
553 $self->{user_cfg
} = $cfg;
558 $self->{user_cfg
} = {};
559 die "Unable to load access control list: $err";
564 my ($self, $ip) = @_;
566 $self->{client_ip
} = $ip;
572 return $self->{client_ip
};
575 sub set_result_attrib
{
576 my ($self, $key, $value) = @_;
578 $self->{result_attributes
}->{$key} = $value;
581 sub get_result_attrib
{
582 my ($self, $key) = @_;
584 return $self->{result_attributes
}->{$key};
588 my ($self, $lang) = @_;
590 # fixme: initialize I18N
592 $self->{language
} = $lang;
598 return $self->{language
};
602 my ($self, $user) = @_;
606 $self->{user
} = $user;
612 die "user name not set\n" if !$self->{user
};
614 return $self->{user
};
617 # read/update list of active workers
618 # we move all finished tasks to the archive index,
619 # but keep aktive and most recent task in the active file.
620 # $nocheck ... consider $new_upid still running (avoid that
621 # we try to read the reult to early.
623 my ($new_upid, $nocheck) = @_;
625 my $lkfn = "/var/log/pve/tasks/.active.lock";
631 my $tasklist = PVE
::INotify
::read_file
('active');
635 my $thash = {}; # only list task once
637 my $check_task = sub {
638 my ($task, $running) = @_;
640 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
646 delete $task->{pstart
};
649 foreach my $task (@$tasklist) {
650 my $upid = $task->{upid
};
651 next if $thash->{$upid};
652 $thash->{$upid} = $task;
656 if ($new_upid && !(my $task = $thash->{$new_upid})) {
657 $task = PVE
::Tools
::upid_decode
($new_upid);
658 $task->{upid
} = $new_upid;
659 $thash->{$new_upid} = $task;
660 &$check_task($task, $nocheck);
664 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
666 my $save = defined($new_upid);
668 foreach my $task (@ta) {
669 next if $task->{endtime
};
670 $task->{endtime
} = time();
671 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
677 foreach my $task (@ta) {
678 if (!$task->{saved
}) {
679 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
688 my $filename = "/var/log/pve/tasks/index";
690 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
691 die "unable to open file '$filename' - $!\n";
692 PVE
::Tools
::safe_print
($filename, $fh, $archive);
695 die "unable to close file '$filename' - $!\n";
700 foreach my $task (@arlist) { # mark as not saved
704 my $maxsize = 50000; # about 1000 entries
705 if ($size > $maxsize) {
706 rename($filename, "$filename.1");
710 # we try to reduce the amount of data
711 # list all running tasks and task and a few others
712 # try to limit to 25 tasks
714 my $max = 25 - scalar(@$tlist);
715 foreach my $task (@ta) {
721 PVE
::INotify
::write_file
('active', $tlist) if $save;
726 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
732 my $kill_process_group = sub {
733 my ($pid, $pstart) = @_;
735 # send kill to process group (negative pid)
738 # always send signal to all pgrp members
739 kill(15, $kpid); # send TERM signal
741 # give max 5 seconds to shut down
742 for (my $i = 0; $i < 5; $i++) {
743 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
752 my ($upid, $killit) = @_;
754 my $task = PVE
::Tools
::upid_decode
($upid);
756 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
758 return 0 if !$running;
761 &$kill_process_group($task->{pid
});
768 # start long running workers
769 # STDIN is redirected to /dev/null
770 # STDOUT,STDERR are redirected to the filename returned by upid_decode
771 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
773 my ($self, $dtype, $id, $user, $function, $background) = @_;
775 $dtype = 'unknown' if !defined ($dtype);
776 $id = '' if !defined ($id);
778 $user = 'root@pve' if !defined ($user);
780 my $sync = ($self->{type
} eq 'cli' && !$background) ?
1 : 0;
785 local $SIG{TERM
} = 'IGNORE';
787 my $starttime = time ();
789 my @psync = POSIX
::pipe();
790 my @csync = POSIX
::pipe();
792 my $node = $self->{nodename
};
795 die "unable to fork worker - $!" if !defined($cpid);
797 my $workerpuid = $cpid ?
$cpid : $$;
799 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
800 die "unable to read process start time";
802 my $upid = PVE
::Tools
::upid_encode
({
803 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
804 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
808 if (!$cpid) { # child
812 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
814 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
816 # set sess/process group - we want to be able to kill the
817 # whole process group
820 POSIX
::close ($psync[0]);
821 POSIX
::close ($csync[1]);
823 $outfh = $sync ?
$psync[1] : undef;
826 PVE
::INotify
::inotify_close
();
828 if (my $atfork = $self->{atfork
}) {
832 # same algorythm as used inside SA
834 my $fd = fileno (STDIN
);
838 POSIX
::close(0) if $fd != 0;
840 die "unable to redirect STDIN - $!"
841 if !open(STDIN
, "</dev/null");
843 $outfh = PVE
::Tools
::upid_open
($upid);
848 $fd = fileno(STDOUT
);
850 POSIX
::close (1) if $fd != 1;
852 die "unable to redirect STDOUT - $!"
853 if !open(STDOUT
, ">&", $outfh);
855 STDOUT-
>autoflush (1);
857 # redirect STDERR to STDOUT
858 $fd = fileno (STDERR
);
860 POSIX
::close(2) if $fd != 2;
862 die "unable to redirect STDERR - $!"
863 if !open(STDERR
, ">&1");
865 STDERR-
>autoflush(1);
868 my $msg = "ERROR: $err";
869 POSIX
::write($psync[1], $msg, length ($msg));
870 POSIX
::close($psync[1]);
875 # sync with parent (signal that we are ready)
879 POSIX
::write($psync[1], $upid, length ($upid));
880 POSIX
::close($psync[1]);
884 # sync with parent (wait until parent is ready)
885 POSIX
::read($csync[0], $readbuf, 4096);
886 die "parent setup error\n" if $readbuf ne 'OK';
888 if ($self->{type
} eq 'ha') {
889 print "task started by HA resource agent\n";
891 eval { &$function($upid); };
897 print STDERR
"TASK ERROR: $err\n";
900 print STDERR
"TASK OK\n";
908 POSIX
::close ($psync[1]);
909 POSIX
::close ($csync[0]);
912 # sync with child (wait until child starts)
913 POSIX
::read($psync[0], $readbuf, 4096);
916 POSIX
::close($psync[0]);
917 &$register_worker($cpid, $user, $upid);
923 die "got no worker upid - start worker failed\n" if !$readbuf;
925 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
926 die "starting worker failed: $1\n";
929 if ($readbuf ne $upid) {
930 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
934 $outfh = PVE
::Tools
::upid_open
($upid);
941 POSIX
::write($csync[1], $msg, length ($msg));
942 POSIX
::close($csync[1]);
945 POSIX
::close($csync[1]);
946 kill(-9, $cpid); # make sure it gets killed
950 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
952 my $tlist = active_workers
($upid, $sync);
953 PVE
::Cluster
::broadcast_tasklist
($tlist);
962 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
963 # always send signal to all pgrp members
965 if ($int_count < 3) {
966 kill(15, $kpid); # send TERM signal
968 kill(9, $kpid); # send KILL signal
972 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
974 my $select = new IO
::Select
;
975 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
978 while ($select->count) {
979 my @handles = $select->can_read(1);
980 if (scalar(@handles)) {
981 my $count = sysread ($handles[0], $readbuf, 4096);
982 if (!defined ($count)) {
984 die "sync pipe read error: $err\n";
986 last if $count == 0; # eof
989 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
992 if ($data =~ m/^TASK OK$/) {
994 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
1005 # some commands daemonize without closing stdout
1006 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
1012 POSIX
::close($psync[0]);
1014 if ($outbuf) { # just to be sure
1017 print $outfh $outbuf;
1023 print STDERR
"$err\n";
1025 print $outfh "TASK ERROR: $err\n";
1029 &$kill_process_group($cpid, $pstart); # make sure it gets killed
1035 &$log_task_result($upid, $user, $res);
1038 return wantarray ?
($upid, $res) : $upid;