1 package PVE
::API2
::AccessControl
;
9 use PVE
::Exception
qw(raise raise_perm_exc);
11 use PVE
::RPCEnvironment
;
12 use PVE
::Cluster
qw(cfs_read_file);
15 use PVE
::AccessControl
;
16 use PVE
::JSONSchema
qw(get_standard_option);
17 use PVE
::API2
::Domains
;
25 my $u2f_available = 0;
31 use base
qw(PVE::RESTHandler);
33 __PACKAGE__-
>register_method ({
34 subclass
=> "PVE::API2::User",
38 __PACKAGE__-
>register_method ({
39 subclass
=> "PVE::API2::Group",
43 __PACKAGE__-
>register_method ({
44 subclass
=> "PVE::API2::Role",
48 __PACKAGE__-
>register_method ({
49 subclass
=> "PVE::API2::ACL",
53 __PACKAGE__-
>register_method ({
54 subclass
=> "PVE::API2::Domains",
58 __PACKAGE__-
>register_method ({
62 description
=> "Directory index.",
67 additionalProperties
=> 0,
75 subdir
=> { type
=> 'string' },
78 links
=> [ { rel
=> 'child', href
=> "{subdir}" } ],
85 my $ma = __PACKAGE__-
>method_attributes();
87 foreach my $info (@$ma) {
88 next if !$info->{subclass
};
90 my $subpath = $info->{match_re
}->[0];
92 push @$res, { subdir
=> $subpath };
95 push @$res, { subdir
=> 'ticket' };
96 push @$res, { subdir
=> 'password' };
102 my $verify_auth = sub {
103 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs) = @_;
105 my $normpath = PVE
::AccessControl
::normalize_path
($path);
108 if (($ticketuser = PVE
::AccessControl
::verify_ticket
($pw_or_ticket, 1)) &&
109 ($ticketuser eq $username)) {
111 } elsif (PVE
::AccessControl
::verify_vnc_ticket
($pw_or_ticket, $username, $normpath, 1)) {
114 $username = PVE
::AccessControl
::authenticate_user
($username, $pw_or_ticket, $otp);
117 my $privlist = [ PVE
::Tools
::split_list
($privs) ];
118 if (!($normpath && scalar(@$privlist) && $rpcenv->check($username, $normpath, $privlist))) {
119 die "no permission ($path, $privs)\n";
122 return { username
=> $username };
125 my $create_ticket = sub {
126 my ($rpcenv, $username, $pw_or_ticket, $otp) = @_;
128 my ($ticketuser, $u2fdata);
129 if (($ticketuser = PVE
::AccessControl
::verify_ticket
($pw_or_ticket, 1)) &&
130 ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
131 # valid ticket. Note: root@pam can create tickets for other users
133 ($username, $u2fdata) = PVE
::AccessControl
::authenticate_user
($username, $pw_or_ticket, $otp);
137 my $ticket_data = $username;
138 if (defined($u2fdata)) {
139 my $u2f = get_u2f_instance
($rpcenv, $u2fdata->@{qw(publicKey keyHandle)});
140 my $challenge = $u2f->auth_challenge()
141 or die "failed to get u2f challenge\n";
142 $challenge = decode_json
($challenge);
143 $extra{U2FChallenge
} = $challenge;
144 $ticket_data = "u2f!$username!$challenge->{challenge}";
147 my $ticket = PVE
::AccessControl
::assemble_ticket
($ticket_data);
148 my $csrftoken = PVE
::AccessControl
::assemble_csrf_prevention_token
($username);
152 username
=> $username,
153 CSRFPreventionToken
=> $csrftoken,
158 my $compute_api_permission = sub {
159 my ($rpcenv, $authuser) = @_;
161 my $usercfg = $rpcenv->{user_cfg
};
165 vms
=> qr/VM\.|Permissions\.Modify/,
166 access
=> qr/(User|Group)\.|Permissions\.Modify/,
167 storage
=> qr/Datastore\.|Permissions\.Modify/,
168 nodes
=> qr/Sys\.|Permissions\.Modify/,
169 dc
=> qr/Sys\.Audit/,
171 map { $res->{$_} = {} } keys %$priv_re_map;
173 my $required_paths = ['/', '/nodes', '/access/groups', '/vms', '/storage'];
175 my $checked_paths = {};
176 foreach my $path (@$required_paths, keys %{$usercfg->{acl
}}) {
177 next if $checked_paths->{$path};
178 $checked_paths->{$path} = 1;
180 my $path_perm = $rpcenv->permissions($authuser, $path);
182 my $toplevel = ($path =~ /^\/(\w
+)/) ?
$1 : 'dc';
183 if ($toplevel eq 'pool') {
184 foreach my $priv (keys %$path_perm) {
185 if ($priv =~ m/^VM\./) {
186 $res->{vms
}->{$priv} = 1;
187 } elsif ($priv =~ m/^Datastore\./) {
188 $res->{storage
}->{$priv} = 1;
189 } elsif ($priv eq 'Permissions.Modify') {
190 $res->{storage
}->{$priv} = 1;
191 $res->{vms
}->{$priv} = 1;
195 my $priv_regex = $priv_re_map->{$toplevel} // next;
196 foreach my $priv (keys %$path_perm) {
197 next if $priv !~ m/^($priv_regex)/;
198 $res->{$toplevel}->{$priv} = 1;
206 __PACKAGE__-
>register_method ({
207 name
=> 'get_ticket',
210 permissions
=> { user
=> 'world' },
211 description
=> "Dummy. Useful for formatters which want to provide a login page.",
213 additionalProperties
=> 0,
215 returns
=> { type
=> "null" },
216 code
=> sub { return undef; }});
218 __PACKAGE__-
>register_method ({
219 name
=> 'create_ticket',
223 description
=> "You need to pass valid credientials.",
226 protected
=> 1, # else we can't access shadow files
227 description
=> "Create or verify authentication ticket.",
229 additionalProperties
=> 0,
232 description
=> "User name",
235 completion
=> \
&PVE
::AccessControl
::complete_username
,
237 realm
=> get_standard_option
('realm', {
238 description
=> "You can optionally pass the realm using this parameter. Normally the realm is simply added to the username <username>\@<relam>.",
240 completion
=> \
&PVE
::AccessControl
::complete_realm
,
243 description
=> "The secret password. This can also be a valid ticket.",
247 description
=> "One-time password for Two-factor authentication.",
252 description
=> "Verify ticket, and check if user have access 'privs' on 'path'",
259 description
=> "Verify ticket, and check if user have access 'privs' on 'path'",
260 type
=> 'string' , format
=> 'pve-priv-list',
270 username
=> { type
=> 'string' },
271 ticket
=> { type
=> 'string', optional
=> 1},
272 CSRFPreventionToken
=> { type
=> 'string', optional
=> 1 },
273 clustername
=> { type
=> 'string', optional
=> 1 },
274 # cap => computed api permissions, unless there's a u2f challenge
280 my $username = $param->{username
};
281 $username .= "\@$param->{realm}" if $param->{realm
};
283 my $rpcenv = PVE
::RPCEnvironment
::get
();
287 # test if user exists and is enabled
288 $rpcenv->check_user_enabled($username);
290 if ($param->{path
} && $param->{privs
}) {
291 $res = &$verify_auth($rpcenv, $username, $param->{password
}, $param->{otp
},
292 $param->{path
}, $param->{privs
});
294 $res = &$create_ticket($rpcenv, $username, $param->{password
}, $param->{otp
});
298 my $clientip = $rpcenv->get_client_ip() || '';
299 syslog
('err', "authentication failure; rhost=$clientip user=$username msg=$err");
300 # do not return any info to prevent user enumeration attacks
301 die PVE
::Exception-
>new("authentication failure\n", code
=> 401);
304 $res->{cap
} = &$compute_api_permission($rpcenv, $username)
305 if !defined($res->{U2FChallenge
});
307 if (PVE
::Corosync
::check_conf_exists
(1)) {
308 if ($rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
310 my $conf = cfs_read_file
('corosync.conf');
311 my $totem = PVE
::Corosync
::totem_config
($conf);
312 if ($totem->{cluster_name
}) {
313 $res->{clustername
} = $totem->{cluster_name
};
320 PVE
::Cluster
::log_msg
('info', 'root@pam', "successful auth for user '$username'");
325 __PACKAGE__-
>register_method ({
326 name
=> 'change_password',
330 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.",
332 ['userid-param', 'self'],
334 [ 'userid-param', 'Realm.AllocateUser'],
335 [ 'userid-group', ['User.Modify']]
339 protected
=> 1, # else we can't access shadow files
340 description
=> "Change user password.",
342 additionalProperties
=> 0,
344 userid
=> get_standard_option
('userid-completed'),
346 description
=> "The new password.",
353 returns
=> { type
=> "null" },
357 my $rpcenv = PVE
::RPCEnvironment
::get
();
358 my $authuser = $rpcenv->get_user();
360 my ($userid, $ruid, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
362 $rpcenv->check_user_exist($userid);
364 if ($authuser eq 'root@pam') {
365 # OK - root can change anything
367 if ($authuser eq $userid) {
368 $rpcenv->check_user_enabled($userid);
369 # OK - each user can change its own password
371 # only root may change root password
372 raise_perm_exc
() if $userid eq 'root@pam';
373 # do not allow to change system user passwords
374 raise_perm_exc
() if $realm eq 'pam';
378 PVE
::AccessControl
::domain_set_password
($realm, $ruid, $param->{password
});
380 PVE
::Cluster
::log_msg
('info', 'root@pam', "changed password for user '$userid'");
385 sub get_u2f_config
() {
386 die "u2f support not available\n" if !$u2f_available;
388 my $dc = cfs_read_file
('datacenter.cfg');
389 my $u2f = $dc->{u2f
};
390 die "u2f not configured in datacenter.cfg\n" if !$u2f;
391 $u2f = PVE
::JSONSchema
::parse_property_string
($PVE::Cluster
::u2f_format
, $u2f);
395 sub get_u2f_instance
{
396 my ($rpcenv, $publicKey, $keyHandle) = @_;
398 # We store the public key base64 encoded (as the api provides it in binary)
399 $publicKey = decode_base64
($publicKey) if defined($publicKey);
401 my $u2fconfig = get_u2f_config
();
402 my $u2f = PVE
::U2F-
>new();
404 # via the 'Host' header (in case a node has multiple hosts available).
405 my $origin = $u2fconfig->{origin
};
406 if (!defined($origin)) {
407 $origin = $rpcenv->get_request_host(1);
409 $origin = "https://$origin";
411 die "failed to figure out u2f origin\n";
415 my $appid = $u2fconfig->{appid
} // $origin;
416 $u2f->set_appid($appid);
417 $u2f->set_origin($origin);
418 $u2f->set_publicKey($publicKey) if defined($publicKey);
419 $u2f->set_keyHandle($keyHandle) if defined($keyHandle);
423 sub verify_user_tfa_config
{
424 my ($type, $tfa_cfg, $value) = @_;
426 if (!defined($type)) {
427 die "missing tfa 'type'\n";
430 if ($type ne 'oath') {
431 die "invalid type for custom tfa authentication\n";
434 my $secret = $tfa_cfg->{keys}
435 or die "missing TOTP secret\n";
436 $tfa_cfg = $tfa_cfg->{config
};
437 # Copy the hash to verify that we have no unexpected keys without modifying the original hash.
438 $tfa_cfg = {%$tfa_cfg};
440 # We can only verify 1 secret but oath_verify_otp allows multiple:
441 if (scalar(PVE
::Tools
::split_list
($secret)) != 1) {
442 die "only exactly one secret key allowed\n";
445 my $digits = delete($tfa_cfg->{digits
}) // 6;
446 my $step = delete($tfa_cfg->{step
}) // 30;
448 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
450 if (length(my $more = join(', ', keys %$tfa_cfg))) {
451 die "unexpected tfa config keys: $more\n";
454 PVE
::OTP
::oath_verify_otp
($value, $secret, $step, $digits);
457 __PACKAGE__-
>register_method ({
458 name
=> 'change_tfa',
462 description
=> 'A user can change their own u2f or totp token.',
464 ['userid-param', 'self'],
466 [ 'userid-param', 'Realm.AllocateUser'],
467 [ 'userid-group', ['User.Modify']]
471 protected
=> 1, # else we can't access shadow files
472 description
=> "Change user u2f authentication.",
474 additionalProperties
=> 0,
476 userid
=> get_standard_option
('userid', {
477 completion
=> \
&PVE
::AccessControl
::complete_username
,
480 optional
=> 1, # Only required if not root@pam
481 description
=> "The current password.",
487 description
=> 'The action to perform',
489 enum
=> [qw(delete new confirm)],
494 'Either the the response to the current u2f registration challenge,'
495 .' or, when adding TOTP, the currently valid TOTP value.',
500 description
=> 'When adding TOTP, the shared secret value.',
502 # This is what pve-common's PVE::OTP::oath_verify_otp accepts.
503 # Should we move this to pve-common's JSONSchema as a named format?
504 pattern
=> qr/[A-Z2-7=]{16}|[A-Fa-f0-9]{40}/,
508 description
=> 'A TFA configuration. This must currently be of type TOTP of not set at all.',
510 format
=> 'pve-tfa-config',
515 returns
=> { type
=> 'object' },
519 my $rpcenv = PVE
::RPCEnvironment
::get
();
520 my $authuser = $rpcenv->get_user();
522 my $action = delete $param->{action
};
523 my $response = delete $param->{response
};
524 my $password = delete($param->{password
}) // '';
525 my $key = delete($param->{key
});
526 my $config = delete($param->{config
});
528 my ($userid, $ruid, $realm) = PVE
::AccessControl
::verify_username
($param->{userid
});
529 $rpcenv->check_user_exist($userid);
531 # Only root may modify root
532 raise_perm_exc
() if $userid eq 'root@pam' && $authuser ne 'root@pam';
534 # Regular users need to confirm their password to change u2f settings.
535 if ($authuser ne 'root@pam') {
536 raise_param_exc
('password' => 'password is required to modify u2f data')
537 if !defined($password);
538 my $domain_cfg = cfs_read_file
('domains.cfg');
539 my $cfg = $domain_cfg->{ids
}->{$realm};
540 die "auth domain '$realm' does not exists\n" if !$cfg;
541 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
542 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
545 if ($action eq 'delete') {
546 PVE
::AccessControl
::user_set_tfa
($userid, $realm, undef, undef);
547 PVE
::Cluster
::log_msg
('info', $authuser, "deleted u2f data for user '$userid'");
548 } elsif ($action eq 'new') {
549 if (defined($config)) {
550 $config = PVE
::Auth
::Plugin
::parse_tfa_config
($config);
551 my $type = delete($config->{type
});
556 verify_user_tfa_config
($type, $tfa_cfg, $response);
557 PVE
::AccessControl
::user_set_tfa
($userid, $realm, $type, $tfa_cfg);
559 # The default is U2F:
560 my $u2f = get_u2f_instance
($rpcenv);
561 my $challenge = $u2f->registration_challenge()
562 or raise
("failed to get u2f challenge");
563 $challenge = decode_json
($challenge);
564 PVE
::AccessControl
::user_set_tfa
($userid, $realm, 'u2f', $challenge);
567 } elsif ($action eq 'confirm') {
568 raise_param_exc
('response' => "confirm action requires the 'response' parameter to be set")
569 if !defined($response);
571 my ($type, $u2fdata) = PVE
::AccessControl
::user_get_tfa
($userid, $realm);
572 raise
("no u2f data available")
573 if (!defined($type) || $type ne 'u2f');
575 my $challenge = $u2fdata->{challenge
}
576 or raise
("no active challenge");
578 my $u2f = get_u2f_instance
($rpcenv);
579 $u2f->set_challenge($challenge);
580 my ($keyHandle, $publicKey) = $u2f->registration_verify($response);
581 PVE
::AccessControl
::user_set_tfa
($userid, $realm, 'u2f', {
582 keyHandle
=> $keyHandle,
583 publicKey
=> encode_base64
($publicKey, ''),
586 die "invalid action: $action\n";
592 __PACKAGE__-
>register_method({
593 name
=> 'verify_tfa',
596 permissions
=> { user
=> 'all' },
597 protected
=> 1, # else we can't access shadow files
598 description
=> 'Finish a u2f challenge.',
600 additionalProperties
=> 0,
604 description
=> 'The response to the current authentication challenge.',
611 ticket
=> { type
=> 'string' },
618 my $rpcenv = PVE
::RPCEnvironment
::get
();
619 my $challenge = $rpcenv->get_u2f_challenge()
620 or raise
('no active challenge');
621 my $authuser = $rpcenv->get_user();
622 my ($username, undef, $realm) = PVE
::AccessControl
::verify_username
($authuser);
624 my ($tfa_type, $u2fdata) = PVE
::AccessControl
::user_get_tfa
($username, $realm);
625 if (!defined($tfa_type) || $tfa_type ne 'u2f') {
626 raise
('no u2f data available');
629 my $keyHandle = $u2fdata->{keyHandle
};
630 my $publicKey = $u2fdata->{publicKey
};
631 raise
("incomplete u2f setup")
632 if !defined($keyHandle) || !defined($publicKey);
634 my $u2f = get_u2f_instance
($rpcenv, $publicKey, $keyHandle);
635 $u2f->set_challenge($challenge);
638 my ($counter, $present) = $u2f->auth_verify($param->{response
});
639 # Do we want to do anything with these?
642 my $clientip = $rpcenv->get_client_ip() || '';
643 syslog
('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
644 die PVE
::Exception-
>new("authentication failure\n", code
=> 401);
647 # create a new ticket for the user:
648 my $ticket_data = "u2f!$authuser!verified";
650 ticket
=> PVE
::AccessControl
::assemble_ticket
($ticket_data),
651 cap
=> &$compute_api_permission($rpcenv, $authuser),