]> git.proxmox.com Git - pve-access-control.git/blob - PVE/API2/AccessControl.pm
add missing 'use PVE::Auth::Plugin'
[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);
10 use PVE::SafeSyslog;
11 use PVE::RPCEnvironment;
12 use PVE::Cluster qw(cfs_read_file);
13 use PVE::Corosync;
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::Auth::Plugin;
23 use PVE::OTP;
24 use PVE::Tools;
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 name => 'index',
61 path => '',
62 method => 'GET',
63 description => "Directory index.",
64 permissions => {
65 user => 'all',
66 },
67 parameters => {
68 additionalProperties => 0,
69 properties => {},
70 },
71 returns => {
72 type => 'array',
73 items => {
74 type => "object",
75 properties => {
76 subdir => { type => 'string' },
77 },
78 },
79 links => [ { rel => 'child', href => "{subdir}" } ],
80 },
81 code => sub {
82 my ($param) = @_;
83
84 my $res = [];
85
86 my $ma = __PACKAGE__->method_attributes();
87
88 foreach my $info (@$ma) {
89 next if !$info->{subclass};
90
91 my $subpath = $info->{match_re}->[0];
92
93 push @$res, { subdir => $subpath };
94 }
95
96 push @$res, { subdir => 'ticket' };
97 push @$res, { subdir => 'password' };
98
99 return $res;
100 }});
101
102
103 my $verify_auth = sub {
104 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs) = @_;
105
106 my $normpath = PVE::AccessControl::normalize_path($path);
107
108 my $ticketuser;
109 if (($ticketuser = PVE::AccessControl::verify_ticket($pw_or_ticket, 1)) &&
110 ($ticketuser eq $username)) {
111 # valid ticket
112 } elsif (PVE::AccessControl::verify_vnc_ticket($pw_or_ticket, $username, $normpath, 1)) {
113 # valid vnc ticket
114 } else {
115 $username = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
116 }
117
118 my $privlist = [ PVE::Tools::split_list($privs) ];
119 if (!($normpath && scalar(@$privlist) && $rpcenv->check($username, $normpath, $privlist))) {
120 die "no permission ($path, $privs)\n";
121 }
122
123 return { username => $username };
124 };
125
126 my $create_ticket = sub {
127 my ($rpcenv, $username, $pw_or_ticket, $otp) = @_;
128
129 my ($ticketuser, undef, $tfa_info) = PVE::AccessControl::verify_ticket($pw_or_ticket, 1);
130 if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
131 if (defined($tfa_info)) {
132 die "incomplete ticket\n";
133 }
134 # valid ticket. Note: root@pam can create tickets for other users
135 } else {
136 ($username, $tfa_info) = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
137 }
138
139 my %extra;
140 my $ticket_data = $username;
141 if (defined($tfa_info)) {
142 $extra{NeedTFA} = 1;
143 if ($tfa_info->{type} eq 'u2f') {
144 my $u2finfo = $tfa_info->{data};
145 my $u2f = get_u2f_instance($rpcenv, $u2finfo->@{qw(publicKey keyHandle)});
146 my $challenge = $u2f->auth_challenge()
147 or die "failed to get u2f challenge\n";
148 $challenge = decode_json($challenge);
149 $extra{U2FChallenge} = $challenge;
150 $ticket_data = "u2f!$username!$challenge->{challenge}";
151 } else {
152 # General half-login / 'missing 2nd factor' ticket:
153 $ticket_data = "tfa!$username";
154 }
155 }
156
157 my $ticket = PVE::AccessControl::assemble_ticket($ticket_data);
158 my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token($username);
159
160 return {
161 ticket => $ticket,
162 username => $username,
163 CSRFPreventionToken => $csrftoken,
164 %extra,
165 };
166 };
167
168 my $compute_api_permission = sub {
169 my ($rpcenv, $authuser) = @_;
170
171 my $usercfg = $rpcenv->{user_cfg};
172
173 my $res = {};
174 my $priv_re_map = {
175 vms => qr/VM\.|Permissions\.Modify/,
176 access => qr/(User|Group)\.|Permissions\.Modify/,
177 storage => qr/Datastore\.|Permissions\.Modify/,
178 nodes => qr/Sys\.|Permissions\.Modify/,
179 dc => qr/Sys\.Audit/,
180 };
181 map { $res->{$_} = {} } keys %$priv_re_map;
182
183 my $required_paths = ['/', '/nodes', '/access/groups', '/vms', '/storage'];
184
185 my $checked_paths = {};
186 foreach my $path (@$required_paths, keys %{$usercfg->{acl}}) {
187 next if $checked_paths->{$path};
188 $checked_paths->{$path} = 1;
189
190 my $path_perm = $rpcenv->permissions($authuser, $path);
191
192 my $toplevel = ($path =~ /^\/(\w+)/) ? $1 : 'dc';
193 if ($toplevel eq 'pool') {
194 foreach my $priv (keys %$path_perm) {
195 if ($priv =~ m/^VM\./) {
196 $res->{vms}->{$priv} = 1;
197 } elsif ($priv =~ m/^Datastore\./) {
198 $res->{storage}->{$priv} = 1;
199 } elsif ($priv eq 'Permissions.Modify') {
200 $res->{storage}->{$priv} = 1;
201 $res->{vms}->{$priv} = 1;
202 }
203 }
204 } else {
205 my $priv_regex = $priv_re_map->{$toplevel} // next;
206 foreach my $priv (keys %$path_perm) {
207 next if $priv !~ m/^($priv_regex)/;
208 $res->{$toplevel}->{$priv} = 1;
209 }
210 }
211 }
212
213 return $res;
214 };
215
216 __PACKAGE__->register_method ({
217 name => 'get_ticket',
218 path => 'ticket',
219 method => 'GET',
220 permissions => { user => 'world' },
221 description => "Dummy. Useful for formatters which want to provide a login page.",
222 parameters => {
223 additionalProperties => 0,
224 },
225 returns => { type => "null" },
226 code => sub { return undef; }});
227
228 __PACKAGE__->register_method ({
229 name => 'create_ticket',
230 path => 'ticket',
231 method => 'POST',
232 permissions => {
233 description => "You need to pass valid credientials.",
234 user => 'world'
235 },
236 protected => 1, # else we can't access shadow files
237 description => "Create or verify authentication ticket.",
238 parameters => {
239 additionalProperties => 0,
240 properties => {
241 username => {
242 description => "User name",
243 type => 'string',
244 maxLength => 64,
245 completion => \&PVE::AccessControl::complete_username,
246 },
247 realm => get_standard_option('realm', {
248 description => "You can optionally pass the realm using this parameter. Normally the realm is simply added to the username <username>\@<relam>.",
249 optional => 1,
250 completion => \&PVE::AccessControl::complete_realm,
251 }),
252 password => {
253 description => "The secret password. This can also be a valid ticket.",
254 type => 'string',
255 },
256 otp => {
257 description => "One-time password for Two-factor authentication.",
258 type => 'string',
259 optional => 1,
260 },
261 path => {
262 description => "Verify ticket, and check if user have access 'privs' on 'path'",
263 type => 'string',
264 requires => 'privs',
265 optional => 1,
266 maxLength => 64,
267 },
268 privs => {
269 description => "Verify ticket, and check if user have access 'privs' on 'path'",
270 type => 'string' , format => 'pve-priv-list',
271 requires => 'path',
272 optional => 1,
273 maxLength => 64,
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 my $rpcenv = PVE::RPCEnvironment::get();
294
295 my $res;
296 eval {
297 # test if user exists and is enabled
298 $rpcenv->check_user_enabled($username);
299
300 if ($param->{path} && $param->{privs}) {
301 $res = &$verify_auth($rpcenv, $username, $param->{password}, $param->{otp},
302 $param->{path}, $param->{privs});
303 } else {
304 $res = &$create_ticket($rpcenv, $username, $param->{password}, $param->{otp});
305 }
306 };
307 if (my $err = $@) {
308 my $clientip = $rpcenv->get_client_ip() || '';
309 syslog('err', "authentication failure; rhost=$clientip user=$username msg=$err");
310 # do not return any info to prevent user enumeration attacks
311 die PVE::Exception->new("authentication failure\n", code => 401);
312 }
313
314 $res->{cap} = &$compute_api_permission($rpcenv, $username)
315 if !defined($res->{NeedTFA});
316
317 if (PVE::Corosync::check_conf_exists(1)) {
318 if ($rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
319 eval {
320 my $conf = cfs_read_file('corosync.conf');
321 my $totem = PVE::Corosync::totem_config($conf);
322 if ($totem->{cluster_name}) {
323 $res->{clustername} = $totem->{cluster_name};
324 }
325 };
326 warn "$@\n" if $@;
327 }
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 description => "Change user password.",
351 parameters => {
352 additionalProperties => 0,
353 properties => {
354 userid => get_standard_option('userid-completed'),
355 password => {
356 description => "The new password.",
357 type => 'string',
358 minLength => 5,
359 maxLength => 64,
360 },
361 }
362 },
363 returns => { type => "null" },
364 code => sub {
365 my ($param) = @_;
366
367 my $rpcenv = PVE::RPCEnvironment::get();
368 my $authuser = $rpcenv->get_user();
369
370 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
371
372 $rpcenv->check_user_exist($userid);
373
374 if ($authuser eq 'root@pam') {
375 # OK - root can change anything
376 } else {
377 if ($authuser eq $userid) {
378 $rpcenv->check_user_enabled($userid);
379 # OK - each user can change its own password
380 } else {
381 # only root may change root password
382 raise_perm_exc() if $userid eq 'root@pam';
383 # do not allow to change system user passwords
384 raise_perm_exc() if $realm eq 'pam';
385 }
386 }
387
388 PVE::AccessControl::domain_set_password($realm, $ruid, $param->{password});
389
390 PVE::Cluster::log_msg('info', 'root@pam', "changed password for user '$userid'");
391
392 return undef;
393 }});
394
395 sub get_u2f_config() {
396 die "u2f support not available\n" if !$u2f_available;
397
398 my $dc = cfs_read_file('datacenter.cfg');
399 my $u2f = $dc->{u2f};
400 die "u2f not configured in datacenter.cfg\n" if !$u2f;
401 $u2f = PVE::JSONSchema::parse_property_string($PVE::Cluster::u2f_format, $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 description => "Change user u2f authentication.",
483 parameters => {
484 additionalProperties => 0,
485 properties => {
486 userid => get_standard_option('userid', {
487 completion => \&PVE::AccessControl::complete_username,
488 }),
489 password => {
490 optional => 1, # Only required if not root@pam
491 description => "The current password.",
492 type => 'string',
493 minLength => 5,
494 maxLength => 64,
495 },
496 action => {
497 description => 'The action to perform',
498 type => 'string',
499 enum => [qw(delete new confirm)],
500 },
501 response => {
502 optional => 1,
503 description =>
504 'Either the the response to the current u2f registration challenge,'
505 .' or, when adding TOTP, the currently valid TOTP value.',
506 type => 'string',
507 },
508 key => {
509 optional => 1,
510 description => 'When adding TOTP, the shared secret value.',
511 type => 'string',
512 # This is what pve-common's PVE::OTP::oath_verify_otp accepts.
513 # Should we move this to pve-common's JSONSchema as a named format?
514 pattern => qr/[A-Z2-7=]{16}|[A-Fa-f0-9]{40}/,
515 },
516 config => {
517 optional => 1,
518 description => 'A TFA configuration. This must currently be of type TOTP of not set at all.',
519 type => 'string',
520 format => 'pve-tfa-config',
521 maxLength => 128,
522 },
523 }
524 },
525 returns => { type => 'object' },
526 code => sub {
527 my ($param) = @_;
528
529 my $rpcenv = PVE::RPCEnvironment::get();
530 my $authuser = $rpcenv->get_user();
531
532 my $action = delete $param->{action};
533 my $response = delete $param->{response};
534 my $password = delete($param->{password}) // '';
535 my $key = delete($param->{key});
536 my $config = delete($param->{config});
537
538 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
539 $rpcenv->check_user_exist($userid);
540
541 # Only root may modify root
542 raise_perm_exc() if $userid eq 'root@pam' && $authuser ne 'root@pam';
543
544 # Regular users need to confirm their password to change u2f settings.
545 if ($authuser ne 'root@pam') {
546 raise_param_exc('password' => 'password is required to modify u2f data')
547 if !defined($password);
548 my $domain_cfg = cfs_read_file('domains.cfg');
549 my $cfg = $domain_cfg->{ids}->{$realm};
550 die "auth domain '$realm' does not exists\n" if !$cfg;
551 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
552 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
553 }
554
555 if ($action eq 'delete') {
556 PVE::AccessControl::user_set_tfa($userid, $realm, undef, undef);
557 PVE::Cluster::log_msg('info', $authuser, "deleted u2f data for user '$userid'");
558 } elsif ($action eq 'new') {
559 if (defined($config)) {
560 $config = PVE::Auth::Plugin::parse_tfa_config($config);
561 my $type = delete($config->{type});
562 my $tfa_cfg = {
563 keys => $key,
564 config => $config,
565 };
566 verify_user_tfa_config($type, $tfa_cfg, $response);
567 PVE::AccessControl::user_set_tfa($userid, $realm, $type, $tfa_cfg);
568 } else {
569 # The default is U2F:
570 my $u2f = get_u2f_instance($rpcenv);
571 my $challenge = $u2f->registration_challenge()
572 or raise("failed to get u2f challenge");
573 $challenge = decode_json($challenge);
574 PVE::AccessControl::user_set_tfa($userid, $realm, 'u2f', $challenge);
575 return $challenge;
576 }
577 } elsif ($action eq 'confirm') {
578 raise_param_exc('response' => "confirm action requires the 'response' parameter to be set")
579 if !defined($response);
580
581 my ($type, $u2fdata) = PVE::AccessControl::user_get_tfa($userid, $realm);
582 raise("no u2f data available")
583 if (!defined($type) || $type ne 'u2f');
584
585 my $challenge = $u2fdata->{challenge}
586 or raise("no active challenge");
587
588 my $u2f = get_u2f_instance($rpcenv);
589 $u2f->set_challenge($challenge);
590 my ($keyHandle, $publicKey) = $u2f->registration_verify($response);
591 PVE::AccessControl::user_set_tfa($userid, $realm, 'u2f', {
592 keyHandle => $keyHandle,
593 publicKey => $publicKey, # already base64 encoded
594 });
595 } else {
596 die "invalid action: $action\n";
597 }
598
599 return {};
600 }});
601
602 __PACKAGE__->register_method({
603 name => 'verify_tfa',
604 path => 'tfa',
605 method => 'POST',
606 permissions => { user => 'all' },
607 protected => 1, # else we can't access shadow files
608 description => 'Finish a u2f challenge.',
609 parameters => {
610 additionalProperties => 0,
611 properties => {
612 response => {
613 type => 'string',
614 description => 'The response to the current authentication challenge.',
615 },
616 }
617 },
618 returns => {
619 type => 'object',
620 properties => {
621 ticket => { type => 'string' },
622 # cap
623 }
624 },
625 code => sub {
626 my ($param) = @_;
627
628 my $rpcenv = PVE::RPCEnvironment::get();
629 my $authuser = $rpcenv->get_user();
630 my ($username, undef, $realm) = PVE::AccessControl::verify_username($authuser);
631
632 my ($tfa_type, $tfa_data) = PVE::AccessControl::user_get_tfa($username, $realm);
633 if (!defined($tfa_type)) {
634 raise('no u2f data available');
635 }
636
637 eval {
638 if ($tfa_type eq 'u2f') {
639 my $challenge = $rpcenv->get_u2f_challenge()
640 or raise('no active challenge');
641
642 my $keyHandle = $tfa_data->{keyHandle};
643 my $publicKey = $tfa_data->{publicKey};
644 raise("incomplete u2f setup")
645 if !defined($keyHandle) || !defined($publicKey);
646
647 my $u2f = get_u2f_instance($rpcenv, $publicKey, $keyHandle);
648 $u2f->set_challenge($challenge);
649
650 my ($counter, $present) = $u2f->auth_verify($param->{response});
651 # Do we want to do anything with these?
652 } else {
653 # sanity check before handing off to the verification code:
654 my $keys = $tfa_data->{keys} or die "missing tfa keys\n";
655 my $config = $tfa_data->{config} or die "bad tfa entry\n";
656 PVE::AccessControl::verify_one_time_pw($tfa_type, $authuser, $keys, $config, $param->{response});
657 }
658 };
659 if (my $err = $@) {
660 my $clientip = $rpcenv->get_client_ip() || '';
661 syslog('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
662 die PVE::Exception->new("authentication failure\n", code => 401);
663 }
664
665 return {
666 ticket => PVE::AccessControl::assemble_ticket($authuser),
667 cap => &$compute_api_permission($rpcenv, $authuser),
668 }
669 }});
670
671 1;