]> git.proxmox.com Git - pve-access-control.git/blob - PVE/API2/AccessControl.pm
API: fix calls to raise_param_exc
[pve-access-control.git] / 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::RESTHandler;
14 use PVE::AccessControl;
15 use PVE::JSONSchema qw(get_standard_option);
16 use PVE::API2::Domains;
17 use PVE::API2::User;
18 use PVE::API2::Group;
19 use PVE::API2::Role;
20 use PVE::API2::ACL;
21 use PVE::Auth::Plugin;
22 use PVE::OTP;
23 use PVE::Tools;
24
25 my $u2f_available = 0;
26 eval {
27 require PVE::U2F;
28 $u2f_available = 1;
29 };
30
31 use base qw(PVE::RESTHandler);
32
33 __PACKAGE__->register_method ({
34 subclass => "PVE::API2::User",
35 path => 'users',
36 });
37
38 __PACKAGE__->register_method ({
39 subclass => "PVE::API2::Group",
40 path => 'groups',
41 });
42
43 __PACKAGE__->register_method ({
44 subclass => "PVE::API2::Role",
45 path => 'roles',
46 });
47
48 __PACKAGE__->register_method ({
49 subclass => "PVE::API2::ACL",
50 path => 'acl',
51 });
52
53 __PACKAGE__->register_method ({
54 subclass => "PVE::API2::Domains",
55 path => 'domains',
56 });
57
58 __PACKAGE__->register_method ({
59 name => 'index',
60 path => '',
61 method => 'GET',
62 description => "Directory index.",
63 permissions => {
64 user => 'all',
65 },
66 parameters => {
67 additionalProperties => 0,
68 properties => {},
69 },
70 returns => {
71 type => 'array',
72 items => {
73 type => "object",
74 properties => {
75 subdir => { type => 'string' },
76 },
77 },
78 links => [ { rel => 'child', href => "{subdir}" } ],
79 },
80 code => sub {
81 my ($param) = @_;
82
83 my $res = [];
84
85 my $ma = __PACKAGE__->method_attributes();
86
87 foreach my $info (@$ma) {
88 next if !$info->{subclass};
89
90 my $subpath = $info->{match_re}->[0];
91
92 push @$res, { subdir => $subpath };
93 }
94
95 push @$res, { subdir => 'ticket' };
96 push @$res, { subdir => 'password' };
97
98 return $res;
99 }});
100
101
102 my $verify_auth = sub {
103 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs) = @_;
104
105 my $normpath = PVE::AccessControl::normalize_path($path);
106
107 my $ticketuser;
108 if (($ticketuser = PVE::AccessControl::verify_ticket($pw_or_ticket, 1)) &&
109 ($ticketuser eq $username)) {
110 # valid ticket
111 } elsif (PVE::AccessControl::verify_vnc_ticket($pw_or_ticket, $username, $normpath, 1)) {
112 # valid vnc ticket
113 } else {
114 $username = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
115 }
116
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";
120 }
121
122 return { username => $username };
123 };
124
125 my $create_ticket = sub {
126 my ($rpcenv, $username, $pw_or_ticket, $otp) = @_;
127
128 my ($ticketuser, undef, $tfa_info) = PVE::AccessControl::verify_ticket($pw_or_ticket, 1);
129 if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
130 if (defined($tfa_info)) {
131 die "incomplete ticket\n";
132 }
133 # valid ticket. Note: root@pam can create tickets for other users
134 } else {
135 ($username, $tfa_info) = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
136 }
137
138 my %extra;
139 my $ticket_data = $username;
140 if (defined($tfa_info)) {
141 $extra{NeedTFA} = 1;
142 if ($tfa_info->{type} eq 'u2f') {
143 my $u2finfo = $tfa_info->{data};
144 my $u2f = get_u2f_instance($rpcenv, $u2finfo->@{qw(publicKey keyHandle)});
145 my $challenge = $u2f->auth_challenge()
146 or die "failed to get u2f challenge\n";
147 $challenge = decode_json($challenge);
148 $extra{U2FChallenge} = $challenge;
149 $ticket_data = "u2f!$username!$challenge->{challenge}";
150 } else {
151 # General half-login / 'missing 2nd factor' ticket:
152 $ticket_data = "tfa!$username";
153 }
154 }
155
156 my $ticket = PVE::AccessControl::assemble_ticket($ticket_data);
157 my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token($username);
158
159 return {
160 ticket => $ticket,
161 username => $username,
162 CSRFPreventionToken => $csrftoken,
163 %extra,
164 };
165 };
166
167 my $compute_api_permission = sub {
168 my ($rpcenv, $authuser) = @_;
169
170 my $usercfg = $rpcenv->{user_cfg};
171
172 my $res = {};
173 my $priv_re_map = {
174 vms => qr/VM\.|Permissions\.Modify/,
175 access => qr/(User|Group)\.|Permissions\.Modify/,
176 storage => qr/Datastore\.|Permissions\.Modify/,
177 nodes => qr/Sys\.|Permissions\.Modify/,
178 dc => qr/Sys\.Audit/,
179 };
180 map { $res->{$_} = {} } keys %$priv_re_map;
181
182 my $required_paths = ['/', '/nodes', '/access/groups', '/vms', '/storage'];
183
184 my $checked_paths = {};
185 foreach my $path (@$required_paths, keys %{$usercfg->{acl}}) {
186 next if $checked_paths->{$path};
187 $checked_paths->{$path} = 1;
188
189 my $path_perm = $rpcenv->permissions($authuser, $path);
190
191 my $toplevel = ($path =~ /^\/(\w+)/) ? $1 : 'dc';
192 if ($toplevel eq 'pool') {
193 foreach my $priv (keys %$path_perm) {
194 if ($priv =~ m/^VM\./) {
195 $res->{vms}->{$priv} = 1;
196 } elsif ($priv =~ m/^Datastore\./) {
197 $res->{storage}->{$priv} = 1;
198 } elsif ($priv eq 'Permissions.Modify') {
199 $res->{storage}->{$priv} = 1;
200 $res->{vms}->{$priv} = 1;
201 }
202 }
203 } else {
204 my $priv_regex = $priv_re_map->{$toplevel} // next;
205 foreach my $priv (keys %$path_perm) {
206 next if $priv !~ m/^($priv_regex)/;
207 $res->{$toplevel}->{$priv} = 1;
208 }
209 }
210 }
211
212 return $res;
213 };
214
215 __PACKAGE__->register_method ({
216 name => 'get_ticket',
217 path => 'ticket',
218 method => 'GET',
219 permissions => { user => 'world' },
220 description => "Dummy. Useful for formatters which want to provide a login page.",
221 parameters => {
222 additionalProperties => 0,
223 },
224 returns => { type => "null" },
225 code => sub { return undef; }});
226
227 __PACKAGE__->register_method ({
228 name => 'create_ticket',
229 path => 'ticket',
230 method => 'POST',
231 permissions => {
232 description => "You need to pass valid credientials.",
233 user => 'world'
234 },
235 protected => 1, # else we can't access shadow files
236 description => "Create or verify authentication ticket.",
237 parameters => {
238 additionalProperties => 0,
239 properties => {
240 username => {
241 description => "User name",
242 type => 'string',
243 maxLength => 64,
244 completion => \&PVE::AccessControl::complete_username,
245 },
246 realm => get_standard_option('realm', {
247 description => "You can optionally pass the realm using this parameter. Normally the realm is simply added to the username <username>\@<relam>.",
248 optional => 1,
249 completion => \&PVE::AccessControl::complete_realm,
250 }),
251 password => {
252 description => "The secret password. This can also be a valid ticket.",
253 type => 'string',
254 },
255 otp => {
256 description => "One-time password for Two-factor authentication.",
257 type => 'string',
258 optional => 1,
259 },
260 path => {
261 description => "Verify ticket, and check if user have access 'privs' on 'path'",
262 type => 'string',
263 requires => 'privs',
264 optional => 1,
265 maxLength => 64,
266 },
267 privs => {
268 description => "Verify ticket, and check if user have access 'privs' on 'path'",
269 type => 'string' , format => 'pve-priv-list',
270 requires => 'path',
271 optional => 1,
272 maxLength => 64,
273 },
274 }
275 },
276 returns => {
277 type => "object",
278 properties => {
279 username => { type => 'string' },
280 ticket => { type => 'string', optional => 1},
281 CSRFPreventionToken => { type => 'string', optional => 1 },
282 clustername => { type => 'string', optional => 1 },
283 # cap => computed api permissions, unless there's a u2f challenge
284 }
285 },
286 code => sub {
287 my ($param) = @_;
288
289 my $username = $param->{username};
290 $username .= "\@$param->{realm}" if $param->{realm};
291
292 my $rpcenv = PVE::RPCEnvironment::get();
293
294 my $res;
295 eval {
296 # test if user exists and is enabled
297 $rpcenv->check_user_enabled($username);
298
299 if ($param->{path} && $param->{privs}) {
300 $res = &$verify_auth($rpcenv, $username, $param->{password}, $param->{otp},
301 $param->{path}, $param->{privs});
302 } else {
303 $res = &$create_ticket($rpcenv, $username, $param->{password}, $param->{otp});
304 }
305 };
306 if (my $err = $@) {
307 my $clientip = $rpcenv->get_client_ip() || '';
308 syslog('err', "authentication failure; rhost=$clientip user=$username msg=$err");
309 # do not return any info to prevent user enumeration attacks
310 die PVE::Exception->new("authentication failure\n", code => 401);
311 }
312
313 $res->{cap} = &$compute_api_permission($rpcenv, $username)
314 if !defined($res->{NeedTFA});
315
316 my $clinfo = PVE::Cluster::get_clinfo();
317 if ($clinfo->{cluster}->{name} && $rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
318 $res->{clustername} = $clinfo->{cluster}->{name};
319 }
320
321 PVE::Cluster::log_msg('info', 'root@pam', "successful auth for user '$username'");
322
323 return $res;
324 }});
325
326 __PACKAGE__->register_method ({
327 name => 'change_password',
328 path => 'password',
329 method => 'PUT',
330 permissions => {
331 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 check => [ 'or',
333 ['userid-param', 'self'],
334 [ 'and',
335 [ 'userid-param', 'Realm.AllocateUser'],
336 [ 'userid-group', ['User.Modify']]
337 ]
338 ],
339 },
340 protected => 1, # else we can't access shadow files
341 description => "Change user password.",
342 parameters => {
343 additionalProperties => 0,
344 properties => {
345 userid => get_standard_option('userid-completed'),
346 password => {
347 description => "The new password.",
348 type => 'string',
349 minLength => 5,
350 maxLength => 64,
351 },
352 }
353 },
354 returns => { type => "null" },
355 code => sub {
356 my ($param) = @_;
357
358 my $rpcenv = PVE::RPCEnvironment::get();
359 my $authuser = $rpcenv->get_user();
360
361 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
362
363 $rpcenv->check_user_exist($userid);
364
365 if ($authuser eq 'root@pam') {
366 # OK - root can change anything
367 } else {
368 if ($authuser eq $userid) {
369 $rpcenv->check_user_enabled($userid);
370 # OK - each user can change its own password
371 } else {
372 # only root may change root password
373 raise_perm_exc() if $userid eq 'root@pam';
374 # do not allow to change system user passwords
375 raise_perm_exc() if $realm eq 'pam';
376 }
377 }
378
379 PVE::AccessControl::domain_set_password($realm, $ruid, $param->{password});
380
381 PVE::Cluster::log_msg('info', 'root@pam', "changed password for user '$userid'");
382
383 return undef;
384 }});
385
386 sub get_u2f_config() {
387 die "u2f support not available\n" if !$u2f_available;
388
389 my $dc = cfs_read_file('datacenter.cfg');
390 my $u2f = $dc->{u2f};
391 die "u2f not configured in datacenter.cfg\n" if !$u2f;
392 $u2f = PVE::JSONSchema::parse_property_string($PVE::Cluster::u2f_format, $u2f);
393 return $u2f;
394 }
395
396 sub get_u2f_instance {
397 my ($rpcenv, $publicKey, $keyHandle) = @_;
398
399 # We store the public key base64 encoded (as the api provides it in binary)
400 $publicKey = decode_base64($publicKey) if defined($publicKey);
401
402 my $u2fconfig = get_u2f_config();
403 my $u2f = PVE::U2F->new();
404
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);
409 if ($origin) {
410 $origin = "https://$origin";
411 } else {
412 die "failed to figure out u2f origin\n";
413 }
414 }
415
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);
421 return $u2f;
422 }
423
424 sub verify_user_tfa_config {
425 my ($type, $tfa_cfg, $value) = @_;
426
427 if (!defined($type)) {
428 die "missing tfa 'type'\n";
429 }
430
431 if ($type ne 'oath') {
432 die "invalid type for custom tfa authentication\n";
433 }
434
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};
440
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";
444 }
445
446 my $digits = delete($tfa_cfg->{digits}) // 6;
447 my $step = delete($tfa_cfg->{step}) // 30;
448 # Maybe also this?
449 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
450
451 if (length(my $more = join(', ', keys %$tfa_cfg))) {
452 die "unexpected tfa config keys: $more\n";
453 }
454
455 PVE::OTP::oath_verify_otp($value, $secret, $step, $digits);
456 }
457
458 __PACKAGE__->register_method ({
459 name => 'change_tfa',
460 path => 'tfa',
461 method => 'PUT',
462 permissions => {
463 description => 'A user can change their own u2f or totp token.',
464 check => [ 'or',
465 ['userid-param', 'self'],
466 [ 'and',
467 [ 'userid-param', 'Realm.AllocateUser'],
468 [ 'userid-group', ['User.Modify']]
469 ]
470 ],
471 },
472 protected => 1, # else we can't access shadow files
473 description => "Change user u2f authentication.",
474 parameters => {
475 additionalProperties => 0,
476 properties => {
477 userid => get_standard_option('userid', {
478 completion => \&PVE::AccessControl::complete_username,
479 }),
480 password => {
481 optional => 1, # Only required if not root@pam
482 description => "The current password.",
483 type => 'string',
484 minLength => 5,
485 maxLength => 64,
486 },
487 action => {
488 description => 'The action to perform',
489 type => 'string',
490 enum => [qw(delete new confirm)],
491 },
492 response => {
493 optional => 1,
494 description =>
495 'Either the the response to the current u2f registration challenge,'
496 .' or, when adding TOTP, the currently valid TOTP value.',
497 type => 'string',
498 },
499 key => {
500 optional => 1,
501 description => 'When adding TOTP, the shared secret value.',
502 type => 'string',
503 format => 'pve-tfa-secret',
504 },
505 config => {
506 optional => 1,
507 description => 'A TFA configuration. This must currently be of type TOTP of not set at all.',
508 type => 'string',
509 format => 'pve-tfa-config',
510 maxLength => 128,
511 },
512 }
513 },
514 returns => { type => 'object' },
515 code => sub {
516 my ($param) = @_;
517
518 my $rpcenv = PVE::RPCEnvironment::get();
519 my $authuser = $rpcenv->get_user();
520
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});
526
527 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
528 $rpcenv->check_user_exist($userid);
529
530 # Only root may modify root
531 raise_perm_exc() if $userid eq 'root@pam' && $authuser ne 'root@pam';
532
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);
542 }
543
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});
551 my $tfa_cfg = {
552 keys => $key,
553 config => $config,
554 };
555 verify_user_tfa_config($type, $tfa_cfg, $response);
556 PVE::AccessControl::user_set_tfa($userid, $realm, $type, $tfa_cfg);
557 } else {
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);
564 return $challenge;
565 }
566 } elsif ($action eq 'confirm') {
567 raise_param_exc({ 'response' => "confirm action requires the 'response' parameter to be set" })
568 if !defined($response);
569
570 my ($type, $u2fdata) = PVE::AccessControl::user_get_tfa($userid, $realm);
571 raise("no u2f data available")
572 if (!defined($type) || $type ne 'u2f');
573
574 my $challenge = $u2fdata->{challenge}
575 or raise("no active challenge");
576
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
583 });
584 } else {
585 die "invalid action: $action\n";
586 }
587
588 return {};
589 }});
590
591 __PACKAGE__->register_method({
592 name => 'verify_tfa',
593 path => 'tfa',
594 method => 'POST',
595 permissions => { user => 'all' },
596 protected => 1, # else we can't access shadow files
597 description => 'Finish a u2f challenge.',
598 parameters => {
599 additionalProperties => 0,
600 properties => {
601 response => {
602 type => 'string',
603 description => 'The response to the current authentication challenge.',
604 },
605 }
606 },
607 returns => {
608 type => 'object',
609 properties => {
610 ticket => { type => 'string' },
611 # cap
612 }
613 },
614 code => sub {
615 my ($param) = @_;
616
617 my $rpcenv = PVE::RPCEnvironment::get();
618 my $authuser = $rpcenv->get_user();
619 my ($username, undef, $realm) = PVE::AccessControl::verify_username($authuser);
620
621 my ($tfa_type, $tfa_data) = PVE::AccessControl::user_get_tfa($username, $realm);
622 if (!defined($tfa_type)) {
623 raise('no u2f data available');
624 }
625
626 eval {
627 if ($tfa_type eq 'u2f') {
628 my $challenge = $rpcenv->get_u2f_challenge()
629 or raise('no active challenge');
630
631 my $keyHandle = $tfa_data->{keyHandle};
632 my $publicKey = $tfa_data->{publicKey};
633 raise("incomplete u2f setup")
634 if !defined($keyHandle) || !defined($publicKey);
635
636 my $u2f = get_u2f_instance($rpcenv, $publicKey, $keyHandle);
637 $u2f->set_challenge($challenge);
638
639 my ($counter, $present) = $u2f->auth_verify($param->{response});
640 # Do we want to do anything with these?
641 } else {
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});
646 }
647 };
648 if (my $err = $@) {
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);
652 }
653
654 return {
655 ticket => PVE::AccessControl::assemble_ticket($authuser),
656 cap => &$compute_api_permission($rpcenv, $authuser),
657 }
658 }});
659
660 1;