]>
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)
33 my $log_task_result = sub {
34 my ($upid, $user, $status) = @_;
36 my $msg = 'successful';
39 my $ec = $status >> 8;
40 my $ic = $status & 255;
41 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
44 my $tlist = active_workers
($upid);
45 PVE
::Cluster
::broadcast_tasklist
($tlist);
47 foreach my $t (@$tlist) {
48 if ($t->{upid
} eq $upid) {
53 if ($task && $task->{status
}) {
54 $msg = $task->{status
};
56 PVE
::Cluster
::log_msg
($pri, $user, "end task $upid $msg");
59 my $worker_reaper = sub {
61 foreach my $pid (keys %$WORKER_PIDS) {
62 my $waitpid = waitpid ($pid, WNOHANG
);
63 if (defined($waitpid) && ($waitpid == $pid)) {
64 my $info = $WORKER_PIDS->{$pid};
65 if ($info && $info->{upid
} && $info->{user
}) {
66 &$log_task_result($info->{upid
}, $info->{user
}, $?);
68 delete ($WORKER_PIDS->{$pid});
73 my $register_worker = sub {
74 my ($pid, $user, $upid) = @_;
78 # do not register if already finished
79 my $waitpid = waitpid ($pid, WNOHANG
);
80 if (defined($waitpid) && ($waitpid == $pid)) {
81 delete ($WORKER_PIDS->{$pid});
85 $WORKER_PIDS->{$pid} = {
93 my $compile_acl_path = sub {
94 my ($self, $user, $path) = @_;
96 my $cfg = $self->{user_cfg
};
98 return undef if !$cfg->{roles
};
100 die "internal error" if $user eq 'root@pam';
102 my $cache = $self->{aclcache
};
103 $cache->{$user} = {} if !$cache->{$user};
104 my $data = $cache->{$user};
106 if (!$data->{poolroles
}) {
107 $data->{poolroles
} = {};
109 foreach my $pool (keys %{$cfg->{pools
}}) {
110 my $d = $cfg->{pools
}->{$pool};
111 my @ra = PVE
::AccessControl
::roles
($cfg, $user, "/pool/$pool"); # pool roles
112 next if !scalar(@ra);
113 foreach my $vmid (keys %{$d->{vms
}}) {
115 $data->{poolroles
}->{"/vms/$vmid"}->{$role} = 1;
118 foreach my $storeid (keys %{$d->{storage
}}) {
120 $data->{poolroles
}->{"/storage/$storeid"}->{$role} = 1;
126 my @ra = PVE
::AccessControl
::roles
($cfg, $user, $path);
128 # apply roles inherited from pools
129 # Note: assume we do not want to propagate those privs
130 if ($data->{poolroles
}->{$path}) {
131 if (!($ra[0] && $ra[0] eq 'NoAccess')) {
132 if ($data->{poolroles
}->{$path}->{NoAccess
}) {
135 foreach my $role (keys %{$data->{poolroles
}->{$path}}) {
142 $data->{roles
}->{$path} = [ @ra ];
145 foreach my $role (@ra) {
146 if (my $privset = $cfg->{roles
}->{$role}) {
147 foreach my $p (keys %$privset) {
152 $data->{privs
}->{$path} = $privs;
158 my ($self, $user, $path) = @_;
160 if ($user eq 'root@pam') { # root can do anything
161 return ('Administrator');
164 $user = PVE
::AccessControl
::verify_username
($user, 1);
167 my $cache = $self->{aclcache
};
168 $cache->{$user} = {} if !$cache->{$user};
170 my $acl = $cache->{$user};
172 my $roles = $acl->{roles
}->{$path};
173 return @$roles if $roles;
175 &$compile_acl_path($self, $user, $path);
176 $roles = $acl->{roles
}->{$path} || [];
181 my ($self, $user, $path) = @_;
183 if ($user eq 'root@pam') { # root can do anything
184 my $cfg = $self->{user_cfg
};
185 return $cfg->{roles
}->{'Administrator'};
188 $user = PVE
::AccessControl
::verify_username
($user, 1);
191 my $cache = $self->{aclcache
};
192 $cache->{$user} = {} if !$cache->{$user};
194 my $acl = $cache->{$user};
196 my $perm = $acl->{privs
}->{$path};
197 return $perm if $perm;
199 return &$compile_acl_path($self, $user, $path);
203 my ($self, $user, $path, $privs, $noerr) = @_;
205 my $perm = $self->permissions($user, $path);
207 foreach my $priv (@$privs) {
208 PVE
::AccessControl
::verify_privname
($priv);
209 if (!$perm->{$priv}) {
210 return undef if $noerr;
211 raise_perm_exc
("$path, $priv");
219 my ($self, $user, $path, $privs, $noerr) = @_;
221 my $perm = $self->permissions($user, $path);
224 foreach my $priv (@$privs) {
225 PVE
::AccessControl
::verify_privname
($priv);
226 if ($perm->{$priv}) {
234 return undef if $noerr;
236 raise_perm_exc
("$path, " . join("|", @$privs));
240 my ($self, $username, $path, $privs, $any, $noerr) = @_;
242 return $self->check_any($username, $path, $privs, $noerr);
244 return $self->check($username, $path, $privs, $noerr);
248 sub check_user_enabled
{
249 my ($self, $user, $noerr) = @_;
251 my $cfg = $self->{user_cfg
};
252 return PVE
::AccessControl
::check_user_enabled
($cfg, $user, $noerr);
255 sub check_user_exist
{
256 my ($self, $user, $noerr) = @_;
258 my $cfg = $self->{user_cfg
};
259 return PVE
::AccessControl
::check_user_exist
($cfg, $user, $noerr);
262 sub check_pool_exist
{
263 my ($self, $pool, $noerr) = @_;
265 my $cfg = $self->{user_cfg
};
267 return 1 if $cfg->{pools
}->{$pool};
269 return undef if $noerr;
271 raise_perm_exc
("pool '$pool' does not exist");
275 my ($self, $user, $vmid, $pool, $privs, $any, $noerr) = @_;
277 my $cfg = $self->{user_cfg
};
280 return if $self->check_full($user, "/pool/$pool", $privs, $any, 1);
282 return $self->check_full($user, "/vms/$vmid", $privs, $any, $noerr);
285 sub check_volume_access
{
286 my ($self, $user, $storecfg, $vmid, $volid) = @_;
288 # test if we have read access to volid
290 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
292 my ($vtype, undef, $ownervm) = PVE
::Storage
::parse_volname
($storecfg, $volid);
293 if ($vtype eq 'iso' || $vtype eq 'vztmpl') {
294 # we simply allow access
295 } elsif (defined($ownervm) && defined($vmid) && ($ownervm == $vmid)) {
296 # we are owner - allow access
297 } elsif ($vtype eq 'backup' && $ownervm) {
298 $self->check($user, "/storage/$sid", ['Datastore.AllocateSpace']);
299 $self->check($user, "/vms/$ownervm", ['VM.Backup']);
301 # allow if we are Datastore administrator
302 $self->check($user, "/storage/$sid", ['Datastore.Allocate']);
305 die "Only root can pass arbitrary filesystem paths."
306 if $user ne 'root@pam';
312 sub is_group_member
{
313 my ($self, $group, $user) = @_;
315 my $cfg = $self->{user_cfg
};
317 return 0 if !$cfg->{groups
}->{$group};
319 return defined($cfg->{groups
}->{$group}->{users
}->{$user});
323 my ($self, $user, $privs, $any) = @_;
325 my $cfg = $self->{user_cfg
};
328 foreach my $group (keys %{$cfg->{groups
}}) {
329 my $path = "/access/groups/$group";
330 if ($self->check_full($user, $path, $privs, $any, 1)) {
331 $groups->{$group} = $cfg->{groups
}->{$group};
338 sub group_member_join
{
339 my ($self, $grouplist) = @_;
343 my $cfg = $self->{user_cfg
};
344 foreach my $group (@$grouplist) {
345 my $data = $cfg->{groups
}->{$group};
347 foreach my $user (keys %{$data->{users
}}) {
355 sub check_perm_modify
{
356 my ($self, $username, $path, $noerr) = @_;
358 return $self->check($username, '/access', [ 'Permissions.Modify' ], $noerr) if !$path;
360 my $testperms = [ 'Permissions.Modify' ];
361 if ($path =~ m
|^/storage/.+$|) {
362 push @$testperms, 'Datastore.Allocate';
363 } elsif ($path =~ m
|^/vms/.+$|) {
364 push @$testperms, 'VM.Allocate';
365 } elsif ($path =~ m
|^/pool/.+$|) {
366 push @$testperms, 'Pool.Allocate';
369 return $self->check_any($username, $path, $testperms, $noerr);
372 sub exec_api2_perm_check
{
373 my ($self, $check, $username, $param, $noerr) = @_;
375 # syslog("info", "CHECK " . join(', ', @$check));
378 my $test = $check->[$ind++];
379 die "no permission test specified" if !$test;
381 if ($test eq 'and') {
382 while (my $subcheck = $check->[$ind++]) {
383 $self->exec_api2_perm_check($subcheck, $username, $param);
386 } elsif ($test eq 'or') {
387 while (my $subcheck = $check->[$ind++]) {
388 return 1 if $self->exec_api2_perm_check($subcheck, $username, $param, 1);
392 } elsif ($test eq 'perm') {
393 my ($t, $tmplpath, $privs, %options) = @$check;
394 my $any = $options{any
};
395 die "missing parameters" if !($tmplpath && $privs);
396 my $require_param = $options{require_param
};
397 if ($require_param && !defined($param->{$require_param})) {
401 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
402 $path = PVE
::AccessControl
::normalize_path
($path);
403 return $self->check_full($username, $path, $privs, $any, $noerr);
404 } elsif ($test eq 'userid-group') {
405 my $userid = $param->{userid
};
406 my ($t, $privs, %options) = @$check;
407 return 0 if !$options{groups_param
} && !$self->check_user_exist($userid, $noerr);
408 if (!$self->check_any($username, "/access/groups", $privs, 1)) {
409 my $groups = $self->filter_groups($username, $privs, 1);
410 if ($options{groups_param
}) {
411 my @group_param = PVE
::Tools
::split_list
($param->{groups
});
412 raise_perm_exc
("/access/groups, " . join("|", @$privs)) if !scalar(@group_param);
413 foreach my $pg (@group_param) {
414 raise_perm_exc
("/access/groups/$pg, " . join("|", @$privs))
418 my $allowed_users = $self->group_member_join([keys %$groups]);
419 if (!$allowed_users->{$userid}) {
426 } elsif ($test eq 'userid-param') {
427 my ($userid, undef, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
428 my ($t, $subtest) = @$check;
429 die "missing parameters" if !$subtest;
430 if ($subtest eq 'self') {
431 return 0 if !$self->check_user_exist($userid, $noerr);
432 return 1 if $username eq $userid;
435 } elsif ($subtest eq 'Realm.AllocateUser') {
436 my $path = "/access/realm/$realm";
437 return $self->check($username, $path, ['Realm.AllocateUser'], $noerr);
439 die "unknown userid-param test";
441 } elsif ($test eq 'perm-modify') {
442 my ($t, $tmplpath) = @$check;
443 my $path = PVE
::Tools
::template_replace
($tmplpath, $param);
444 $path = PVE
::AccessControl
::normalize_path
($path);
445 return $self->check_perm_modify($username, $path, $noerr);
447 die "unknown permission test";
451 sub check_api2_permissions
{
452 my ($self, $perm, $username, $param) = @_;
454 return 1 if !$username && $perm->{user
} eq 'world';
456 raise_perm_exc
("user != null") if !$username;
458 return 1 if $username eq 'root@pam';
460 raise_perm_exc
('user != root@pam') if !$perm;
462 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
464 return $self->exec_api2_perm_check($perm->{check
}, $username, $param)
470 # initialize environment - must be called once at program startup
472 my ($class, $type, %params) = @_;
474 $class = ref($class) || $class;
476 die "already initialized" if $pve_env;
478 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
480 $SIG{CHLD
} = $worker_reaper;
483 # cli ... command started fron command line
484 # pub ... access from public server (apache)
485 # priv ... access from private server (pvedaemon)
486 # ha ... access from HA resource manager agent (rgmanager)
497 foreach my $p (keys %params) {
498 if ($p eq 'atfork') {
499 $self->{$p} = $params{$p};
501 die "unknown option '$p'";
507 my ($sysname, $nodename) = POSIX
::uname
();
509 $nodename =~ s/\..*$//; # strip domain part, if any
511 $self->{nodename
} = $nodename;
519 die "not initialized" if !$pve_env;
524 # init_request - must be called before each RPC request
526 my ($self, %params) = @_;
528 PVE
::Cluster
::cfs_update
();
530 $self->{result_attributes
} = {};
532 my $userconfig; # we use this for regression tests
533 foreach my $p (keys %params) {
534 if ($p eq 'userconfig') {
535 $userconfig = $params{$p};
537 die "unknown parameter '$p'";
542 $self->{aclcache
} = {};
544 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
545 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
546 $self->{user_cfg
} = $cfg;
549 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
550 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
551 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
552 $self->{aclversion
} = $ucvers;
553 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
554 $self->{user_cfg
} = $cfg;
559 $self->{user_cfg
} = {};
560 die "Unable to load access control list: $err";
565 my ($self, $ip) = @_;
567 $self->{client_ip
} = $ip;
573 return $self->{client_ip
};
576 sub set_result_attrib
{
577 my ($self, $key, $value) = @_;
579 $self->{result_attributes
}->{$key} = $value;
582 sub get_result_attrib
{
583 my ($self, $key) = @_;
585 return $self->{result_attributes
}->{$key};
589 my ($self, $lang) = @_;
591 # fixme: initialize I18N
593 $self->{language
} = $lang;
599 return $self->{language
};
603 my ($self, $user) = @_;
607 $self->{user
} = $user;
613 die "user name not set\n" if !$self->{user
};
615 return $self->{user
};
622 # read/update list of active workers
623 # we move all finished tasks to the archive index,
624 # but keep aktive and most recent task in the active file.
625 # $nocheck ... consider $new_upid still running (avoid that
626 # we try to read the reult to early.
628 my ($new_upid, $nocheck) = @_;
630 my $lkfn = "/var/log/pve/tasks/.active.lock";
636 my $tasklist = PVE
::INotify
::read_file
('active');
640 my $thash = {}; # only list task once
642 my $check_task = sub {
643 my ($task, $running) = @_;
645 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
651 delete $task->{pstart
};
654 foreach my $task (@$tasklist) {
655 my $upid = $task->{upid
};
656 next if $thash->{$upid};
657 $thash->{$upid} = $task;
661 if ($new_upid && !(my $task = $thash->{$new_upid})) {
662 $task = PVE
::Tools
::upid_decode
($new_upid);
663 $task->{upid
} = $new_upid;
664 $thash->{$new_upid} = $task;
665 &$check_task($task, $nocheck);
669 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
671 my $save = defined($new_upid);
673 foreach my $task (@ta) {
674 next if $task->{endtime
};
675 $task->{endtime
} = time();
676 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
682 foreach my $task (@ta) {
683 if (!$task->{saved
}) {
684 $archive .= sprintf("%s %08X %s\n", $task->{upid
}, $task->{endtime
}, $task->{status
});
693 my $filename = "/var/log/pve/tasks/index";
695 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
696 die "unable to open file '$filename' - $!\n";
697 PVE
::Tools
::safe_print
($filename, $fh, $archive);
700 die "unable to close file '$filename' - $!\n";
705 foreach my $task (@arlist) { # mark as not saved
709 my $maxsize = 50000; # about 1000 entries
710 if ($size > $maxsize) {
711 rename($filename, "$filename.1");
715 # we try to reduce the amount of data
716 # list all running tasks and task and a few others
717 # try to limit to 25 tasks
719 my $max = 25 - scalar(@$tlist);
720 foreach my $task (@ta) {
726 PVE
::INotify
::write_file
('active', $tlist) if $save;
731 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
737 my $kill_process_group = sub {
738 my ($pid, $pstart) = @_;
740 # send kill to process group (negative pid)
743 # always send signal to all pgrp members
744 kill(15, $kpid); # send TERM signal
746 # give max 5 seconds to shut down
747 for (my $i = 0; $i < 5; $i++) {
748 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
757 my ($upid, $killit) = @_;
759 my $task = PVE
::Tools
::upid_decode
($upid);
761 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
763 return 0 if !$running;
766 &$kill_process_group($task->{pid
});
773 # start long running workers
774 # STDIN is redirected to /dev/null
775 # STDOUT,STDERR are redirected to the filename returned by upid_decode
776 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
778 my ($self, $dtype, $id, $user, $function, $background) = @_;
780 $dtype = 'unknown' if !defined ($dtype);
781 $id = '' if !defined ($id);
783 $user = 'root@pve' if !defined ($user);
785 my $sync = ($self->{type
} eq 'cli' && !$background) ?
1 : 0;
790 local $SIG{TERM
} = 'IGNORE';
792 my $starttime = time ();
794 my @psync = POSIX
::pipe();
795 my @csync = POSIX
::pipe();
797 my $node = $self->{nodename
};
800 die "unable to fork worker - $!" if !defined($cpid);
802 my $workerpuid = $cpid ?
$cpid : $$;
804 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
805 die "unable to read process start time";
807 my $upid = PVE
::Tools
::upid_encode
({
808 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
809 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
813 if (!$cpid) { # child
818 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
820 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
822 # set sess/process group - we want to be able to kill the
823 # whole process group
826 POSIX
::close ($psync[0]);
827 POSIX
::close ($csync[1]);
829 $outfh = $sync ?
$psync[1] : undef;
832 PVE
::INotify
::inotify_close
();
834 if (my $atfork = $self->{atfork
}) {
838 # same algorythm as used inside SA
840 my $fd = fileno (STDIN
);
844 POSIX
::close(0) if $fd != 0;
846 die "unable to redirect STDIN - $!"
847 if !open(STDIN
, "</dev/null");
849 $outfh = PVE
::Tools
::upid_open
($upid);
854 $fd = fileno(STDOUT
);
856 POSIX
::close (1) if $fd != 1;
858 die "unable to redirect STDOUT - $!"
859 if !open(STDOUT
, ">&", $outfh);
861 STDOUT-
>autoflush (1);
863 # redirect STDERR to STDOUT
864 $fd = fileno (STDERR
);
866 POSIX
::close(2) if $fd != 2;
868 die "unable to redirect STDERR - $!"
869 if !open(STDERR
, ">&1");
871 STDERR-
>autoflush(1);
874 my $msg = "ERROR: $err";
875 POSIX
::write($psync[1], $msg, length ($msg));
876 POSIX
::close($psync[1]);
881 # sync with parent (signal that we are ready)
885 POSIX
::write($psync[1], $upid, length ($upid));
886 POSIX
::close($psync[1]);
890 # sync with parent (wait until parent is ready)
891 POSIX
::read($csync[0], $readbuf, 4096);
892 die "parent setup error\n" if $readbuf ne 'OK';
894 if ($self->{type
} eq 'ha') {
895 print "task started by HA resource agent\n";
897 eval { &$function($upid); };
903 print STDERR
"TASK ERROR: $err\n";
906 print STDERR
"TASK OK\n";
914 POSIX
::close ($psync[1]);
915 POSIX
::close ($csync[0]);
918 # sync with child (wait until child starts)
919 POSIX
::read($psync[0], $readbuf, 4096);
922 POSIX
::close($psync[0]);
923 &$register_worker($cpid, $user, $upid);
929 die "got no worker upid - start worker failed\n" if !$readbuf;
931 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
932 die "starting worker failed: $1\n";
935 if ($readbuf ne $upid) {
936 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
940 $outfh = PVE
::Tools
::upid_open
($upid);
947 POSIX
::write($csync[1], $msg, length ($msg));
948 POSIX
::close($csync[1]);
951 POSIX
::close($csync[1]);
952 kill(-9, $cpid); # make sure it gets killed
956 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
958 my $tlist = active_workers
($upid, $sync);
959 PVE
::Cluster
::broadcast_tasklist
($tlist);
968 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
969 # always send signal to all pgrp members
971 if ($int_count < 3) {
972 kill(15, $kpid); # send TERM signal
974 kill(9, $kpid); # send KILL signal
978 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
980 my $select = new IO
::Select
;
981 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
984 while ($select->count) {
985 my @handles = $select->can_read(1);
986 if (scalar(@handles)) {
987 my $count = sysread ($handles[0], $readbuf, 4096);
988 if (!defined ($count)) {
990 die "sync pipe read error: $err\n";
992 last if $count == 0; # eof
995 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
998 if ($data =~ m/^TASK OK$/) {
1000 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
1001 print STDERR
"$1\n";
1011 # some commands daemonize without closing stdout
1012 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
1018 POSIX
::close($psync[0]);
1020 if ($outbuf) { # just to be sure
1023 print $outfh $outbuf;
1029 print STDERR
"$err\n";
1031 print $outfh "TASK ERROR: $err\n";
1035 &$kill_process_group($cpid, $pstart); # make sure it gets killed
1041 &$log_task_result($upid, $user, $res);
1044 return wantarray ?
($upid, $res) : $upid;