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
::API2
::OpenId
;
23 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 ({
60 subclass
=> "PVE::API2::OpenId",
64 __PACKAGE__-
>register_method ({
68 description
=> "Directory index.",
73 additionalProperties
=> 0,
81 subdir
=> { type
=> 'string' },
84 links
=> [ { rel
=> 'child', href
=> "{subdir}" } ],
91 my $ma = __PACKAGE__-
>method_attributes();
93 foreach my $info (@$ma) {
94 next if !$info->{subclass
};
96 my $subpath = $info->{match_re
}->[0];
98 push @$res, { subdir
=> $subpath };
101 push @$res, { subdir
=> 'ticket' };
102 push @$res, { subdir
=> 'password' };
108 my $verify_auth = sub {
109 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs) = @_;
111 my $normpath = PVE
::AccessControl
::normalize_path
($path);
114 if (($ticketuser = PVE
::AccessControl
::verify_ticket
($pw_or_ticket, 1)) &&
115 ($ticketuser eq $username)) {
117 } elsif (PVE
::AccessControl
::verify_vnc_ticket
($pw_or_ticket, $username, $normpath, 1)) {
120 $username = PVE
::AccessControl
::authenticate_user
($username, $pw_or_ticket, $otp);
123 my $privlist = [ PVE
::Tools
::split_list
($privs) ];
124 if (!($normpath && scalar(@$privlist) && $rpcenv->check($username, $normpath, $privlist))) {
125 die "no permission ($path, $privs)\n";
128 return { username
=> $username };
131 my $create_ticket = sub {
132 my ($rpcenv, $username, $pw_or_ticket, $otp) = @_;
134 my ($ticketuser, undef, $tfa_info) = PVE
::AccessControl
::verify_ticket
($pw_or_ticket, 1);
135 if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
136 if (defined($tfa_info)) {
137 die "incomplete ticket\n";
139 # valid ticket. Note: root@pam can create tickets for other users
141 ($username, $tfa_info) = PVE
::AccessControl
::authenticate_user
($username, $pw_or_ticket, $otp);
145 my $ticket_data = $username;
146 if (defined($tfa_info)) {
148 if ($tfa_info->{type
} eq 'u2f') {
149 my $u2finfo = $tfa_info->{data
};
150 my $u2f = get_u2f_instance
($rpcenv, $u2finfo->@{qw(publicKey keyHandle)});
151 my $challenge = $u2f->auth_challenge()
152 or die "failed to get u2f challenge\n";
153 $challenge = decode_json
($challenge);
154 $extra{U2FChallenge
} = $challenge;
155 $ticket_data = "u2f!$username!$challenge->{challenge}";
157 # General half-login / 'missing 2nd factor' ticket:
158 $ticket_data = "tfa!$username";
162 my $ticket = PVE
::AccessControl
::assemble_ticket
($ticket_data);
163 my $csrftoken = PVE
::AccessControl
::assemble_csrf_prevention_token
($username);
167 username
=> $username,
168 CSRFPreventionToken
=> $csrftoken,
173 __PACKAGE__-
>register_method ({
174 name
=> 'get_ticket',
177 permissions
=> { user
=> 'world' },
178 description
=> "Dummy. Useful for formatters which want to provide a login page.",
180 additionalProperties
=> 0,
182 returns
=> { type
=> "null" },
183 code
=> sub { return undef; }});
185 __PACKAGE__-
>register_method ({
186 name
=> 'create_ticket',
190 description
=> "You need to pass valid credientials.",
193 protected
=> 1, # else we can't access shadow files
194 allowtoken
=> 0, # we don't want tokens to create tickets
195 description
=> "Create or verify authentication ticket.",
197 additionalProperties
=> 0,
200 description
=> "User name",
203 completion
=> \
&PVE
::AccessControl
::complete_username
,
205 realm
=> get_standard_option
('realm', {
206 description
=> "You can optionally pass the realm using this parameter. Normally the realm is simply added to the username <username>\@<relam>.",
208 completion
=> \
&PVE
::AccessControl
::complete_realm
,
211 description
=> "The secret password. This can also be a valid ticket.",
215 description
=> "One-time password for Two-factor authentication.",
220 description
=> "Verify ticket, and check if user have access 'privs' on 'path'",
227 description
=> "Verify ticket, and check if user have access 'privs' on 'path'",
228 type
=> 'string' , format
=> 'pve-priv-list',
238 username
=> { type
=> 'string' },
239 ticket
=> { type
=> 'string', optional
=> 1},
240 CSRFPreventionToken
=> { type
=> 'string', optional
=> 1 },
241 clustername
=> { type
=> 'string', optional
=> 1 },
242 # cap => computed api permissions, unless there's a u2f challenge
248 my $username = $param->{username
};
249 $username .= "\@$param->{realm}" if $param->{realm
};
251 $username = PVE
::AccessControl
::lookup_username
($username);
252 my $rpcenv = PVE
::RPCEnvironment
::get
();
256 # test if user exists and is enabled
257 $rpcenv->check_user_enabled($username);
259 if ($param->{path
} && $param->{privs
}) {
260 $res = &$verify_auth($rpcenv, $username, $param->{password
}, $param->{otp
},
261 $param->{path
}, $param->{privs
});
263 $res = &$create_ticket($rpcenv, $username, $param->{password
}, $param->{otp
});
267 my $clientip = $rpcenv->get_client_ip() || '';
268 syslog
('err', "authentication failure; rhost=$clientip user=$username msg=$err");
269 # do not return any info to prevent user enumeration attacks
270 die PVE
::Exception-
>new("authentication failure\n", code
=> 401);
273 $res->{cap
} = $rpcenv->compute_api_permission($username)
274 if !defined($res->{NeedTFA
});
276 my $clinfo = PVE
::Cluster
::get_clinfo
();
277 if ($clinfo->{cluster
}->{name
} && $rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
278 $res->{clustername
} = $clinfo->{cluster
}->{name
};
281 PVE
::Cluster
::log_msg
('info', 'root@pam', "successful auth for user '$username'");
286 __PACKAGE__-
>register_method ({
287 name
=> 'change_password',
291 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.",
293 ['userid-param', 'self'],
295 [ 'userid-param', 'Realm.AllocateUser'],
296 [ 'userid-group', ['User.Modify']]
300 protected
=> 1, # else we can't access shadow files
301 allowtoken
=> 0, # we don't want tokens to change the regular user password
302 description
=> "Change user password.",
304 additionalProperties
=> 0,
306 userid
=> get_standard_option
('userid-completed'),
308 description
=> "The new password.",
315 returns
=> { type
=> "null" },
319 my $rpcenv = PVE
::RPCEnvironment
::get
();
320 my $authuser = $rpcenv->get_user();
322 my ($userid, $ruid, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
324 $rpcenv->check_user_exist($userid);
326 if ($authuser eq 'root@pam') {
327 # OK - root can change anything
329 if ($authuser eq $userid) {
330 $rpcenv->check_user_enabled($userid);
331 # OK - each user can change its own password
333 # only root may change root password
334 raise_perm_exc
() if $userid eq 'root@pam';
335 # do not allow to change system user passwords
336 raise_perm_exc
() if $realm eq 'pam';
340 PVE
::AccessControl
::domain_set_password
($realm, $ruid, $param->{password
});
342 PVE
::Cluster
::log_msg
('info', 'root@pam', "changed password for user '$userid'");
347 sub get_u2f_config
() {
348 die "u2f support not available\n" if !$u2f_available;
350 my $dc = cfs_read_file
('datacenter.cfg');
351 my $u2f = $dc->{u2f
};
352 die "u2f not configured in datacenter.cfg\n" if !$u2f;
356 sub get_u2f_instance
{
357 my ($rpcenv, $publicKey, $keyHandle) = @_;
359 # We store the public key base64 encoded (as the api provides it in binary)
360 $publicKey = decode_base64
($publicKey) if defined($publicKey);
362 my $u2fconfig = get_u2f_config
();
363 my $u2f = PVE
::U2F-
>new();
365 # via the 'Host' header (in case a node has multiple hosts available).
366 my $origin = $u2fconfig->{origin
};
367 if (!defined($origin)) {
368 $origin = $rpcenv->get_request_host(1);
370 $origin = "https://$origin";
372 die "failed to figure out u2f origin\n";
376 my $appid = $u2fconfig->{appid
} // $origin;
377 $u2f->set_appid($appid);
378 $u2f->set_origin($origin);
379 $u2f->set_publicKey($publicKey) if defined($publicKey);
380 $u2f->set_keyHandle($keyHandle) if defined($keyHandle);
384 sub verify_user_tfa_config
{
385 my ($type, $tfa_cfg, $value) = @_;
387 if (!defined($type)) {
388 die "missing tfa 'type'\n";
391 if ($type ne 'oath') {
392 die "invalid type for custom tfa authentication\n";
395 my $secret = $tfa_cfg->{keys}
396 or die "missing TOTP secret\n";
397 $tfa_cfg = $tfa_cfg->{config
};
398 # Copy the hash to verify that we have no unexpected keys without modifying the original hash.
399 $tfa_cfg = {%$tfa_cfg};
401 # We can only verify 1 secret but oath_verify_otp allows multiple:
402 if (scalar(PVE
::Tools
::split_list
($secret)) != 1) {
403 die "only exactly one secret key allowed\n";
406 my $digits = delete($tfa_cfg->{digits
}) // 6;
407 my $step = delete($tfa_cfg->{step
}) // 30;
409 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
411 if (length(my $more = join(', ', keys %$tfa_cfg))) {
412 die "unexpected tfa config keys: $more\n";
415 PVE
::OTP
::oath_verify_otp
($value, $secret, $step, $digits);
418 __PACKAGE__-
>register_method ({
419 name
=> 'change_tfa',
423 description
=> 'A user can change their own u2f or totp token.',
425 ['userid-param', 'self'],
427 [ 'userid-param', 'Realm.AllocateUser'],
428 [ 'userid-group', ['User.Modify']]
432 protected
=> 1, # else we can't access shadow files
433 allowtoken
=> 0, # we don't want tokens to change the regular user's TFA settings
434 description
=> "Change user u2f authentication.",
436 additionalProperties
=> 0,
438 userid
=> get_standard_option
('userid', {
439 completion
=> \
&PVE
::AccessControl
::complete_username
,
442 optional
=> 1, # Only required if not root@pam
443 description
=> "The current password.",
449 description
=> 'The action to perform',
451 enum
=> [qw(delete new confirm)],
456 'Either the the response to the current u2f registration challenge,'
457 .' or, when adding TOTP, the currently valid TOTP value.',
462 description
=> 'When adding TOTP, the shared secret value.',
464 format
=> 'pve-tfa-secret',
468 description
=> 'A TFA configuration. This must currently be of type TOTP of not set at all.',
470 format
=> 'pve-tfa-config',
475 returns
=> { type
=> 'object' },
479 my $rpcenv = PVE
::RPCEnvironment
::get
();
480 my $authuser = $rpcenv->get_user();
482 my $action = delete $param->{action
};
483 my $response = delete $param->{response
};
484 my $password = delete($param->{password
}) // '';
485 my $key = delete($param->{key
});
486 my $config = delete($param->{config
});
488 my ($userid, $ruid, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
489 $rpcenv->check_user_exist($userid);
491 # Only root may modify root
492 raise_perm_exc
() if $userid eq 'root@pam' && $authuser ne 'root@pam';
494 # Regular users need to confirm their password to change u2f settings.
495 if ($authuser ne 'root@pam') {
496 raise_param_exc
({ 'password' => 'password is required to modify u2f data' })
497 if !defined($password);
498 my $domain_cfg = cfs_read_file
('domains.cfg');
499 my $cfg = $domain_cfg->{ids
}->{$realm};
500 die "auth domain '$realm' does not exist\n" if !$cfg;
501 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
502 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
505 if ($action eq 'delete') {
506 PVE
::AccessControl
::user_set_tfa
($userid, $realm, undef, undef);
507 PVE
::Cluster
::log_msg
('info', $authuser, "deleted u2f data for user '$userid'");
508 } elsif ($action eq 'new') {
509 if (defined($config)) {
510 $config = PVE
::Auth
::Plugin
::parse_tfa_config
($config);
511 my $type = delete($config->{type
});
516 verify_user_tfa_config
($type, $tfa_cfg, $response);
517 PVE
::AccessControl
::user_set_tfa
($userid, $realm, $type, $tfa_cfg);
519 # The default is U2F:
520 my $u2f = get_u2f_instance
($rpcenv);
521 my $challenge = $u2f->registration_challenge()
522 or raise
("failed to get u2f challenge");
523 $challenge = decode_json
($challenge);
524 PVE
::AccessControl
::user_set_tfa
($userid, $realm, 'u2f', $challenge);
527 } elsif ($action eq 'confirm') {
528 raise_param_exc
({ 'response' => "confirm action requires the 'response' parameter to be set" })
529 if !defined($response);
531 my ($type, $u2fdata) = PVE
::AccessControl
::user_get_tfa
($userid, $realm);
532 raise
("no u2f data available")
533 if (!defined($type) || $type ne 'u2f');
535 my $challenge = $u2fdata->{challenge
}
536 or raise
("no active challenge");
538 my $u2f = get_u2f_instance
($rpcenv);
539 $u2f->set_challenge($challenge);
540 my ($keyHandle, $publicKey) = $u2f->registration_verify($response);
541 PVE
::AccessControl
::user_set_tfa
($userid, $realm, 'u2f', {
542 keyHandle
=> $keyHandle,
543 publicKey
=> $publicKey, # already base64 encoded
546 die "invalid action: $action\n";
552 __PACKAGE__-
>register_method({
553 name
=> 'verify_tfa',
556 permissions
=> { user
=> 'all' },
557 protected
=> 1, # else we can't access shadow files
558 allowtoken
=> 0, # we don't want tokens to access TFA information
559 description
=> 'Finish a u2f challenge.',
561 additionalProperties
=> 0,
565 description
=> 'The response to the current authentication challenge.',
572 ticket
=> { type
=> 'string' },
579 my $rpcenv = PVE
::RPCEnvironment
::get
();
580 my $authuser = $rpcenv->get_user();
581 my ($username, undef, $realm) = PVE
::AccessControl
::verify_username
($authuser);
583 my ($tfa_type, $tfa_data) = PVE
::AccessControl
::user_get_tfa
($username, $realm);
584 if (!defined($tfa_type)) {
585 raise
('no u2f data available');
589 if ($tfa_type eq 'u2f') {
590 my $challenge = $rpcenv->get_u2f_challenge()
591 or raise
('no active challenge');
593 my $keyHandle = $tfa_data->{keyHandle
};
594 my $publicKey = $tfa_data->{publicKey
};
595 raise
("incomplete u2f setup")
596 if !defined($keyHandle) || !defined($publicKey);
598 my $u2f = get_u2f_instance
($rpcenv, $publicKey, $keyHandle);
599 $u2f->set_challenge($challenge);
601 my ($counter, $present) = $u2f->auth_verify($param->{response
});
602 # Do we want to do anything with these?
604 # sanity check before handing off to the verification code:
605 my $keys = $tfa_data->{keys} or die "missing tfa keys\n";
606 my $config = $tfa_data->{config
} or die "bad tfa entry\n";
607 PVE
::AccessControl
::verify_one_time_pw
($tfa_type, $authuser, $keys, $config, $param->{response
});
611 my $clientip = $rpcenv->get_client_ip() || '';
612 syslog
('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
613 die PVE
::Exception-
>new("authentication failure\n", code
=> 401);
617 ticket
=> PVE
::AccessControl
::assemble_ticket
($authuser),
618 cap
=> $rpcenv->compute_api_permission($authuser),
622 __PACKAGE__-
>register_method({
623 name
=> 'permissions',
624 path
=> 'permissions',
626 description
=> 'Retrieve effective permissions of given user/token.',
628 description
=> "Each user/token is allowed to dump their own permissions. A user can dump the permissions of another user if they have 'Sys.Audit' permission on /access.",
632 additionalProperties
=> 0,
636 description
=> "User ID or full API token ID",
637 pattern
=> $PVE::AccessControl
::userid_or_token_regex
,
640 path
=> get_standard_option
('acl-path', {
641 description
=> "Only dump this specific path, not the whole tree.",
648 description
=> 'Map of "path" => (Map of "privilege" => "propagate boolean").',
653 my $rpcenv = PVE
::RPCEnvironment
::get
();
655 my $userid = $param->{userid
};
656 if (defined($userid)) {
657 $rpcenv->check($rpcenv->get_user(), '/access', ['Sys.Audit']);
659 $userid = $rpcenv->get_user();
664 if (my $path = $param->{path
}) {
665 my $perms = $rpcenv->permissions($userid, $path);
667 $res = { $path => $perms };
672 $res = $rpcenv->get_effective_permissions($userid);