]> git.proxmox.com Git - pve-access-control.git/blob - PVE/API2/AccessControl.pm
f3366968ce0f17aa8147045dc3f82b6bc6010cb1
[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::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, $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
132 } else {
133 ($username, $u2fdata) = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
134 }
135
136 my %extra;
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}";
145 }
146
147 my $ticket = PVE::AccessControl::assemble_ticket($ticket_data);
148 my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token($username);
149
150 return {
151 ticket => $ticket,
152 username => $username,
153 CSRFPreventionToken => $csrftoken,
154 %extra,
155 };
156 };
157
158 my $compute_api_permission = sub {
159 my ($rpcenv, $authuser) = @_;
160
161 my $usercfg = $rpcenv->{user_cfg};
162
163 my $res = {};
164 my $priv_re_map = {
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/,
170 };
171 map { $res->{$_} = {} } keys %$priv_re_map;
172
173 my $required_paths = ['/', '/nodes', '/access/groups', '/vms', '/storage'];
174
175 my $checked_paths = {};
176 foreach my $path (@$required_paths, keys %{$usercfg->{acl}}) {
177 next if $checked_paths->{$path};
178 $checked_paths->{$path} = 1;
179
180 my $path_perm = $rpcenv->permissions($authuser, $path);
181
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;
192 }
193 }
194 } else {
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;
199 }
200 }
201 }
202
203 return $res;
204 };
205
206 __PACKAGE__->register_method ({
207 name => 'get_ticket',
208 path => 'ticket',
209 method => 'GET',
210 permissions => { user => 'world' },
211 description => "Dummy. Useful for formatters which want to provide a login page.",
212 parameters => {
213 additionalProperties => 0,
214 },
215 returns => { type => "null" },
216 code => sub { return undef; }});
217
218 __PACKAGE__->register_method ({
219 name => 'create_ticket',
220 path => 'ticket',
221 method => 'POST',
222 permissions => {
223 description => "You need to pass valid credientials.",
224 user => 'world'
225 },
226 protected => 1, # else we can't access shadow files
227 description => "Create or verify authentication ticket.",
228 parameters => {
229 additionalProperties => 0,
230 properties => {
231 username => {
232 description => "User name",
233 type => 'string',
234 maxLength => 64,
235 completion => \&PVE::AccessControl::complete_username,
236 },
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>.",
239 optional => 1,
240 completion => \&PVE::AccessControl::complete_realm,
241 }),
242 password => {
243 description => "The secret password. This can also be a valid ticket.",
244 type => 'string',
245 },
246 otp => {
247 description => "One-time password for Two-factor authentication.",
248 type => 'string',
249 optional => 1,
250 },
251 path => {
252 description => "Verify ticket, and check if user have access 'privs' on 'path'",
253 type => 'string',
254 requires => 'privs',
255 optional => 1,
256 maxLength => 64,
257 },
258 privs => {
259 description => "Verify ticket, and check if user have access 'privs' on 'path'",
260 type => 'string' , format => 'pve-priv-list',
261 requires => 'path',
262 optional => 1,
263 maxLength => 64,
264 },
265 }
266 },
267 returns => {
268 type => "object",
269 properties => {
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
275 }
276 },
277 code => sub {
278 my ($param) = @_;
279
280 my $username = $param->{username};
281 $username .= "\@$param->{realm}" if $param->{realm};
282
283 my $rpcenv = PVE::RPCEnvironment::get();
284
285 my $res;
286 eval {
287 # test if user exists and is enabled
288 $rpcenv->check_user_enabled($username);
289
290 if ($param->{path} && $param->{privs}) {
291 $res = &$verify_auth($rpcenv, $username, $param->{password}, $param->{otp},
292 $param->{path}, $param->{privs});
293 } else {
294 $res = &$create_ticket($rpcenv, $username, $param->{password}, $param->{otp});
295 }
296 };
297 if (my $err = $@) {
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);
302 }
303
304 $res->{cap} = &$compute_api_permission($rpcenv, $username)
305 if !defined($res->{U2FChallenge});
306
307 if (PVE::Corosync::check_conf_exists(1)) {
308 if ($rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
309 eval {
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};
314 }
315 };
316 warn "$@\n" if $@;
317 }
318 }
319
320 PVE::Cluster::log_msg('info', 'root@pam', "successful auth for user '$username'");
321
322 return $res;
323 }});
324
325 __PACKAGE__->register_method ({
326 name => 'change_password',
327 path => 'password',
328 method => 'PUT',
329 permissions => {
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.",
331 check => [ 'or',
332 ['userid-param', 'self'],
333 [ 'and',
334 [ 'userid-param', 'Realm.AllocateUser'],
335 [ 'userid-group', ['User.Modify']]
336 ]
337 ],
338 },
339 protected => 1, # else we can't access shadow files
340 description => "Change user password.",
341 parameters => {
342 additionalProperties => 0,
343 properties => {
344 userid => get_standard_option('userid-completed'),
345 password => {
346 description => "The new password.",
347 type => 'string',
348 minLength => 5,
349 maxLength => 64,
350 },
351 }
352 },
353 returns => { type => "null" },
354 code => sub {
355 my ($param) = @_;
356
357 my $rpcenv = PVE::RPCEnvironment::get();
358 my $authuser = $rpcenv->get_user();
359
360 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
361
362 $rpcenv->check_user_exist($userid);
363
364 if ($authuser eq 'root@pam') {
365 # OK - root can change anything
366 } else {
367 if ($authuser eq $userid) {
368 $rpcenv->check_user_enabled($userid);
369 # OK - each user can change its own password
370 } else {
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';
375 }
376 }
377
378 PVE::AccessControl::domain_set_password($realm, $ruid, $param->{password});
379
380 PVE::Cluster::log_msg('info', 'root@pam', "changed password for user '$userid'");
381
382 return undef;
383 }});
384
385 sub get_u2f_config() {
386 die "u2f support not available\n" if !$u2f_available;
387
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);
392 return $u2f;
393 }
394
395 sub get_u2f_instance {
396 my ($rpcenv, $publicKey, $keyHandle) = @_;
397
398 # We store the public key base64 encoded (as the api provides it in binary)
399 $publicKey = decode_base64($publicKey) if defined($publicKey);
400
401 my $u2fconfig = get_u2f_config();
402 my $u2f = PVE::U2F->new();
403
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);
408 if ($origin) {
409 $origin = "https://$origin";
410 } else {
411 die "failed to figure out u2f origin\n";
412 }
413 }
414
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);
420 return $u2f;
421 }
422
423 sub verify_user_tfa_config {
424 my ($type, $tfa_cfg, $value) = @_;
425
426 if (!defined($type)) {
427 die "missing tfa 'type'\n";
428 }
429
430 if ($type ne 'oath') {
431 die "invalid type for custom tfa authentication\n";
432 }
433
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};
439
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";
443 }
444
445 my $digits = delete($tfa_cfg->{digits}) // 6;
446 my $step = delete($tfa_cfg->{step}) // 30;
447 # Maybe also this?
448 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
449
450 if (length(my $more = join(', ', keys %$tfa_cfg))) {
451 die "unexpected tfa config keys: $more\n";
452 }
453
454 PVE::OTP::oath_verify_otp($value, $secret, $step, $digits);
455 }
456
457 __PACKAGE__->register_method ({
458 name => 'change_tfa',
459 path => 'tfa',
460 method => 'PUT',
461 permissions => {
462 description => 'A user can change their own u2f or totp token.',
463 check => [ 'or',
464 ['userid-param', 'self'],
465 [ 'and',
466 [ 'userid-param', 'Realm.AllocateUser'],
467 [ 'userid-group', ['User.Modify']]
468 ]
469 ],
470 },
471 protected => 1, # else we can't access shadow files
472 description => "Change user u2f authentication.",
473 parameters => {
474 additionalProperties => 0,
475 properties => {
476 userid => get_standard_option('userid', {
477 completion => \&PVE::AccessControl::complete_username,
478 }),
479 password => {
480 optional => 1, # Only required if not root@pam
481 description => "The current password.",
482 type => 'string',
483 minLength => 5,
484 maxLength => 64,
485 },
486 action => {
487 description => 'The action to perform',
488 type => 'string',
489 enum => [qw(delete new confirm)],
490 },
491 response => {
492 optional => 1,
493 description =>
494 'Either the the response to the current u2f registration challenge,'
495 .' or, when adding TOTP, the currently valid TOTP value.',
496 type => 'string',
497 },
498 key => {
499 optional => 1,
500 description => 'When adding TOTP, the shared secret value.',
501 type => 'string',
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}/,
505 },
506 config => {
507 optional => 1,
508 description => 'A TFA configuration. This must currently be of type TOTP of not set at all.',
509 type => 'string',
510 format => 'pve-tfa-config',
511 maxLength => 128,
512 },
513 }
514 },
515 returns => { type => 'object' },
516 code => sub {
517 my ($param) = @_;
518
519 my $rpcenv = PVE::RPCEnvironment::get();
520 my $authuser = $rpcenv->get_user();
521
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});
527
528 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
529 $rpcenv->check_user_exist($userid);
530
531 # Only root may modify root
532 raise_perm_exc() if $userid eq 'root@pam' && $authuser ne 'root@pam';
533
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);
543 }
544
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});
552 my $tfa_cfg = {
553 keys => $key,
554 config => $config,
555 };
556 verify_user_tfa_config($type, $tfa_cfg, $response);
557 PVE::AccessControl::user_set_tfa($userid, $realm, $type, $tfa_cfg);
558 } else {
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);
565 return $challenge;
566 }
567 } elsif ($action eq 'confirm') {
568 raise_param_exc('response' => "confirm action requires the 'response' parameter to be set")
569 if !defined($response);
570
571 my ($type, $u2fdata) = PVE::AccessControl::user_get_tfa($userid, $realm);
572 raise("no u2f data available")
573 if (!defined($type) || $type ne 'u2f');
574
575 my $challenge = $u2fdata->{challenge}
576 or raise("no active challenge");
577
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, ''),
584 });
585 } else {
586 die "invalid action: $action\n";
587 }
588
589 return {};
590 }});
591
592 __PACKAGE__->register_method({
593 name => 'verify_tfa',
594 path => 'tfa',
595 method => 'POST',
596 permissions => { user => 'all' },
597 protected => 1, # else we can't access shadow files
598 description => 'Finish a u2f challenge.',
599 parameters => {
600 additionalProperties => 0,
601 properties => {
602 response => {
603 type => 'string',
604 description => 'The response to the current authentication challenge.',
605 },
606 }
607 },
608 returns => {
609 type => 'object',
610 properties => {
611 ticket => { type => 'string' },
612 # cap
613 }
614 },
615 code => sub {
616 my ($param) = @_;
617
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);
623
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');
627 }
628
629 my $keyHandle = $u2fdata->{keyHandle};
630 my $publicKey = $u2fdata->{publicKey};
631 raise("incomplete u2f setup")
632 if !defined($keyHandle) || !defined($publicKey);
633
634 my $u2f = get_u2f_instance($rpcenv, $publicKey, $keyHandle);
635 $u2f->set_challenge($challenge);
636
637 eval {
638 my ($counter, $present) = $u2f->auth_verify($param->{response});
639 # Do we want to do anything with these?
640 };
641 if (my $err = $@) {
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);
645 }
646
647 # create a new ticket for the user:
648 my $ticket_data = "u2f!$authuser!verified";
649 return {
650 ticket => PVE::AccessControl::assemble_ticket($ticket_data),
651 cap => &$compute_api_permission($rpcenv, $authuser),
652 }
653 }});
654
655 1;