]> git.proxmox.com Git - pve-access-control.git/blob - src/PVE/API2/AccessControl.pm
user: password change: require confirmation-password parameter
[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::API2::TFA;
24 use PVE::Auth::Plugin;
25 use PVE::OTP;
26
27 my $u2f_available = 0;
28 eval {
29 require PVE::U2F;
30 $u2f_available = 1;
31 };
32
33 use base qw(PVE::RESTHandler);
34
35 __PACKAGE__->register_method ({
36 subclass => "PVE::API2::User",
37 path => 'users',
38 });
39
40 __PACKAGE__->register_method ({
41 subclass => "PVE::API2::Group",
42 path => 'groups',
43 });
44
45 __PACKAGE__->register_method ({
46 subclass => "PVE::API2::Role",
47 path => 'roles',
48 });
49
50 __PACKAGE__->register_method ({
51 subclass => "PVE::API2::ACL",
52 path => 'acl',
53 });
54
55 __PACKAGE__->register_method ({
56 subclass => "PVE::API2::Domains",
57 path => 'domains',
58 });
59
60 __PACKAGE__->register_method ({
61 subclass => "PVE::API2::OpenId",
62 path => 'openid',
63 });
64
65 __PACKAGE__->register_method ({
66 subclass => "PVE::API2::TFA",
67 path => 'tfa',
68 });
69
70 __PACKAGE__->register_method ({
71 name => 'index',
72 path => '',
73 method => 'GET',
74 description => "Directory index.",
75 permissions => {
76 user => 'all',
77 },
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) = @_;
94
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' };
108 push @$res, { subdir => 'password' };
109
110 return $res;
111 }});
112
113
114 my sub verify_auth : prototype($$$$$$) {
115 my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs) = @_;
116
117 my $normpath = PVE::AccessControl::normalize_path($path);
118 die "invalid path - $path\n" if defined($path) && !defined($normpath);
119
120 my $ticketuser;
121 if (($ticketuser = PVE::AccessControl::verify_ticket($pw_or_ticket, 1)) &&
122 ($ticketuser eq $username)) {
123 # valid ticket
124 } elsif (PVE::AccessControl::verify_vnc_ticket($pw_or_ticket, $username, $normpath, 1)) {
125 # valid vnc ticket
126 } else {
127 $username = PVE::AccessControl::authenticate_user(
128 $username,
129 $pw_or_ticket,
130 $otp,
131 );
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
142 my sub create_ticket_do : prototype($$$$$) {
143 my ($rpcenv, $username, $pw_or_ticket, $otp, $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 }
155
156 if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
157 if (defined($tfa_info)) {
158 die "incomplete ticket\n";
159 }
160 # valid ticket. Note: root@pam can create tickets for other users
161 } else {
162 ($username, $tfa_info) = PVE::AccessControl::authenticate_user(
163 $username,
164 $pw_or_ticket,
165 $otp,
166 $tfa_challenge,
167 );
168 }
169
170 my %extra;
171 my $ticket_data = $username;
172 my $aad;
173 if (defined($tfa_info)) {
174 $extra{NeedTFA} = 1;
175 $ticket_data = "!tfa!$tfa_info";
176 $aad = $username;
177 }
178
179 my $ticket = PVE::AccessControl::assemble_ticket($ticket_data, $aad);
180 my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token($username);
181
182 return {
183 ticket => $ticket,
184 username => $username,
185 CSRFPreventionToken => $csrftoken,
186 %extra,
187 };
188 };
189
190 __PACKAGE__->register_method ({
191 name => 'get_ticket',
192 path => 'ticket',
193 method => 'GET',
194 permissions => { user => 'world' },
195 description => "Dummy. Useful for formatters which want to provide a login page.",
196 parameters => {
197 additionalProperties => 0,
198 },
199 returns => { type => "null" },
200 code => sub { return undef; }});
201
202 __PACKAGE__->register_method ({
203 name => 'create_ticket',
204 path => 'ticket',
205 method => 'POST',
206 permissions => {
207 description => "You need to pass valid credientials.",
208 user => 'world'
209 },
210 protected => 1, # else we can't access shadow files
211 allowtoken => 0, # we don't want tokens to create tickets
212 description => "Create or verify authentication ticket.",
213 parameters => {
214 additionalProperties => 0,
215 properties => {
216 username => {
217 description => "User name",
218 type => 'string',
219 maxLength => 64,
220 completion => \&PVE::AccessControl::complete_username,
221 },
222 realm => get_standard_option('realm', {
223 description => "You can optionally pass the realm using this parameter. Normally the realm is simply added to the username <username>\@<relam>.",
224 optional => 1,
225 completion => \&PVE::AccessControl::complete_realm,
226 }),
227 password => {
228 description => "The secret password. This can also be a valid ticket.",
229 type => 'string',
230 },
231 otp => {
232 description => "One-time password for Two-factor authentication.",
233 type => 'string',
234 optional => 1,
235 },
236 path => {
237 description => "Verify ticket, and check if user have access 'privs' on 'path'",
238 type => 'string',
239 requires => 'privs',
240 optional => 1,
241 maxLength => 64,
242 },
243 privs => {
244 description => "Verify ticket, and check if user have access 'privs' on 'path'",
245 type => 'string' , format => 'pve-priv-list',
246 requires => 'path',
247 optional => 1,
248 maxLength => 64,
249 },
250 'new-format' => {
251 type => 'boolean',
252 description => 'This parameter is now ignored and assumed to be 1.',
253 optional => 1,
254 default => 1,
255 },
256 'tfa-challenge' => {
257 type => 'string',
258 description => "The signed TFA challenge string the user wants to respond to.",
259 optional => 1,
260 },
261 }
262 },
263 returns => {
264 type => "object",
265 properties => {
266 username => { type => 'string' },
267 ticket => { type => 'string', optional => 1},
268 CSRFPreventionToken => { type => 'string', optional => 1 },
269 clustername => { type => 'string', optional => 1 },
270 # cap => computed api permissions, unless there's a u2f challenge
271 }
272 },
273 code => sub {
274 my ($param) = @_;
275
276 my $username = $param->{username};
277 $username .= "\@$param->{realm}" if $param->{realm};
278
279 $username = PVE::AccessControl::lookup_username($username);
280 my $rpcenv = PVE::RPCEnvironment::get();
281
282 my $res;
283 eval {
284 # test if user exists and is enabled
285 $rpcenv->check_user_enabled($username);
286
287 if ($param->{path} && $param->{privs}) {
288 $res = verify_auth($rpcenv, $username, $param->{password}, $param->{otp},
289 $param->{path}, $param->{privs});
290 } else {
291 $res = create_ticket_do(
292 $rpcenv,
293 $username,
294 $param->{password},
295 $param->{otp},
296 $param->{'tfa-challenge'},
297 );
298 }
299 };
300 if (my $err = $@) {
301 my $clientip = $rpcenv->get_client_ip() || '';
302 syslog('err', "authentication failure; rhost=$clientip user=$username msg=$err");
303 # do not return any info to prevent user enumeration attacks
304 die PVE::Exception->new("authentication failure\n", code => 401);
305 }
306
307 $res->{cap} = $rpcenv->compute_api_permission($username)
308 if !defined($res->{NeedTFA});
309
310 my $clinfo = PVE::Cluster::get_clinfo();
311 if ($clinfo->{cluster}->{name} && $rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
312 $res->{clustername} = $clinfo->{cluster}->{name};
313 }
314
315 PVE::Cluster::log_msg('info', 'root@pam', "successful auth for user '$username'");
316
317 return $res;
318 }});
319
320 __PACKAGE__->register_method ({
321 name => 'change_password',
322 path => 'password',
323 method => 'PUT',
324 permissions => {
325 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.",
326 check => [ 'or',
327 ['userid-param', 'self'],
328 [ 'and',
329 [ 'userid-param', 'Realm.AllocateUser'],
330 [ 'userid-group', ['User.Modify']]
331 ]
332 ],
333 },
334 protected => 1, # else we can't access shadow files
335 allowtoken => 0, # we don't want tokens to change the regular user password
336 description => "Change user password.",
337 parameters => {
338 additionalProperties => 0,
339 properties => {
340 userid => get_standard_option('userid-completed'),
341 password => {
342 description => "The new password.",
343 type => 'string',
344 minLength => 5,
345 maxLength => 64,
346 },
347 'confirmation-password' => $PVE::API2::TFA::OPTIONAL_PASSWORD_SCHEMA,
348 }
349 },
350 returns => { type => "null" },
351 code => sub {
352 my ($param) = @_;
353
354 my $rpcenv = PVE::RPCEnvironment::get();
355 my $authuser = $rpcenv->get_user();
356
357 my ($userid, $ruid, $realm) = $rpcenv->reauth_user_for_user_modification(
358 $authuser,
359 $param->{userid},
360 $param->{'confirmation-password'},
361 'confirmation-password',
362 );
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 return $u2f;
392 }
393
394 sub get_u2f_instance {
395 my ($rpcenv, $publicKey, $keyHandle) = @_;
396
397 # We store the public key base64 encoded (as the api provides it in binary)
398 $publicKey = decode_base64($publicKey) if defined($publicKey);
399
400 my $u2fconfig = get_u2f_config();
401 my $u2f = PVE::U2F->new();
402
403 # via the 'Host' header (in case a node has multiple hosts available).
404 my $origin = $u2fconfig->{origin};
405 if (!defined($origin)) {
406 $origin = $rpcenv->get_request_host(1);
407 if ($origin) {
408 $origin = "https://$origin";
409 } else {
410 die "failed to figure out u2f origin\n";
411 }
412 }
413
414 my $appid = $u2fconfig->{appid} // $origin;
415 $u2f->set_appid($appid);
416 $u2f->set_origin($origin);
417 $u2f->set_publicKey($publicKey) if defined($publicKey);
418 $u2f->set_keyHandle($keyHandle) if defined($keyHandle);
419 return $u2f;
420 }
421
422 sub verify_user_tfa_config {
423 my ($type, $tfa_cfg, $value) = @_;
424
425 if (!defined($type)) {
426 die "missing tfa 'type'\n";
427 }
428
429 if ($type ne 'oath') {
430 die "invalid type for custom tfa authentication\n";
431 }
432
433 my $secret = $tfa_cfg->{keys}
434 or die "missing TOTP secret\n";
435 $tfa_cfg = $tfa_cfg->{config};
436 # Copy the hash to verify that we have no unexpected keys without modifying the original hash.
437 $tfa_cfg = {%$tfa_cfg};
438
439 # We can only verify 1 secret but oath_verify_otp allows multiple:
440 if (scalar(PVE::Tools::split_list($secret)) != 1) {
441 die "only exactly one secret key allowed\n";
442 }
443
444 my $digits = delete($tfa_cfg->{digits}) // 6;
445 my $step = delete($tfa_cfg->{step}) // 30;
446 # Maybe also this?
447 # my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
448
449 if (length(my $more = join(', ', keys %$tfa_cfg))) {
450 die "unexpected tfa config keys: $more\n";
451 }
452
453 PVE::OTP::oath_verify_otp($value, $secret, $step, $digits);
454 }
455
456
457 __PACKAGE__->register_method({
458 name => 'permissions',
459 path => 'permissions',
460 method => 'GET',
461 description => 'Retrieve effective permissions of given user/token.',
462 permissions => {
463 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.",
464 user => 'all',
465 },
466 parameters => {
467 additionalProperties => 0,
468 properties => {
469 userid => {
470 type => 'string',
471 description => "User ID or full API token ID",
472 pattern => $PVE::AccessControl::userid_or_token_regex,
473 optional => 1,
474 },
475 path => get_standard_option('acl-path', {
476 description => "Only dump this specific path, not the whole tree.",
477 optional => 1,
478 }),
479 },
480 },
481 returns => {
482 type => 'object',
483 description => 'Map of "path" => (Map of "privilege" => "propagate boolean").',
484 },
485 code => sub {
486 my ($param) = @_;
487
488 my $rpcenv = PVE::RPCEnvironment::get();
489
490 my $userid = $param->{userid};
491 if (defined($userid)) {
492 $rpcenv->check($rpcenv->get_user(), '/access', ['Sys.Audit']);
493 } else {
494 $userid = $rpcenv->get_user();
495 }
496
497 my $res;
498
499 if (my $path = $param->{path}) {
500 my $perms = $rpcenv->permissions($userid, $path);
501 if ($perms) {
502 $res = { $path => $perms };
503 } else {
504 $res = {};
505 }
506 } else {
507 $res = $rpcenv->get_effective_permissions($userid);
508 }
509
510 return $res;
511 }});
512
513 1;