]> git.proxmox.com Git - pve-access-control.git/blob - src/PVE/API2/AccessControl.pm
8fa360682098ff5a160c350cfee9c1bfb35db5f0
[pve-access-control.git] / src / PVE / API2 / AccessControl.pm
1 package PVE::API2::AccessControl;
2
3 use strict;
4 use warnings;
5
6 use JSON;
7 use MIME::Base64;
8
9 use PVE::Exception qw(raise raise_perm_exc raise_param_exc);
10 use PVE::SafeSyslog;
11 use PVE::RPCEnvironment;
12 use PVE::Cluster qw(cfs_read_file);
13 use PVE::DataCenterConfig;
14 use PVE::RESTHandler;
15 use PVE::AccessControl;
16 use PVE::JSONSchema qw(get_standard_option);
17 use PVE::API2::Domains;
18 use PVE::API2::User;
19 use PVE::API2::Group;
20 use PVE::API2::Role;
21 use PVE::API2::ACL;
22 use PVE::API2::OpenId;
23 use PVE::Auth::Plugin;
24 use PVE::OTP;
25
26 my $u2f_available = 0;
27 eval {
28 require PVE::U2F;
29 $u2f_available = 1;
30 };
31
32 use base qw(PVE::RESTHandler);
33
34 __PACKAGE__->register_method ({
35 subclass => "PVE::API2::User",
36 path => 'users',
37 });
38
39 __PACKAGE__->register_method ({
40 subclass => "PVE::API2::Group",
41 path => 'groups',
42 });
43
44 __PACKAGE__->register_method ({
45 subclass => "PVE::API2::Role",
46 path => 'roles',
47 });
48
49 __PACKAGE__->register_method ({
50 subclass => "PVE::API2::ACL",
51 path => 'acl',
52 });
53
54 __PACKAGE__->register_method ({
55 subclass => "PVE::API2::Domains",
56 path => 'domains',
57 });
58
59 __PACKAGE__->register_method ({
60 subclass => "PVE::API2::OpenId",
61 path => 'openid',
62 });
63
64 __PACKAGE__->register_method ({
65 name => 'index',
66 path => '',
67 method => 'GET',
68 description => "Directory index.",
69 permissions => {
70 user => 'all',
71 },
72 parameters => {
73 additionalProperties => 0,
74 properties => {},
75 },
76 returns => {
77 type => 'array',
78 items => {
79 type => "object",
80 properties => {
81 subdir => { type => 'string' },
82 },
83 },
84 links => [ { rel => 'child', href => "{subdir}" } ],
85 },
86 code => sub {
87 my ($param) = @_;
88
89 my $res = [];
90
91 my $ma = __PACKAGE__->method_attributes();
92
93 foreach my $info (@$ma) {
94 next if !$info->{subclass};
95
96 my $subpath = $info->{match_re}->[0];
97
98 push @$res, { subdir => $subpath };
99 }
100
101 push @$res, { subdir => 'ticket' };
102 push @$res, { subdir => 'password' };
103
104 return $res;
105 }});
106
107
108 my sub verify_auth : prototype($$$$$$$) {
109 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs, $new_format) = @_;
110
111 my $normpath = PVE::AccessControl::normalize_path($path);
112
113 my $ticketuser;
114 if (($ticketuser = PVE::AccessControl::verify_ticket($pw_or_ticket, 1)) &&
115 ($ticketuser eq $username)) {
116 # valid ticket
117 } elsif (PVE::AccessControl::verify_vnc_ticket($pw_or_ticket, $username, $normpath, 1)) {
118 # valid vnc ticket
119 } else {
120 $username = PVE::AccessControl::authenticate_user(
121 $username,
122 $pw_or_ticket,
123 $otp,
124 $new_format,
125 );
126 }
127
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";
131 }
132
133 return { username => $username };
134 };
135
136 my sub create_ticket_do : prototype($$$$$$) {
137 my ($rpcenv, $username, $pw_or_ticket, $otp, $new_format, $tfa_challenge) = @_;
138
139 die "TFA response should be in 'password', not 'otp' when 'tfa-challenge' is set\n"
140 if defined($otp) && defined($tfa_challenge);
141
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`.
146
147 ($ticketuser, undef, $tfa_info) = PVE::AccessControl::verify_ticket($pw_or_ticket, 1);
148 }
149
150 if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
151 if (defined($tfa_info)) {
152 die "incomplete ticket\n";
153 }
154 # valid ticket. Note: root@pam can create tickets for other users
155 } else {
156 ($username, $tfa_info) = PVE::AccessControl::authenticate_user(
157 $username,
158 $pw_or_ticket,
159 $otp,
160 $new_format,
161 $tfa_challenge,
162 );
163 }
164
165 my %extra;
166 my $ticket_data = $username;
167 my $aad;
168 if ($new_format) {
169 if (defined($tfa_info)) {
170 $extra{NeedTFA} = 1;
171 $ticket_data = "!tfa!$tfa_info";
172 $aad = $username;
173 }
174 } elsif (defined($tfa_info)) {
175 $extra{NeedTFA} = 1;
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}";
184 } else {
185 # General half-login / 'missing 2nd factor' ticket:
186 $ticket_data = "tfa!$username";
187 }
188 }
189
190 my $ticket = PVE::AccessControl::assemble_ticket($ticket_data, $aad);
191 my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token($username);
192
193 return {
194 ticket => $ticket,
195 username => $username,
196 CSRFPreventionToken => $csrftoken,
197 %extra,
198 };
199 };
200
201 __PACKAGE__->register_method ({
202 name => 'get_ticket',
203 path => 'ticket',
204 method => 'GET',
205 permissions => { user => 'world' },
206 description => "Dummy. Useful for formatters which want to provide a login page.",
207 parameters => {
208 additionalProperties => 0,
209 },
210 returns => { type => "null" },
211 code => sub { return undef; }});
212
213 __PACKAGE__->register_method ({
214 name => 'create_ticket',
215 path => 'ticket',
216 method => 'POST',
217 permissions => {
218 description => "You need to pass valid credientials.",
219 user => 'world'
220 },
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.",
224 parameters => {
225 additionalProperties => 0,
226 properties => {
227 username => {
228 description => "User name",
229 type => 'string',
230 maxLength => 64,
231 completion => \&PVE::AccessControl::complete_username,
232 },
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>.",
235 optional => 1,
236 completion => \&PVE::AccessControl::complete_realm,
237 }),
238 password => {
239 description => "The secret password. This can also be a valid ticket.",
240 type => 'string',
241 },
242 otp => {
243 description => "One-time password for Two-factor authentication.",
244 type => 'string',
245 optional => 1,
246 },
247 path => {
248 description => "Verify ticket, and check if user have access 'privs' on 'path'",
249 type => 'string',
250 requires => 'privs',
251 optional => 1,
252 maxLength => 64,
253 },
254 privs => {
255 description => "Verify ticket, and check if user have access 'privs' on 'path'",
256 type => 'string' , format => 'pve-priv-list',
257 requires => 'path',
258 optional => 1,
259 maxLength => 64,
260 },
261 'new-format' => {
262 type => 'boolean',
263 description =>
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',
267 optional => 1,
268 default => 0,
269 },
270 'tfa-challenge' => {
271 type => 'string',
272 description => "The signed TFA challenge string the user wants to respond to.",
273 optional => 1,
274 },
275 }
276 },
277 returns => {
278 type => "object",
279 properties => {
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
285 }
286 },
287 code => sub {
288 my ($param) = @_;
289
290 my $username = $param->{username};
291 $username .= "\@$param->{realm}" if $param->{realm};
292
293 $username = PVE::AccessControl::lookup_username($username);
294 my $rpcenv = PVE::RPCEnvironment::get();
295
296 my $res;
297 eval {
298 # test if user exists and is enabled
299 $rpcenv->check_user_enabled($username);
300
301 if ($param->{path} && $param->{privs}) {
302 $res = verify_auth($rpcenv, $username, $param->{password}, $param->{otp},
303 $param->{path}, $param->{privs}, $param->{'new-format'});
304 } else {
305 $res = create_ticket_do(
306 $rpcenv,
307 $username,
308 $param->{password},
309 $param->{otp},
310 $param->{'new-format'},
311 $param->{'tfa-challenge'},
312 );
313 }
314 };
315 if (my $err = $@) {
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);
320 }
321
322 $res->{cap} = $rpcenv->compute_api_permission($username)
323 if !defined($res->{NeedTFA});
324
325 my $clinfo = PVE::Cluster::get_clinfo();
326 if ($clinfo->{cluster}->{name} && $rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
327 $res->{clustername} = $clinfo->{cluster}->{name};
328 }
329
330 PVE::Cluster::log_msg('info', 'root@pam', "successful auth for user '$username'");
331
332 return $res;
333 }});
334
335 __PACKAGE__->register_method ({
336 name => 'change_password',
337 path => 'password',
338 method => 'PUT',
339 permissions => {
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.",
341 check => [ 'or',
342 ['userid-param', 'self'],
343 [ 'and',
344 [ 'userid-param', 'Realm.AllocateUser'],
345 [ 'userid-group', ['User.Modify']]
346 ]
347 ],
348 },
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.",
352 parameters => {
353 additionalProperties => 0,
354 properties => {
355 userid => get_standard_option('userid-completed'),
356 password => {
357 description => "The new password.",
358 type => 'string',
359 minLength => 5,
360 maxLength => 64,
361 },
362 }
363 },
364 returns => { type => "null" },
365 code => sub {
366 my ($param) = @_;
367
368 my $rpcenv = PVE::RPCEnvironment::get();
369 my $authuser = $rpcenv->get_user();
370
371 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
372
373 $rpcenv->check_user_exist($userid);
374
375 if ($authuser eq 'root@pam') {
376 # OK - root can change anything
377 } else {
378 if ($authuser eq $userid) {
379 $rpcenv->check_user_enabled($userid);
380 # OK - each user can change its own password
381 } else {
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';
386 }
387 }
388
389 PVE::AccessControl::domain_set_password($realm, $ruid, $param->{password});
390
391 PVE::Cluster::log_msg('info', 'root@pam', "changed password for user '$userid'");
392
393 return undef;
394 }});
395
396 sub get_u2f_config() {
397 die "u2f support not available\n" if !$u2f_available;
398
399 my $dc = cfs_read_file('datacenter.cfg');
400 my $u2f = $dc->{u2f};
401 die "u2f not configured in datacenter.cfg\n" if !$u2f;
402 return $u2f;
403 }
404
405 sub get_u2f_instance {
406 my ($rpcenv, $publicKey, $keyHandle) = @_;
407
408 # We store the public key base64 encoded (as the api provides it in binary)
409 $publicKey = decode_base64($publicKey) if defined($publicKey);
410
411 my $u2fconfig = get_u2f_config();
412 my $u2f = PVE::U2F->new();
413
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);
418 if ($origin) {
419 $origin = "https://$origin";
420 } else {
421 die "failed to figure out u2f origin\n";
422 }
423 }
424
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);
430 return $u2f;
431 }
432
433 sub verify_user_tfa_config {
434 my ($type, $tfa_cfg, $value) = @_;
435
436 if (!defined($type)) {
437 die "missing tfa 'type'\n";
438 }
439
440 if ($type ne 'oath') {
441 die "invalid type for custom tfa authentication\n";
442 }
443
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};
449
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";
453 }
454
455 my $digits = delete($tfa_cfg->{digits}) // 6;
456 my $step = delete($tfa_cfg->{step}) // 30;
457 # Maybe also this?
458 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
459
460 if (length(my $more = join(', ', keys %$tfa_cfg))) {
461 die "unexpected tfa config keys: $more\n";
462 }
463
464 PVE::OTP::oath_verify_otp($value, $secret, $step, $digits);
465 }
466
467 __PACKAGE__->register_method ({
468 name => 'change_tfa',
469 path => 'tfa',
470 method => 'PUT',
471 permissions => {
472 description => 'A user can change their own u2f or totp token.',
473 check => [ 'or',
474 ['userid-param', 'self'],
475 [ 'and',
476 [ 'userid-param', 'Realm.AllocateUser'],
477 [ 'userid-group', ['User.Modify']]
478 ]
479 ],
480 },
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.",
484 parameters => {
485 additionalProperties => 0,
486 properties => {
487 userid => get_standard_option('userid', {
488 completion => \&PVE::AccessControl::complete_username,
489 }),
490 password => {
491 optional => 1, # Only required if not root@pam
492 description => "The current password.",
493 type => 'string',
494 minLength => 5,
495 maxLength => 64,
496 },
497 action => {
498 description => 'The action to perform',
499 type => 'string',
500 enum => [qw(delete new confirm)],
501 },
502 response => {
503 optional => 1,
504 description =>
505 'Either the the response to the current u2f registration challenge,'
506 .' or, when adding TOTP, the currently valid TOTP value.',
507 type => 'string',
508 },
509 key => {
510 optional => 1,
511 description => 'When adding TOTP, the shared secret value.',
512 type => 'string',
513 format => 'pve-tfa-secret',
514 },
515 config => {
516 optional => 1,
517 description => 'A TFA configuration. This must currently be of type TOTP of not set at all.',
518 type => 'string',
519 format => 'pve-tfa-config',
520 maxLength => 128,
521 },
522 }
523 },
524 returns => { type => 'object' },
525 code => sub {
526 my ($param) = @_;
527
528 die "TODO!\n";
529
530 my $rpcenv = PVE::RPCEnvironment::get();
531 my $authuser = $rpcenv->get_user();
532
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});
538
539 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
540 $rpcenv->check_user_exist($userid);
541
542 # Only root may modify root
543 raise_perm_exc() if $userid eq 'root@pam' && $authuser ne 'root@pam';
544
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);
554 }
555
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});
563 my $tfa_cfg = {
564 keys => $key,
565 config => $config,
566 };
567 verify_user_tfa_config($type, $tfa_cfg, $response);
568 PVE::AccessControl::user_set_tfa($userid, $realm, $type, $tfa_cfg);
569 } else {
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);
576 return $challenge;
577 }
578 } elsif ($action eq 'confirm') {
579 raise_param_exc({ 'response' => "confirm action requires the 'response' parameter to be set" })
580 if !defined($response);
581
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');
585
586 my $challenge = $u2fdata->{challenge}
587 or raise("no active challenge");
588
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
595 });
596 } else {
597 die "invalid action: $action\n";
598 }
599
600 return {};
601 }});
602
603 __PACKAGE__->register_method({
604 name => 'verify_tfa',
605 path => 'tfa',
606 method => 'POST',
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.',
611 parameters => {
612 additionalProperties => 0,
613 properties => {
614 response => {
615 type => 'string',
616 description => 'The response to the current authentication challenge.',
617 },
618 }
619 },
620 returns => {
621 type => 'object',
622 properties => {
623 ticket => { type => 'string' },
624 # cap
625 }
626 },
627 code => sub {
628 my ($param) = @_;
629
630 my $rpcenv = PVE::RPCEnvironment::get();
631 my $authuser = $rpcenv->get_user();
632 my ($username, undef, $realm) = PVE::AccessControl::verify_username($authuser);
633
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');
637 }
638
639 eval {
640 if ($tfa_type eq 'u2f') {
641 my $challenge = $rpcenv->get_u2f_challenge()
642 or raise('no active challenge');
643
644 my $keyHandle = $tfa_data->{keyHandle};
645 my $publicKey = $tfa_data->{publicKey};
646 raise("incomplete u2f setup")
647 if !defined($keyHandle) || !defined($publicKey);
648
649 my $u2f = get_u2f_instance($rpcenv, $publicKey, $keyHandle);
650 $u2f->set_challenge($challenge);
651
652 my ($counter, $present) = $u2f->auth_verify($param->{response});
653 # Do we want to do anything with these?
654 } else {
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});
659 }
660 };
661 if (my $err = $@) {
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);
665 }
666
667 return {
668 ticket => PVE::AccessControl::assemble_ticket($authuser),
669 cap => $rpcenv->compute_api_permission($authuser),
670 }
671 }});
672
673 __PACKAGE__->register_method({
674 name => 'permissions',
675 path => 'permissions',
676 method => 'GET',
677 description => 'Retrieve effective permissions of given user/token.',
678 permissions => {
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.",
680 user => 'all',
681 },
682 parameters => {
683 additionalProperties => 0,
684 properties => {
685 userid => {
686 type => 'string',
687 description => "User ID or full API token ID",
688 pattern => $PVE::AccessControl::userid_or_token_regex,
689 optional => 1,
690 },
691 path => get_standard_option('acl-path', {
692 description => "Only dump this specific path, not the whole tree.",
693 optional => 1,
694 }),
695 },
696 },
697 returns => {
698 type => 'object',
699 description => 'Map of "path" => (Map of "privilege" => "propagate boolean").',
700 },
701 code => sub {
702 my ($param) = @_;
703
704 my $rpcenv = PVE::RPCEnvironment::get();
705
706 my $userid = $param->{userid};
707 if (defined($userid)) {
708 $rpcenv->check($rpcenv->get_user(), '/access', ['Sys.Audit']);
709 } else {
710 $userid = $rpcenv->get_user();
711 }
712
713 my $res;
714
715 if (my $path = $param->{path}) {
716 my $perms = $rpcenv->permissions($userid, $path);
717 if ($perms) {
718 $res = { $path => $perms };
719 } else {
720 $res = {};
721 }
722 } else {
723 $res = $rpcenv->get_effective_permissions($userid);
724 }
725
726 return $res;
727 }});
728
729 1;