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 sub verify_auth
: prototype($$$$$$$) {
109 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs, $new_format) = @_;
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
(
128 my $privlist = [ PVE
::Tools
::split_list
($privs) ];
129 if (!($normpath && scalar(@$privlist) && $rpcenv->check($username, $normpath, $privlist))) {
130 die "no permission ($path, $privs)\n";
133 return { username
=> $username };
136 my sub create_ticket_do
: prototype($$$$$$) {
137 my ($rpcenv, $username, $pw_or_ticket, $otp, $new_format, $tfa_challenge) = @_;
139 die "TFA response should be in 'password', not 'otp' when 'tfa-challenge' is set\n"
140 if defined($otp) && defined($tfa_challenge);
142 my ($ticketuser, undef, $tfa_info);
143 if (!defined($tfa_challenge)) {
144 # We only verify this ticket if we're not responding to a TFA challenge, as in that case
145 # it is a TFA-data ticket and will be verified by `authenticate_user`.
147 ($ticketuser, undef, $tfa_info) = PVE
::AccessControl
::verify_ticket
($pw_or_ticket, 1);
150 if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
151 if (defined($tfa_info)) {
152 die "incomplete ticket\n";
154 # valid ticket. Note: root@pam can create tickets for other users
156 ($username, $tfa_info) = PVE
::AccessControl
::authenticate_user
(
166 my $ticket_data = $username;
169 if (defined($tfa_info)) {
171 $ticket_data = "!tfa!$tfa_info";
174 } elsif (defined($tfa_info)) {
176 if ($tfa_info->{type
} eq 'u2f') {
177 my $u2finfo = $tfa_info->{data
};
178 my $u2f = get_u2f_instance
($rpcenv, $u2finfo->@{qw(publicKey keyHandle)});
179 my $challenge = $u2f->auth_challenge()
180 or die "failed to get u2f challenge\n";
181 $challenge = decode_json
($challenge);
182 $extra{U2FChallenge
} = $challenge;
183 $ticket_data = "u2f!$username!$challenge->{challenge}";
185 # General half-login / 'missing 2nd factor' ticket:
186 $ticket_data = "tfa!$username";
190 my $ticket = PVE
::AccessControl
::assemble_ticket
($ticket_data, $aad);
191 my $csrftoken = PVE
::AccessControl
::assemble_csrf_prevention_token
($username);
195 username
=> $username,
196 CSRFPreventionToken
=> $csrftoken,
201 __PACKAGE__-
>register_method ({
202 name
=> 'get_ticket',
205 permissions
=> { user
=> 'world' },
206 description
=> "Dummy. Useful for formatters which want to provide a login page.",
208 additionalProperties
=> 0,
210 returns
=> { type
=> "null" },
211 code
=> sub { return undef; }});
213 __PACKAGE__-
>register_method ({
214 name
=> 'create_ticket',
218 description
=> "You need to pass valid credientials.",
221 protected
=> 1, # else we can't access shadow files
222 allowtoken
=> 0, # we don't want tokens to create tickets
223 description
=> "Create or verify authentication ticket.",
225 additionalProperties
=> 0,
228 description
=> "User name",
231 completion
=> \
&PVE
::AccessControl
::complete_username
,
233 realm
=> get_standard_option
('realm', {
234 description
=> "You can optionally pass the realm using this parameter. Normally the realm is simply added to the username <username>\@<relam>.",
236 completion
=> \
&PVE
::AccessControl
::complete_realm
,
239 description
=> "The secret password. This can also be a valid ticket.",
243 description
=> "One-time password for Two-factor authentication.",
248 description
=> "Verify ticket, and check if user have access 'privs' on 'path'",
255 description
=> "Verify ticket, and check if user have access 'privs' on 'path'",
256 type
=> 'string' , format
=> 'pve-priv-list',
264 'With webauthn the format of half-authenticated tickts changed.'
265 .' New clients should pass 1 here and not worry about the old format.'
266 .' The old format is deprecated and will be retired with PVE-8.0',
272 description
=> "The signed TFA challenge string the user wants to respond to.",
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 $username = PVE
::AccessControl
::lookup_username
($username);
294 my $rpcenv = PVE
::RPCEnvironment
::get
();
298 # test if user exists and is enabled
299 $rpcenv->check_user_enabled($username);
301 if ($param->{path
} && $param->{privs
}) {
302 $res = verify_auth
($rpcenv, $username, $param->{password
}, $param->{otp
},
303 $param->{path
}, $param->{privs
}, $param->{'new-format'});
305 $res = create_ticket_do
(
310 $param->{'new-format'},
311 $param->{'tfa-challenge'},
316 my $clientip = $rpcenv->get_client_ip() || '';
317 syslog
('err', "authentication failure; rhost=$clientip user=$username msg=$err");
318 # do not return any info to prevent user enumeration attacks
319 die PVE
::Exception-
>new("authentication failure\n", code
=> 401);
322 $res->{cap
} = $rpcenv->compute_api_permission($username)
323 if !defined($res->{NeedTFA
});
325 my $clinfo = PVE
::Cluster
::get_clinfo
();
326 if ($clinfo->{cluster
}->{name
} && $rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
327 $res->{clustername
} = $clinfo->{cluster
}->{name
};
330 PVE
::Cluster
::log_msg
('info', 'root@pam', "successful auth for user '$username'");
335 __PACKAGE__-
>register_method ({
336 name
=> 'change_password',
340 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.",
342 ['userid-param', 'self'],
344 [ 'userid-param', 'Realm.AllocateUser'],
345 [ 'userid-group', ['User.Modify']]
349 protected
=> 1, # else we can't access shadow files
350 allowtoken
=> 0, # we don't want tokens to change the regular user password
351 description
=> "Change user password.",
353 additionalProperties
=> 0,
355 userid
=> get_standard_option
('userid-completed'),
357 description
=> "The new password.",
364 returns
=> { type
=> "null" },
368 my $rpcenv = PVE
::RPCEnvironment
::get
();
369 my $authuser = $rpcenv->get_user();
371 my ($userid, $ruid, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
373 $rpcenv->check_user_exist($userid);
375 if ($authuser eq 'root@pam') {
376 # OK - root can change anything
378 if ($authuser eq $userid) {
379 $rpcenv->check_user_enabled($userid);
380 # OK - each user can change its own password
382 # only root may change root password
383 raise_perm_exc
() if $userid eq 'root@pam';
384 # do not allow to change system user passwords
385 raise_perm_exc
() if $realm eq 'pam';
389 PVE
::AccessControl
::domain_set_password
($realm, $ruid, $param->{password
});
391 PVE
::Cluster
::log_msg
('info', 'root@pam', "changed password for user '$userid'");
396 sub get_u2f_config
() {
397 die "u2f support not available\n" if !$u2f_available;
399 my $dc = cfs_read_file
('datacenter.cfg');
400 my $u2f = $dc->{u2f
};
401 die "u2f not configured in datacenter.cfg\n" if !$u2f;
405 sub get_u2f_instance
{
406 my ($rpcenv, $publicKey, $keyHandle) = @_;
408 # We store the public key base64 encoded (as the api provides it in binary)
409 $publicKey = decode_base64
($publicKey) if defined($publicKey);
411 my $u2fconfig = get_u2f_config
();
412 my $u2f = PVE
::U2F-
>new();
414 # via the 'Host' header (in case a node has multiple hosts available).
415 my $origin = $u2fconfig->{origin
};
416 if (!defined($origin)) {
417 $origin = $rpcenv->get_request_host(1);
419 $origin = "https://$origin";
421 die "failed to figure out u2f origin\n";
425 my $appid = $u2fconfig->{appid
} // $origin;
426 $u2f->set_appid($appid);
427 $u2f->set_origin($origin);
428 $u2f->set_publicKey($publicKey) if defined($publicKey);
429 $u2f->set_keyHandle($keyHandle) if defined($keyHandle);
433 sub verify_user_tfa_config
{
434 my ($type, $tfa_cfg, $value) = @_;
436 if (!defined($type)) {
437 die "missing tfa 'type'\n";
440 if ($type ne 'oath') {
441 die "invalid type for custom tfa authentication\n";
444 my $secret = $tfa_cfg->{keys}
445 or die "missing TOTP secret\n";
446 $tfa_cfg = $tfa_cfg->{config
};
447 # Copy the hash to verify that we have no unexpected keys without modifying the original hash.
448 $tfa_cfg = {%$tfa_cfg};
450 # We can only verify 1 secret but oath_verify_otp allows multiple:
451 if (scalar(PVE
::Tools
::split_list
($secret)) != 1) {
452 die "only exactly one secret key allowed\n";
455 my $digits = delete($tfa_cfg->{digits
}) // 6;
456 my $step = delete($tfa_cfg->{step
}) // 30;
458 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
460 if (length(my $more = join(', ', keys %$tfa_cfg))) {
461 die "unexpected tfa config keys: $more\n";
464 PVE
::OTP
::oath_verify_otp
($value, $secret, $step, $digits);
467 __PACKAGE__-
>register_method ({
468 name
=> 'change_tfa',
472 description
=> 'A user can change their own u2f or totp token.',
474 ['userid-param', 'self'],
476 [ 'userid-param', 'Realm.AllocateUser'],
477 [ 'userid-group', ['User.Modify']]
481 protected
=> 1, # else we can't access shadow files
482 allowtoken
=> 0, # we don't want tokens to change the regular user's TFA settings
483 description
=> "Change user u2f authentication.",
485 additionalProperties
=> 0,
487 userid
=> get_standard_option
('userid', {
488 completion
=> \
&PVE
::AccessControl
::complete_username
,
491 optional
=> 1, # Only required if not root@pam
492 description
=> "The current password.",
498 description
=> 'The action to perform',
500 enum
=> [qw(delete new confirm)],
505 'Either the the response to the current u2f registration challenge,'
506 .' or, when adding TOTP, the currently valid TOTP value.',
511 description
=> 'When adding TOTP, the shared secret value.',
513 format
=> 'pve-tfa-secret',
517 description
=> 'A TFA configuration. This must currently be of type TOTP of not set at all.',
519 format
=> 'pve-tfa-config',
524 returns
=> { type
=> 'object' },
530 my $rpcenv = PVE
::RPCEnvironment
::get
();
531 my $authuser = $rpcenv->get_user();
533 my $action = delete $param->{action
};
534 my $response = delete $param->{response
};
535 my $password = delete($param->{password
}) // '';
536 my $key = delete($param->{key
});
537 my $config = delete($param->{config
});
539 my ($userid, $ruid, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
540 $rpcenv->check_user_exist($userid);
542 # Only root may modify root
543 raise_perm_exc
() if $userid eq 'root@pam' && $authuser ne 'root@pam';
545 # Regular users need to confirm their password to change u2f settings.
546 if ($authuser ne 'root@pam') {
547 raise_param_exc
({ 'password' => 'password is required to modify u2f data' })
548 if !defined($password);
549 my $domain_cfg = cfs_read_file
('domains.cfg');
550 my $cfg = $domain_cfg->{ids
}->{$realm};
551 die "auth domain '$realm' does not exist\n" if !$cfg;
552 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
553 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
556 if ($action eq 'delete') {
557 PVE
::AccessControl
::user_set_tfa
($userid, $realm, undef, undef);
558 PVE
::Cluster
::log_msg
('info', $authuser, "deleted u2f data for user '$userid'");
559 } elsif ($action eq 'new') {
560 if (defined($config)) {
561 $config = PVE
::Auth
::Plugin
::parse_tfa_config
($config);
562 my $type = delete($config->{type
});
567 verify_user_tfa_config
($type, $tfa_cfg, $response);
568 PVE
::AccessControl
::user_set_tfa
($userid, $realm, $type, $tfa_cfg);
570 # The default is U2F:
571 my $u2f = get_u2f_instance
($rpcenv);
572 my $challenge = $u2f->registration_challenge()
573 or raise
("failed to get u2f challenge");
574 $challenge = decode_json
($challenge);
575 PVE
::AccessControl
::user_set_tfa
($userid, $realm, 'u2f', $challenge);
578 } elsif ($action eq 'confirm') {
579 raise_param_exc
({ 'response' => "confirm action requires the 'response' parameter to be set" })
580 if !defined($response);
582 my ($type, $u2fdata) = PVE
::AccessControl
::user_get_tfa
($userid, $realm, 'FIXME');
583 raise
("no u2f data available")
584 if (!defined($type) || $type ne 'u2f');
586 my $challenge = $u2fdata->{challenge
}
587 or raise
("no active challenge");
589 my $u2f = get_u2f_instance
($rpcenv);
590 $u2f->set_challenge($challenge);
591 my ($keyHandle, $publicKey) = $u2f->registration_verify($response);
592 PVE
::AccessControl
::user_set_tfa
($userid, $realm, 'u2f', {
593 keyHandle
=> $keyHandle,
594 publicKey
=> $publicKey, # already base64 encoded
597 die "invalid action: $action\n";
603 __PACKAGE__-
>register_method({
604 name
=> 'verify_tfa',
607 permissions
=> { user
=> 'all' },
608 protected
=> 1, # else we can't access shadow files
609 allowtoken
=> 0, # we don't want tokens to access TFA information
610 description
=> 'Finish a u2f challenge.',
612 additionalProperties
=> 0,
616 description
=> 'The response to the current authentication challenge.',
623 ticket
=> { type
=> 'string' },
630 my $rpcenv = PVE
::RPCEnvironment
::get
();
631 my $authuser = $rpcenv->get_user();
632 my ($username, undef, $realm) = PVE
::AccessControl
::verify_username
($authuser);
634 my ($tfa_type, $tfa_data) = PVE
::AccessControl
::user_get_tfa
($username, $realm, 0);
635 if (!defined($tfa_type)) {
636 raise
('no u2f data available');
640 if ($tfa_type eq 'u2f') {
641 my $challenge = $rpcenv->get_u2f_challenge()
642 or raise
('no active challenge');
644 my $keyHandle = $tfa_data->{keyHandle
};
645 my $publicKey = $tfa_data->{publicKey
};
646 raise
("incomplete u2f setup")
647 if !defined($keyHandle) || !defined($publicKey);
649 my $u2f = get_u2f_instance
($rpcenv, $publicKey, $keyHandle);
650 $u2f->set_challenge($challenge);
652 my ($counter, $present) = $u2f->auth_verify($param->{response
});
653 # Do we want to do anything with these?
655 # sanity check before handing off to the verification code:
656 my $keys = $tfa_data->{keys} or die "missing tfa keys\n";
657 my $config = $tfa_data->{config
} or die "bad tfa entry\n";
658 PVE
::AccessControl
::verify_one_time_pw
($tfa_type, $authuser, $keys, $config, $param->{response
});
662 my $clientip = $rpcenv->get_client_ip() || '';
663 syslog
('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
664 die PVE
::Exception-
>new("authentication failure\n", code
=> 401);
668 ticket
=> PVE
::AccessControl
::assemble_ticket
($authuser),
669 cap
=> $rpcenv->compute_api_permission($authuser),
673 __PACKAGE__-
>register_method({
674 name
=> 'permissions',
675 path
=> 'permissions',
677 description
=> 'Retrieve effective permissions of given user/token.',
679 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.",
683 additionalProperties
=> 0,
687 description
=> "User ID or full API token ID",
688 pattern
=> $PVE::AccessControl
::userid_or_token_regex
,
691 path
=> get_standard_option
('acl-path', {
692 description
=> "Only dump this specific path, not the whole tree.",
699 description
=> 'Map of "path" => (Map of "privilege" => "propagate boolean").',
704 my $rpcenv = PVE
::RPCEnvironment
::get
();
706 my $userid = $param->{userid
};
707 if (defined($userid)) {
708 $rpcenv->check($rpcenv->get_user(), '/access', ['Sys.Audit']);
710 $userid = $rpcenv->get_user();
715 if (my $path = $param->{path
}) {
716 my $perms = $rpcenv->permissions($userid, $path);
718 $res = { $path => $perms };
723 $res = $rpcenv->get_effective_permissions($userid);