1 package PVE
::API2
::AccessControl
;
9 use PVE
::Exception
qw(raise raise_perm_exc raise_param_exc);
11 use PVE
::RPCEnvironment
;
12 use PVE
::Cluster
qw(cfs_read_file);
13 use PVE
::DataCenterConfig
;
15 use PVE
::AccessControl
;
16 use PVE
::JSONSchema
qw(get_standard_option);
17 use PVE
::API2
::Domains
;
22 use PVE
::Auth
::Plugin
;
26 my $u2f_available = 0;
32 use base
qw(PVE::RESTHandler);
34 __PACKAGE__-
>register_method ({
35 subclass
=> "PVE::API2::User",
39 __PACKAGE__-
>register_method ({
40 subclass
=> "PVE::API2::Group",
44 __PACKAGE__-
>register_method ({
45 subclass
=> "PVE::API2::Role",
49 __PACKAGE__-
>register_method ({
50 subclass
=> "PVE::API2::ACL",
54 __PACKAGE__-
>register_method ({
55 subclass
=> "PVE::API2::Domains",
59 __PACKAGE__-
>register_method ({
63 description
=> "Directory index.",
68 additionalProperties
=> 0,
76 subdir
=> { type
=> 'string' },
79 links
=> [ { rel
=> 'child', href
=> "{subdir}" } ],
86 my $ma = __PACKAGE__-
>method_attributes();
88 foreach my $info (@$ma) {
89 next if !$info->{subclass
};
91 my $subpath = $info->{match_re
}->[0];
93 push @$res, { subdir
=> $subpath };
96 push @$res, { subdir
=> 'ticket' };
97 push @$res, { subdir
=> 'password' };
103 my $verify_auth = sub {
104 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs) = @_;
106 my $normpath = PVE
::AccessControl
::normalize_path
($path);
109 if (($ticketuser = PVE
::AccessControl
::verify_ticket
($pw_or_ticket, 1)) &&
110 ($ticketuser eq $username)) {
112 } elsif (PVE
::AccessControl
::verify_vnc_ticket
($pw_or_ticket, $username, $normpath, 1)) {
115 $username = PVE
::AccessControl
::authenticate_user
($username, $pw_or_ticket, $otp);
118 my $privlist = [ PVE
::Tools
::split_list
($privs) ];
119 if (!($normpath && scalar(@$privlist) && $rpcenv->check($username, $normpath, $privlist))) {
120 die "no permission ($path, $privs)\n";
123 return { username
=> $username };
126 my $create_ticket = sub {
127 my ($rpcenv, $username, $pw_or_ticket, $otp) = @_;
129 my ($ticketuser, undef, $tfa_info) = PVE
::AccessControl
::verify_ticket
($pw_or_ticket, 1);
130 if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
131 if (defined($tfa_info)) {
132 die "incomplete ticket\n";
134 # valid ticket. Note: root@pam can create tickets for other users
136 ($username, $tfa_info) = PVE
::AccessControl
::authenticate_user
($username, $pw_or_ticket, $otp);
140 my $ticket_data = $username;
141 if (defined($tfa_info)) {
143 if ($tfa_info->{type
} eq 'u2f') {
144 my $u2finfo = $tfa_info->{data
};
145 my $u2f = get_u2f_instance
($rpcenv, $u2finfo->@{qw(publicKey keyHandle)});
146 my $challenge = $u2f->auth_challenge()
147 or die "failed to get u2f challenge\n";
148 $challenge = decode_json
($challenge);
149 $extra{U2FChallenge
} = $challenge;
150 $ticket_data = "u2f!$username!$challenge->{challenge}";
152 # General half-login / 'missing 2nd factor' ticket:
153 $ticket_data = "tfa!$username";
157 my $ticket = PVE
::AccessControl
::assemble_ticket
($ticket_data);
158 my $csrftoken = PVE
::AccessControl
::assemble_csrf_prevention_token
($username);
162 username
=> $username,
163 CSRFPreventionToken
=> $csrftoken,
168 my $compute_api_permission = sub {
169 my ($rpcenv, $authuser) = @_;
171 my $usercfg = $rpcenv->{user_cfg
};
175 vms
=> qr/VM\.|Permissions\.Modify/,
176 access
=> qr/(User|Group)\.|Permissions\.Modify/,
177 storage
=> qr/Datastore\.|Permissions\.Modify/,
178 nodes
=> qr/Sys\.|Permissions\.Modify/,
179 dc
=> qr/Sys\.Audit/,
181 map { $res->{$_} = {} } keys %$priv_re_map;
183 my $required_paths = ['/', '/nodes', '/access/groups', '/vms', '/storage'];
185 my $checked_paths = {};
186 foreach my $path (@$required_paths, keys %{$usercfg->{acl
}}) {
187 next if $checked_paths->{$path};
188 $checked_paths->{$path} = 1;
190 my $path_perm = $rpcenv->permissions($authuser, $path);
192 my $toplevel = ($path =~ /^\/(\w
+)/) ?
$1 : 'dc';
193 if ($toplevel eq 'pool') {
194 foreach my $priv (keys %$path_perm) {
195 if ($priv =~ m/^VM\./) {
196 $res->{vms
}->{$priv} = 1;
197 } elsif ($priv =~ m/^Datastore\./) {
198 $res->{storage
}->{$priv} = 1;
199 } elsif ($priv eq 'Permissions.Modify') {
200 $res->{storage
}->{$priv} = 1;
201 $res->{vms
}->{$priv} = 1;
205 my $priv_regex = $priv_re_map->{$toplevel} // next;
206 foreach my $priv (keys %$path_perm) {
207 next if $priv !~ m/^($priv_regex)/;
208 $res->{$toplevel}->{$priv} = 1;
216 __PACKAGE__-
>register_method ({
217 name
=> 'get_ticket',
220 permissions
=> { user
=> 'world' },
221 description
=> "Dummy. Useful for formatters which want to provide a login page.",
223 additionalProperties
=> 0,
225 returns
=> { type
=> "null" },
226 code
=> sub { return undef; }});
228 __PACKAGE__-
>register_method ({
229 name
=> 'create_ticket',
233 description
=> "You need to pass valid credientials.",
236 protected
=> 1, # else we can't access shadow files
237 description
=> "Create or verify authentication ticket.",
239 additionalProperties
=> 0,
242 description
=> "User name",
245 completion
=> \
&PVE
::AccessControl
::complete_username
,
247 realm
=> get_standard_option
('realm', {
248 description
=> "You can optionally pass the realm using this parameter. Normally the realm is simply added to the username <username>\@<relam>.",
250 completion
=> \
&PVE
::AccessControl
::complete_realm
,
253 description
=> "The secret password. This can also be a valid ticket.",
257 description
=> "One-time password for Two-factor authentication.",
262 description
=> "Verify ticket, and check if user have access 'privs' on 'path'",
269 description
=> "Verify ticket, and check if user have access 'privs' on 'path'",
270 type
=> 'string' , format
=> 'pve-priv-list',
280 username
=> { type
=> 'string' },
281 ticket
=> { type
=> 'string', optional
=> 1},
282 CSRFPreventionToken
=> { type
=> 'string', optional
=> 1 },
283 clustername
=> { type
=> 'string', optional
=> 1 },
284 # cap => computed api permissions, unless there's a u2f challenge
290 my $username = $param->{username
};
291 $username .= "\@$param->{realm}" if $param->{realm
};
293 my $rpcenv = PVE
::RPCEnvironment
::get
();
297 # test if user exists and is enabled
298 $rpcenv->check_user_enabled($username);
300 if ($param->{path
} && $param->{privs
}) {
301 $res = &$verify_auth($rpcenv, $username, $param->{password
}, $param->{otp
},
302 $param->{path
}, $param->{privs
});
304 $res = &$create_ticket($rpcenv, $username, $param->{password
}, $param->{otp
});
308 my $clientip = $rpcenv->get_client_ip() || '';
309 syslog
('err', "authentication failure; rhost=$clientip user=$username msg=$err");
310 # do not return any info to prevent user enumeration attacks
311 die PVE
::Exception-
>new("authentication failure\n", code
=> 401);
314 $res->{cap
} = &$compute_api_permission($rpcenv, $username)
315 if !defined($res->{NeedTFA
});
317 my $clinfo = PVE
::Cluster
::get_clinfo
();
318 if ($clinfo->{cluster
}->{name
} && $rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
319 $res->{clustername
} = $clinfo->{cluster
}->{name
};
322 PVE
::Cluster
::log_msg
('info', 'root@pam', "successful auth for user '$username'");
327 __PACKAGE__-
>register_method ({
328 name
=> 'change_password',
332 description
=> "Each user is allowed to change his own password. A user can change the password of another user if he has 'Realm.AllocateUser' (on the realm of user <userid>) and 'User.Modify' permission on /access/groups/<group> on a group where user <userid> is member of.",
334 ['userid-param', 'self'],
336 [ 'userid-param', 'Realm.AllocateUser'],
337 [ 'userid-group', ['User.Modify']]
341 protected
=> 1, # else we can't access shadow files
342 description
=> "Change user password.",
344 additionalProperties
=> 0,
346 userid
=> get_standard_option
('userid-completed'),
348 description
=> "The new password.",
355 returns
=> { type
=> "null" },
359 my $rpcenv = PVE
::RPCEnvironment
::get
();
360 my $authuser = $rpcenv->get_user();
362 my ($userid, $ruid, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
364 $rpcenv->check_user_exist($userid);
366 if ($authuser eq 'root@pam') {
367 # OK - root can change anything
369 if ($authuser eq $userid) {
370 $rpcenv->check_user_enabled($userid);
371 # OK - each user can change its own password
373 # only root may change root password
374 raise_perm_exc
() if $userid eq 'root@pam';
375 # do not allow to change system user passwords
376 raise_perm_exc
() if $realm eq 'pam';
380 PVE
::AccessControl
::domain_set_password
($realm, $ruid, $param->{password
});
382 PVE
::Cluster
::log_msg
('info', 'root@pam', "changed password for user '$userid'");
387 sub get_u2f_config
() {
388 die "u2f support not available\n" if !$u2f_available;
390 my $dc = cfs_read_file
('datacenter.cfg');
391 my $u2f = $dc->{u2f
};
392 die "u2f not configured in datacenter.cfg\n" if !$u2f;
396 sub get_u2f_instance
{
397 my ($rpcenv, $publicKey, $keyHandle) = @_;
399 # We store the public key base64 encoded (as the api provides it in binary)
400 $publicKey = decode_base64
($publicKey) if defined($publicKey);
402 my $u2fconfig = get_u2f_config
();
403 my $u2f = PVE
::U2F-
>new();
405 # via the 'Host' header (in case a node has multiple hosts available).
406 my $origin = $u2fconfig->{origin
};
407 if (!defined($origin)) {
408 $origin = $rpcenv->get_request_host(1);
410 $origin = "https://$origin";
412 die "failed to figure out u2f origin\n";
416 my $appid = $u2fconfig->{appid
} // $origin;
417 $u2f->set_appid($appid);
418 $u2f->set_origin($origin);
419 $u2f->set_publicKey($publicKey) if defined($publicKey);
420 $u2f->set_keyHandle($keyHandle) if defined($keyHandle);
424 sub verify_user_tfa_config
{
425 my ($type, $tfa_cfg, $value) = @_;
427 if (!defined($type)) {
428 die "missing tfa 'type'\n";
431 if ($type ne 'oath') {
432 die "invalid type for custom tfa authentication\n";
435 my $secret = $tfa_cfg->{keys}
436 or die "missing TOTP secret\n";
437 $tfa_cfg = $tfa_cfg->{config
};
438 # Copy the hash to verify that we have no unexpected keys without modifying the original hash.
439 $tfa_cfg = {%$tfa_cfg};
441 # We can only verify 1 secret but oath_verify_otp allows multiple:
442 if (scalar(PVE
::Tools
::split_list
($secret)) != 1) {
443 die "only exactly one secret key allowed\n";
446 my $digits = delete($tfa_cfg->{digits
}) // 6;
447 my $step = delete($tfa_cfg->{step
}) // 30;
449 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
451 if (length(my $more = join(', ', keys %$tfa_cfg))) {
452 die "unexpected tfa config keys: $more\n";
455 PVE
::OTP
::oath_verify_otp
($value, $secret, $step, $digits);
458 __PACKAGE__-
>register_method ({
459 name
=> 'change_tfa',
463 description
=> 'A user can change their own u2f or totp token.',
465 ['userid-param', 'self'],
467 [ 'userid-param', 'Realm.AllocateUser'],
468 [ 'userid-group', ['User.Modify']]
472 protected
=> 1, # else we can't access shadow files
473 description
=> "Change user u2f authentication.",
475 additionalProperties
=> 0,
477 userid
=> get_standard_option
('userid', {
478 completion
=> \
&PVE
::AccessControl
::complete_username
,
481 optional
=> 1, # Only required if not root@pam
482 description
=> "The current password.",
488 description
=> 'The action to perform',
490 enum
=> [qw(delete new confirm)],
495 'Either the the response to the current u2f registration challenge,'
496 .' or, when adding TOTP, the currently valid TOTP value.',
501 description
=> 'When adding TOTP, the shared secret value.',
503 format
=> 'pve-tfa-secret',
507 description
=> 'A TFA configuration. This must currently be of type TOTP of not set at all.',
509 format
=> 'pve-tfa-config',
514 returns
=> { type
=> 'object' },
518 my $rpcenv = PVE
::RPCEnvironment
::get
();
519 my $authuser = $rpcenv->get_user();
521 my $action = delete $param->{action
};
522 my $response = delete $param->{response
};
523 my $password = delete($param->{password
}) // '';
524 my $key = delete($param->{key
});
525 my $config = delete($param->{config
});
527 my ($userid, $ruid, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
528 $rpcenv->check_user_exist($userid);
530 # Only root may modify root
531 raise_perm_exc
() if $userid eq 'root@pam' && $authuser ne 'root@pam';
533 # Regular users need to confirm their password to change u2f settings.
534 if ($authuser ne 'root@pam') {
535 raise_param_exc
({ 'password' => 'password is required to modify u2f data' })
536 if !defined($password);
537 my $domain_cfg = cfs_read_file
('domains.cfg');
538 my $cfg = $domain_cfg->{ids
}->{$realm};
539 die "auth domain '$realm' does not exists\n" if !$cfg;
540 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
541 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
544 if ($action eq 'delete') {
545 PVE
::AccessControl
::user_set_tfa
($userid, $realm, undef, undef);
546 PVE
::Cluster
::log_msg
('info', $authuser, "deleted u2f data for user '$userid'");
547 } elsif ($action eq 'new') {
548 if (defined($config)) {
549 $config = PVE
::Auth
::Plugin
::parse_tfa_config
($config);
550 my $type = delete($config->{type
});
555 verify_user_tfa_config
($type, $tfa_cfg, $response);
556 PVE
::AccessControl
::user_set_tfa
($userid, $realm, $type, $tfa_cfg);
558 # The default is U2F:
559 my $u2f = get_u2f_instance
($rpcenv);
560 my $challenge = $u2f->registration_challenge()
561 or raise
("failed to get u2f challenge");
562 $challenge = decode_json
($challenge);
563 PVE
::AccessControl
::user_set_tfa
($userid, $realm, 'u2f', $challenge);
566 } elsif ($action eq 'confirm') {
567 raise_param_exc
({ 'response' => "confirm action requires the 'response' parameter to be set" })
568 if !defined($response);
570 my ($type, $u2fdata) = PVE
::AccessControl
::user_get_tfa
($userid, $realm);
571 raise
("no u2f data available")
572 if (!defined($type) || $type ne 'u2f');
574 my $challenge = $u2fdata->{challenge
}
575 or raise
("no active challenge");
577 my $u2f = get_u2f_instance
($rpcenv);
578 $u2f->set_challenge($challenge);
579 my ($keyHandle, $publicKey) = $u2f->registration_verify($response);
580 PVE
::AccessControl
::user_set_tfa
($userid, $realm, 'u2f', {
581 keyHandle
=> $keyHandle,
582 publicKey
=> $publicKey, # already base64 encoded
585 die "invalid action: $action\n";
591 __PACKAGE__-
>register_method({
592 name
=> 'verify_tfa',
595 permissions
=> { user
=> 'all' },
596 protected
=> 1, # else we can't access shadow files
597 description
=> 'Finish a u2f challenge.',
599 additionalProperties
=> 0,
603 description
=> 'The response to the current authentication challenge.',
610 ticket
=> { type
=> 'string' },
617 my $rpcenv = PVE
::RPCEnvironment
::get
();
618 my $authuser = $rpcenv->get_user();
619 my ($username, undef, $realm) = PVE
::AccessControl
::verify_username
($authuser);
621 my ($tfa_type, $tfa_data) = PVE
::AccessControl
::user_get_tfa
($username, $realm);
622 if (!defined($tfa_type)) {
623 raise
('no u2f data available');
627 if ($tfa_type eq 'u2f') {
628 my $challenge = $rpcenv->get_u2f_challenge()
629 or raise
('no active challenge');
631 my $keyHandle = $tfa_data->{keyHandle
};
632 my $publicKey = $tfa_data->{publicKey
};
633 raise
("incomplete u2f setup")
634 if !defined($keyHandle) || !defined($publicKey);
636 my $u2f = get_u2f_instance
($rpcenv, $publicKey, $keyHandle);
637 $u2f->set_challenge($challenge);
639 my ($counter, $present) = $u2f->auth_verify($param->{response
});
640 # Do we want to do anything with these?
642 # sanity check before handing off to the verification code:
643 my $keys = $tfa_data->{keys} or die "missing tfa keys\n";
644 my $config = $tfa_data->{config
} or die "bad tfa entry\n";
645 PVE
::AccessControl
::verify_one_time_pw
($tfa_type, $authuser, $keys, $config, $param->{response
});
649 my $clientip = $rpcenv->get_client_ip() || '';
650 syslog
('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
651 die PVE
::Exception-
>new("authentication failure\n", code
=> 401);
655 ticket
=> PVE
::AccessControl
::assemble_ticket
($authuser),
656 cap
=> &$compute_api_permission($rpcenv, $authuser),