]> git.proxmox.com Git - pve-access-control.git/blame - src/PVE/API2/AccessControl.pm
userid-group check: distinguish create and update
[pve-access-control.git] / src / PVE / API2 / AccessControl.pm
CommitLineData
2c3a6c0a
DM
1package PVE::API2::AccessControl;
2
3use strict;
4use warnings;
5
2b4c98ab
WB
6use JSON;
7use MIME::Base64;
8
e240695b 9use PVE::Exception qw(raise raise_perm_exc raise_param_exc);
2c3a6c0a
DM
10use PVE::SafeSyslog;
11use PVE::RPCEnvironment;
a427cecb 12use PVE::Cluster qw(cfs_read_file);
158514a8 13use PVE::DataCenterConfig;
2c3a6c0a
DM
14use PVE::RESTHandler;
15use PVE::AccessControl;
16use PVE::JSONSchema qw(get_standard_option);
17use PVE::API2::Domains;
18use PVE::API2::User;
19use PVE::API2::Group;
20use PVE::API2::Role;
21use PVE::API2::ACL;
ac344d7d 22use PVE::API2::OpenId;
dc547a13 23use PVE::API2::TFA;
8967f86f 24use PVE::Auth::Plugin;
47d731c7 25use PVE::OTP;
2c3a6c0a 26
2b4c98ab
WB
27my $u2f_available = 0;
28eval {
29 require PVE::U2F;
30 $u2f_available = 1;
31};
32
2c3a6c0a
DM
33use base qw(PVE::RESTHandler);
34
35__PACKAGE__->register_method ({
30dd4869 36 subclass => "PVE::API2::User",
2c3a6c0a
DM
37 path => 'users',
38});
39
40__PACKAGE__->register_method ({
30dd4869 41 subclass => "PVE::API2::Group",
2c3a6c0a
DM
42 path => 'groups',
43});
44
45__PACKAGE__->register_method ({
30dd4869 46 subclass => "PVE::API2::Role",
2c3a6c0a
DM
47 path => 'roles',
48});
49
50__PACKAGE__->register_method ({
30dd4869 51 subclass => "PVE::API2::ACL",
2c3a6c0a
DM
52 path => 'acl',
53});
54
55__PACKAGE__->register_method ({
30dd4869 56 subclass => "PVE::API2::Domains",
2c3a6c0a
DM
57 path => 'domains',
58});
59
ac344d7d
DM
60__PACKAGE__->register_method ({
61 subclass => "PVE::API2::OpenId",
62 path => 'openid',
63});
64
dc547a13
WB
65__PACKAGE__->register_method ({
66 subclass => "PVE::API2::TFA",
67 path => 'tfa',
68});
69
2c3a6c0a 70__PACKAGE__->register_method ({
30dd4869
TM
71 name => 'index',
72 path => '',
2c3a6c0a
DM
73 method => 'GET',
74 description => "Directory index.",
30dd4869 75 permissions => {
82b63965
DM
76 user => 'all',
77 },
2c3a6c0a
DM
78 parameters => {
79 additionalProperties => 0,
80 properties => {},
81 },
82 returns => {
83 type => 'array',
84 items => {
85 type => "object",
86 properties => {
87 subdir => { type => 'string' },
88 },
89 },
90 links => [ { rel => 'child', href => "{subdir}" } ],
91 },
92 code => sub {
93 my ($param) = @_;
30dd4869 94
2c3a6c0a
DM
95 my $res = [];
96
97 my $ma = __PACKAGE__->method_attributes();
98
99 foreach my $info (@$ma) {
100 next if !$info->{subclass};
101
102 my $subpath = $info->{match_re}->[0];
103
104 push @$res, { subdir => $subpath };
105 }
106
107 push @$res, { subdir => 'ticket' };
37d45deb 108 push @$res, { subdir => 'password' };
2c3a6c0a
DM
109
110 return $res;
111 }});
112
adf8d771 113
afb10353
WB
114my sub verify_auth : prototype($$$$$$$) {
115 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs, $new_format) = @_;
adf8d771
DM
116
117 my $normpath = PVE::AccessControl::normalize_path($path);
118
119 my $ticketuser;
120 if (($ticketuser = PVE::AccessControl::verify_ticket($pw_or_ticket, 1)) &&
121 ($ticketuser eq $username)) {
122 # valid ticket
123 } elsif (PVE::AccessControl::verify_vnc_ticket($pw_or_ticket, $username, $normpath, 1)) {
124 # valid vnc ticket
125 } else {
afb10353
WB
126 $username = PVE::AccessControl::authenticate_user(
127 $username,
128 $pw_or_ticket,
129 $otp,
130 $new_format,
131 );
adf8d771
DM
132 }
133
134 my $privlist = [ PVE::Tools::split_list($privs) ];
135 if (!($normpath && scalar(@$privlist) && $rpcenv->check($username, $normpath, $privlist))) {
136 die "no permission ($path, $privs)\n";
137 }
138
139 return { username => $username };
140};
141
afb10353
WB
142my sub create_ticket_do : prototype($$$$$$) {
143 my ($rpcenv, $username, $pw_or_ticket, $otp, $new_format, $tfa_challenge) = @_;
144
145 die "TFA response should be in 'password', not 'otp' when 'tfa-challenge' is set\n"
146 if defined($otp) && defined($tfa_challenge);
147
148 my ($ticketuser, undef, $tfa_info);
149 if (!defined($tfa_challenge)) {
150 # We only verify this ticket if we're not responding to a TFA challenge, as in that case
151 # it is a TFA-data ticket and will be verified by `authenticate_user`.
152
153 ($ticketuser, undef, $tfa_info) = PVE::AccessControl::verify_ticket($pw_or_ticket, 1);
154 }
adf8d771 155
f25628d3
WB
156 if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
157 if (defined($tfa_info)) {
158 die "incomplete ticket\n";
159 }
adf8d771
DM
160 # valid ticket. Note: root@pam can create tickets for other users
161 } else {
afb10353
WB
162 ($username, $tfa_info) = PVE::AccessControl::authenticate_user(
163 $username,
164 $pw_or_ticket,
165 $otp,
166 $new_format,
167 $tfa_challenge,
168 );
18f8ba18
WB
169 }
170
171 my %extra;
172 my $ticket_data = $username;
afb10353
WB
173 my $aad;
174 if ($new_format) {
175 if (defined($tfa_info)) {
176 $extra{NeedTFA} = 1;
177 $ticket_data = "!tfa!$tfa_info";
178 $aad = $username;
179 }
180 } elsif (defined($tfa_info)) {
f25628d3
WB
181 $extra{NeedTFA} = 1;
182 if ($tfa_info->{type} eq 'u2f') {
183 my $u2finfo = $tfa_info->{data};
184 my $u2f = get_u2f_instance($rpcenv, $u2finfo->@{qw(publicKey keyHandle)});
185 my $challenge = $u2f->auth_challenge()
186 or die "failed to get u2f challenge\n";
187 $challenge = decode_json($challenge);
188 $extra{U2FChallenge} = $challenge;
189 $ticket_data = "u2f!$username!$challenge->{challenge}";
190 } else {
191 # General half-login / 'missing 2nd factor' ticket:
192 $ticket_data = "tfa!$username";
193 }
adf8d771
DM
194 }
195
afb10353 196 my $ticket = PVE::AccessControl::assemble_ticket($ticket_data, $aad);
adf8d771
DM
197 my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token($username);
198
199 return {
200 ticket => $ticket,
201 username => $username,
202 CSRFPreventionToken => $csrftoken,
18f8ba18 203 %extra,
adf8d771
DM
204 };
205};
206
39e4e363 207__PACKAGE__->register_method ({
30dd4869
TM
208 name => 'get_ticket',
209 path => 'ticket',
39e4e363
DM
210 method => 'GET',
211 permissions => { user => 'world' },
36dd9dbd 212 description => "Dummy. Useful for formatters which want to provide a login page.",
39e4e363
DM
213 parameters => {
214 additionalProperties => 0,
215 },
216 returns => { type => "null" },
217 code => sub { return undef; }});
30dd4869 218
2c3a6c0a 219__PACKAGE__->register_method ({
30dd4869
TM
220 name => 'create_ticket',
221 path => 'ticket',
2c3a6c0a 222 method => 'POST',
30dd4869 223 permissions => {
96919234 224 description => "You need to pass valid credientials.",
30dd4869 225 user => 'world'
96919234 226 },
2c3a6c0a 227 protected => 1, # else we can't access shadow files
49372390 228 allowtoken => 0, # we don't want tokens to create tickets
adf8d771 229 description => "Create or verify authentication ticket.",
2c3a6c0a
DM
230 parameters => {
231 additionalProperties => 0,
232 properties => {
233 username => {
3a5ae7a0
SI
234 description => "User name",
235 type => 'string',
236 maxLength => 64,
237 completion => \&PVE::AccessControl::complete_username,
2c3a6c0a
DM
238 },
239 realm => get_standard_option('realm', {
240 description => "You can optionally pass the realm using this parameter. Normally the realm is simply added to the username <username>\@<relam>.",
3e5bfdf6
DM
241 optional => 1,
242 completion => \&PVE::AccessControl::complete_realm,
243 }),
30dd4869 244 password => {
2c3a6c0a
DM
245 description => "The secret password. This can also be a valid ticket.",
246 type => 'string',
247 },
96f8ebd6
DM
248 otp => {
249 description => "One-time password for Two-factor authentication.",
250 type => 'string',
251 optional => 1,
252 },
2c3a6c0a 253 path => {
adf8d771 254 description => "Verify ticket, and check if user have access 'privs' on 'path'",
2c3a6c0a
DM
255 type => 'string',
256 requires => 'privs',
257 optional => 1,
258 maxLength => 64,
259 },
30dd4869 260 privs => {
adf8d771 261 description => "Verify ticket, and check if user have access 'privs' on 'path'",
2c3a6c0a
DM
262 type => 'string' , format => 'pve-priv-list',
263 requires => 'path',
264 optional => 1,
265 maxLength => 64,
266 },
afb10353
WB
267 'new-format' => {
268 type => 'boolean',
269 description =>
270 'With webauthn the format of half-authenticated tickts changed.'
271 .' New clients should pass 1 here and not worry about the old format.'
272 .' The old format is deprecated and will be retired with PVE-8.0',
273 optional => 1,
274 default => 0,
275 },
276 'tfa-challenge' => {
277 type => 'string',
278 description => "The signed TFA challenge string the user wants to respond to.",
279 optional => 1,
280 },
2c3a6c0a
DM
281 }
282 },
283 returns => {
284 type => "object",
285 properties => {
2c3a6c0a 286 username => { type => 'string' },
adf8d771
DM
287 ticket => { type => 'string', optional => 1},
288 CSRFPreventionToken => { type => 'string', optional => 1 },
e842fec5 289 clustername => { type => 'string', optional => 1 },
18f8ba18 290 # cap => computed api permissions, unless there's a u2f challenge
2c3a6c0a
DM
291 }
292 },
293 code => sub {
294 my ($param) = @_;
30dd4869 295
2c3a6c0a
DM
296 my $username = $param->{username};
297 $username .= "\@$param->{realm}" if $param->{realm};
298
eb41d200 299 $username = PVE::AccessControl::lookup_username($username);
2c3a6c0a 300 my $rpcenv = PVE::RPCEnvironment::get();
2c3a6c0a 301
adf8d771 302 my $res;
adf8d771 303 eval {
7070c1ae
DM
304 # test if user exists and is enabled
305 $rpcenv->check_user_enabled($username);
306
2c3a6c0a 307 if ($param->{path} && $param->{privs}) {
afb10353
WB
308 $res = verify_auth($rpcenv, $username, $param->{password}, $param->{otp},
309 $param->{path}, $param->{privs}, $param->{'new-format'});
2c3a6c0a 310 } else {
afb10353
WB
311 $res = create_ticket_do(
312 $rpcenv,
313 $username,
314 $param->{password},
315 $param->{otp},
316 $param->{'new-format'},
317 $param->{'tfa-challenge'},
318 );
2c3a6c0a 319 }
2c3a6c0a
DM
320 };
321 if (my $err = $@) {
adf8d771 322 my $clientip = $rpcenv->get_client_ip() || '';
2c3a6c0a 323 syslog('err', "authentication failure; rhost=$clientip user=$username msg=$err");
6126ab75 324 # do not return any info to prevent user enumeration attacks
fe2defd9 325 die PVE::Exception->new("authentication failure\n", code => 401);
2c3a6c0a
DM
326 }
327
ac344d7d 328 $res->{cap} = $rpcenv->compute_api_permission($username)
f25628d3 329 if !defined($res->{NeedTFA});
dd2cfee0 330
0fb0c62d
FG
331 my $clinfo = PVE::Cluster::get_clinfo();
332 if ($clinfo->{cluster}->{name} && $rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
333 $res->{clustername} = $clinfo->{cluster}->{name};
e842fec5
TL
334 }
335
2c3a6c0a
DM
336 PVE::Cluster::log_msg('info', 'root@pam', "successful auth for user '$username'");
337
adf8d771 338 return $res;
2c3a6c0a
DM
339 }});
340
37d45deb 341__PACKAGE__->register_method ({
765305e2 342 name => 'change_password',
30dd4869 343 path => 'password',
37d45deb 344 method => 'PUT',
30dd4869 345 permissions => {
82b63965 346 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.",
30dd4869 347 check => [ 'or',
12683df7 348 ['userid-param', 'self'],
82b63965
DM
349 [ 'and',
350 [ 'userid-param', 'Realm.AllocateUser'],
351 [ 'userid-group', ['User.Modify']]
352 ]
12683df7
DM
353 ],
354 },
37d45deb 355 protected => 1, # else we can't access shadow files
49372390 356 allowtoken => 0, # we don't want tokens to change the regular user password
37d45deb
DM
357 description => "Change user password.",
358 parameters => {
359 additionalProperties => 0,
360 properties => {
3a5ae7a0 361 userid => get_standard_option('userid-completed'),
30dd4869 362 password => {
37d45deb
DM
363 description => "The new password.",
364 type => 'string',
30dd4869 365 minLength => 5,
37d45deb
DM
366 maxLength => 64,
367 },
368 }
369 },
370 returns => { type => "null" },
371 code => sub {
372 my ($param) = @_;
373
374 my $rpcenv = PVE::RPCEnvironment::get();
375 my $authuser = $rpcenv->get_user();
376
377 my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
378
12683df7 379 $rpcenv->check_user_exist($userid);
37d45deb
DM
380
381 if ($authuser eq 'root@pam') {
382 # OK - root can change anything
383 } else {
384 if ($authuser eq $userid) {
385 $rpcenv->check_user_enabled($userid);
386 # OK - each user can change its own password
387 } else {
12683df7 388 # only root may change root password
37d45deb 389 raise_perm_exc() if $userid eq 'root@pam';
59321f26
DM
390 # do not allow to change system user passwords
391 raise_perm_exc() if $realm eq 'pam';
37d45deb
DM
392 }
393 }
394
395 PVE::AccessControl::domain_set_password($realm, $ruid, $param->{password});
396
397 PVE::Cluster::log_msg('info', 'root@pam', "changed password for user '$userid'");
398
399 return undef;
400 }});
401
2b4c98ab
WB
402sub get_u2f_config() {
403 die "u2f support not available\n" if !$u2f_available;
404
405 my $dc = cfs_read_file('datacenter.cfg');
406 my $u2f = $dc->{u2f};
407 die "u2f not configured in datacenter.cfg\n" if !$u2f;
2b4c98ab
WB
408 return $u2f;
409}
410
411sub get_u2f_instance {
412 my ($rpcenv, $publicKey, $keyHandle) = @_;
413
414 # We store the public key base64 encoded (as the api provides it in binary)
415 $publicKey = decode_base64($publicKey) if defined($publicKey);
416
417 my $u2fconfig = get_u2f_config();
418 my $u2f = PVE::U2F->new();
419
420 # via the 'Host' header (in case a node has multiple hosts available).
421 my $origin = $u2fconfig->{origin};
422 if (!defined($origin)) {
423 $origin = $rpcenv->get_request_host(1);
424 if ($origin) {
425 $origin = "https://$origin";
426 } else {
427 die "failed to figure out u2f origin\n";
428 }
429 }
430
431 my $appid = $u2fconfig->{appid} // $origin;
432 $u2f->set_appid($appid);
433 $u2f->set_origin($origin);
434 $u2f->set_publicKey($publicKey) if defined($publicKey);
435 $u2f->set_keyHandle($keyHandle) if defined($keyHandle);
436 return $u2f;
437}
438
47d731c7
WB
439sub verify_user_tfa_config {
440 my ($type, $tfa_cfg, $value) = @_;
441
442 if (!defined($type)) {
443 die "missing tfa 'type'\n";
444 }
445
446 if ($type ne 'oath') {
447 die "invalid type for custom tfa authentication\n";
448 }
449
450 my $secret = $tfa_cfg->{keys}
451 or die "missing TOTP secret\n";
452 $tfa_cfg = $tfa_cfg->{config};
453 # Copy the hash to verify that we have no unexpected keys without modifying the original hash.
454 $tfa_cfg = {%$tfa_cfg};
455
456 # We can only verify 1 secret but oath_verify_otp allows multiple:
457 if (scalar(PVE::Tools::split_list($secret)) != 1) {
458 die "only exactly one secret key allowed\n";
459 }
460
461 my $digits = delete($tfa_cfg->{digits}) // 6;
462 my $step = delete($tfa_cfg->{step}) // 30;
463 # Maybe also this?
464 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
465
466 if (length(my $more = join(', ', keys %$tfa_cfg))) {
467 die "unexpected tfa config keys: $more\n";
468 }
469
470 PVE::OTP::oath_verify_otp($value, $secret, $step, $digits);
471}
472
2b4c98ab 473
c3fa8a36
FG
474__PACKAGE__->register_method({
475 name => 'permissions',
476 path => 'permissions',
477 method => 'GET',
478 description => 'Retrieve effective permissions of given user/token.',
479 permissions => {
480 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.",
481 user => 'all',
482 },
483 parameters => {
484 additionalProperties => 0,
485 properties => {
486 userid => {
487 type => 'string',
488 description => "User ID or full API token ID",
489 pattern => $PVE::AccessControl::userid_or_token_regex,
490 optional => 1,
491 },
492 path => get_standard_option('acl-path', {
493 description => "Only dump this specific path, not the whole tree.",
494 optional => 1,
495 }),
496 },
497 },
498 returns => {
499 type => 'object',
500 description => 'Map of "path" => (Map of "privilege" => "propagate boolean").',
501 },
502 code => sub {
503 my ($param) = @_;
504
505 my $rpcenv = PVE::RPCEnvironment::get();
506
507 my $userid = $param->{userid};
508 if (defined($userid)) {
509 $rpcenv->check($rpcenv->get_user(), '/access', ['Sys.Audit']);
510 } else {
511 $userid = $rpcenv->get_user();
512 }
513
514 my $res;
515
516 if (my $path = $param->{path}) {
517 my $perms = $rpcenv->permissions($userid, $path);
518 if ($perms) {
519 $res = { $path => $perms };
520 } else {
521 $res = {};
522 }
523 } else {
524 $res = $rpcenv->get_effective_permissions($userid);
525 }
526
527 return $res;
528 }});
529
2c3a6c0a 5301;