]> git.proxmox.com Git - pve-access-control.git/blob - src/PVE/API2/TFA.pm
use statement fixup
[pve-access-control.git] / src / PVE / API2 / TFA.pm
1 package PVE::API2::TFA;
2
3 use strict;
4 use warnings;
5
6 use HTTP::Status qw(:constants);
7
8 use PVE::AccessControl;
9 use PVE::Cluster qw(cfs_read_file cfs_write_file);
10 use PVE::Exception qw(raise raise_perm_exc raise_param_exc);
11 use PVE::JSONSchema qw(get_standard_option);
12 use PVE::RPCEnvironment;
13 use PVE::SafeSyslog;
14
15 use PVE::API2::AccessControl; # for old login api get_u2f_instance method
16
17 use PVE::RESTHandler;
18
19 use base qw(PVE::RESTHandler);
20
21 my $OPTIONAL_PASSWORD_SCHEMA = {
22 description => "The current password.",
23 type => 'string',
24 optional => 1, # Only required if not root@pam
25 minLength => 5,
26 maxLength => 64
27 };
28
29 my $TFA_TYPE_SCHEMA = {
30 type => 'string',
31 description => 'TFA Entry Type.',
32 enum => [qw(totp u2f webauthn recovery yubico)],
33 };
34
35 my %TFA_INFO_PROPERTIES = (
36 id => {
37 type => 'string',
38 description => 'The id used to reference this entry.',
39 },
40 description => {
41 type => 'string',
42 description => 'User chosen description for this entry.',
43 },
44 created => {
45 type => 'integer',
46 description => 'Creation time of this entry as unix epoch.',
47 },
48 enable => {
49 type => 'boolean',
50 description => 'Whether this TFA entry is currently enabled.',
51 optional => 1,
52 default => 1,
53 },
54 );
55
56 my $TYPED_TFA_ENTRY_SCHEMA = {
57 type => 'object',
58 description => 'TFA Entry.',
59 properties => {
60 type => $TFA_TYPE_SCHEMA,
61 %TFA_INFO_PROPERTIES,
62 },
63 };
64
65 my $TFA_ID_SCHEMA = {
66 type => 'string',
67 description => 'A TFA entry id.',
68 };
69
70 my $TFA_UPDATE_INFO_SCHEMA = {
71 type => 'object',
72 properties => {
73 id => {
74 type => 'string',
75 description => 'The id of a newly added TFA entry.',
76 },
77 challenge => {
78 type => 'string',
79 optional => 1,
80 description =>
81 'When adding u2f entries, this contains a challenge the user must respond to in order'
82 .' to finish the registration.'
83 },
84 recovery => {
85 type => 'array',
86 optional => 1,
87 description =>
88 'When adding recovery codes, this contains the list of codes to be displayed to'
89 .' the user',
90 items => {
91 type => 'string',
92 description => 'A recovery entry.'
93 },
94 },
95 },
96 };
97
98 # Only root may modify root, regular users need to specify their password.
99 #
100 # Returns the userid returned from `verify_username`.
101 # Or ($userid, $realm) in list context.
102 my sub root_permission_check : prototype($$$$) {
103 my ($rpcenv, $authuser, $userid, $password) = @_;
104
105 ($userid, undef, my $realm) = PVE::AccessControl::verify_username($userid);
106 $rpcenv->check_user_exist($userid);
107
108 raise_perm_exc() if $userid eq 'root@pam' && $authuser ne 'root@pam';
109
110 # Regular users need to confirm their password to change TFA settings.
111 if ($authuser ne 'root@pam') {
112 raise_param_exc({ 'password' => 'password is required to modify TFA data' })
113 if !defined($password);
114
115 ($authuser, my $auth_username, my $auth_realm) =
116 PVE::AccessControl::verify_username($authuser);
117
118 my $domain_cfg = cfs_read_file('domains.cfg');
119 my $cfg = $domain_cfg->{ids}->{$auth_realm};
120 die "auth domain '$auth_realm' does not exist\n" if !$cfg;
121 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
122 $plugin->authenticate_user($cfg, $auth_realm, $auth_username, $password);
123 }
124
125 return wantarray ? ($userid, $realm) : $userid;
126 }
127
128 # Set TFA to enabled if $tfa_cfg is passed, or to disabled if $tfa_cfg is undef,
129 # When enabling we also merge the old user.cfg keys into the $tfa_cfg.
130 my sub set_user_tfa_enabled : prototype($$$) {
131 my ($userid, $realm, $tfa_cfg) = @_;
132
133 PVE::AccessControl::lock_user_config(sub {
134 my $user_cfg = cfs_read_file('user.cfg');
135 my $user = $user_cfg->{users}->{$userid};
136 my $keys = $user->{keys};
137 # When enabling, we convert old-old keys,
138 # When disabling, we shouldn't actually have old keys anymore, so if they are there,
139 # they'll be removed.
140 if ($tfa_cfg && $keys && $keys !~ /^x(?:!.*)?$/) {
141 my $domain_cfg = cfs_read_file('domains.cfg');
142 my $realm_cfg = $domain_cfg->{ids}->{$realm};
143 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
144
145 my $realm_tfa = $realm_cfg->{tfa};
146 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa) if $realm_tfa;
147
148 PVE::AccessControl::add_old_keys_to_realm_tfa($userid, $tfa_cfg, $realm_tfa, $keys);
149 }
150 $user->{keys} = $tfa_cfg ? 'x' : undef;
151 cfs_write_file("user.cfg", $user_cfg);
152 }, "enabling TFA for the user failed");
153 }
154
155 ### OLD API
156
157 __PACKAGE__->register_method({
158 name => 'verify_tfa',
159 path => '',
160 method => 'POST',
161 permissions => { user => 'all' },
162 protected => 1, # else we can't access shadow files
163 allowtoken => 0, # we don't want tokens to access TFA information
164 description => 'Finish a u2f challenge.',
165 parameters => {
166 additionalProperties => 0,
167 properties => {
168 response => {
169 type => 'string',
170 description => 'The response to the current authentication challenge.',
171 },
172 }
173 },
174 returns => {
175 type => 'object',
176 properties => {
177 ticket => { type => 'string' },
178 # cap
179 }
180 },
181 code => sub {
182 my ($param) = @_;
183
184 my $rpcenv = PVE::RPCEnvironment::get();
185 my $authuser = $rpcenv->get_user();
186 my ($username, undef, $realm) = PVE::AccessControl::verify_username($authuser);
187
188 my ($tfa_type, $tfa_data) = PVE::AccessControl::user_get_tfa($username, $realm, 0);
189 if (!defined($tfa_type)) {
190 raise('no u2f data available');
191 }
192 if ($tfa_type eq 'incompatible') {
193 raise('tfa entries incompatible with old login api');
194 }
195
196 eval {
197 if ($tfa_type eq 'u2f') {
198 my $challenge = $rpcenv->get_u2f_challenge()
199 or raise('no active challenge');
200
201 my $keyHandle = $tfa_data->{keyHandle};
202 my $publicKey = $tfa_data->{publicKey};
203 raise("incomplete u2f setup")
204 if !defined($keyHandle) || !defined($publicKey);
205
206 my $u2f = PVE::API2::AccessControl::get_u2f_instance($rpcenv, $publicKey, $keyHandle);
207 $u2f->set_challenge($challenge);
208
209 my ($counter, $present) = $u2f->auth_verify($param->{response});
210 # Do we want to do anything with these?
211 } else {
212 # sanity check before handing off to the verification code:
213 my $keys = $tfa_data->{keys} or die "missing tfa keys\n";
214 my $config = $tfa_data->{config} or die "bad tfa entry\n";
215 PVE::AccessControl::verify_one_time_pw($tfa_type, $authuser, $keys, $config, $param->{response});
216 }
217 };
218 if (my $err = $@) {
219 my $clientip = $rpcenv->get_client_ip() || '';
220 syslog('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
221 die PVE::Exception->new("authentication failure\n", code => 401);
222 }
223
224 return {
225 ticket => PVE::AccessControl::assemble_ticket($authuser),
226 cap => $rpcenv->compute_api_permission($authuser),
227 }
228 }});
229
230 ### END OLD API
231
232 __PACKAGE__->register_method ({
233 name => 'list_user_tfa',
234 path => '{userid}',
235 method => 'GET',
236 permissions => {
237 check => [ 'or',
238 ['userid-param', 'self'],
239 ['userid-group', ['User.Modify', 'Sys.Audit']],
240 ],
241 },
242 protected => 1, # else we can't access shadow files
243 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
244 description => 'List TFA configurations of users.',
245 parameters => {
246 additionalProperties => 0,
247 properties => {
248 userid => get_standard_option('userid', {
249 completion => \&PVE::AccessControl::complete_username,
250 }),
251 }
252 },
253 returns => {
254 description => "A list of the user's TFA entries.",
255 type => 'array',
256 items => $TYPED_TFA_ENTRY_SCHEMA,
257 },
258 code => sub {
259 my ($param) = @_;
260 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
261 return $tfa_cfg->api_list_user_tfa($param->{userid});
262 }});
263
264 __PACKAGE__->register_method ({
265 name => 'get_tfa_entry',
266 path => '{userid}/{id}',
267 method => 'GET',
268 permissions => {
269 check => [ 'or',
270 ['userid-param', 'self'],
271 ['userid-group', ['User.Modify', 'Sys.Audit']],
272 ],
273 },
274 protected => 1, # else we can't access shadow files
275 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
276 description => 'Fetch a requested TFA entry if present.',
277 parameters => {
278 additionalProperties => 0,
279 properties => {
280 userid => get_standard_option('userid', {
281 completion => \&PVE::AccessControl::complete_username,
282 }),
283 id => $TFA_ID_SCHEMA,
284 }
285 },
286 returns => $TYPED_TFA_ENTRY_SCHEMA,
287 code => sub {
288 my ($param) = @_;
289 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
290 my $id = $param->{id};
291 my $entry = $tfa_cfg->api_get_tfa_entry($param->{userid}, $id);
292 raise("No such tfa entry '$id'", code => HTTP::Status::HTTP_NOT_FOUND) if !$entry;
293 return $entry;
294 }});
295
296 __PACKAGE__->register_method ({
297 name => 'delete_tfa',
298 path => '{userid}/{id}',
299 method => 'DELETE',
300 permissions => {
301 check => [ 'or',
302 ['userid-param', 'self'],
303 ['userid-group', ['User.Modify']],
304 ],
305 },
306 protected => 1, # else we can't access shadow files
307 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
308 description => 'Delete a TFA entry by ID.',
309 parameters => {
310 additionalProperties => 0,
311 properties => {
312 userid => get_standard_option('userid', {
313 completion => \&PVE::AccessControl::complete_username,
314 }),
315 id => $TFA_ID_SCHEMA,
316 password => $OPTIONAL_PASSWORD_SCHEMA,
317 }
318 },
319 returns => { type => 'null' },
320 code => sub {
321 my ($param) = @_;
322
323 PVE::AccessControl::assert_new_tfa_config_available();
324
325 my $rpcenv = PVE::RPCEnvironment::get();
326 my $authuser = $rpcenv->get_user();
327 my $userid =
328 root_permission_check($rpcenv, $authuser, $param->{userid}, $param->{password});
329
330 my $has_entries_left = PVE::AccessControl::lock_tfa_config(sub {
331 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
332 my $has_entries_left = $tfa_cfg->api_delete_tfa($userid, $param->{id});
333 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
334 return $has_entries_left;
335 });
336 if (!$has_entries_left) {
337 set_user_tfa_enabled($userid, undef, undef);
338 }
339 }});
340
341 __PACKAGE__->register_method ({
342 name => 'list_tfa',
343 path => '',
344 method => 'GET',
345 permissions => {
346 description => "Returns all or just the logged-in user, depending on privileges.",
347 user => 'all',
348 },
349 protected => 1, # else we can't access shadow files
350 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
351 description => 'List TFA configurations of users.',
352 parameters => {
353 additionalProperties => 0,
354 properties => {}
355 },
356 returns => {
357 description => "The list tuples of user and TFA entries.",
358 type => 'array',
359 items => {
360 type => 'object',
361 properties => {
362 userid => {
363 type => 'string',
364 description => 'User this entry belongs to.',
365 },
366 entries => {
367 type => 'array',
368 items => $TYPED_TFA_ENTRY_SCHEMA,
369 },
370 },
371 },
372 },
373 code => sub {
374 my ($param) = @_;
375
376 my $rpcenv = PVE::RPCEnvironment::get();
377 my $authuser = $rpcenv->get_user();
378
379 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
380 my $entries = $tfa_cfg->api_list_tfa($authuser, 1);
381
382 my $privs = [ 'User.Modify', 'Sys.Audit' ];
383 if ($rpcenv->check_any($authuser, "/access/groups", $privs, 1)) {
384 # can modify all
385 return $entries;
386 }
387
388 my $groups = $rpcenv->filter_groups($authuser, $privs, 1);
389 my $allowed_users = $rpcenv->group_member_join([keys %$groups]);
390 return [
391 grep {
392 my $userid = $_->{userid};
393 $userid eq $authuser || $allowed_users->{$userid}
394 } $entries->@*
395 ];
396 }});
397
398 __PACKAGE__->register_method ({
399 name => 'add_tfa_entry',
400 path => '{userid}',
401 method => 'POST',
402 permissions => {
403 check => [ 'or',
404 ['userid-param', 'self'],
405 ['userid-group', ['User.Modify']],
406 ],
407 },
408 protected => 1, # else we can't access shadow files
409 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
410 description => 'Add a TFA entry for a user.',
411 parameters => {
412 additionalProperties => 0,
413 properties => {
414 userid => get_standard_option('userid', {
415 completion => \&PVE::AccessControl::complete_username,
416 }),
417 type => $TFA_TYPE_SCHEMA,
418 description => {
419 type => 'string',
420 description => 'A description to distinguish multiple entries from one another',
421 maxLength => 255,
422 optional => 1,
423 },
424 totp => {
425 type => 'string',
426 description => "A totp URI.",
427 optional => 1,
428 },
429 value => {
430 type => 'string',
431 description =>
432 'The current value for the provided totp URI, or a Webauthn/U2F'
433 .' challenge response',
434 optional => 1,
435 },
436 challenge => {
437 type => 'string',
438 description => 'When responding to a u2f challenge: the original challenge string',
439 optional => 1,
440 },
441 password => $OPTIONAL_PASSWORD_SCHEMA,
442 },
443 },
444 returns => $TFA_UPDATE_INFO_SCHEMA,
445 code => sub {
446 my ($param) = @_;
447
448 PVE::AccessControl::assert_new_tfa_config_available();
449
450 my $rpcenv = PVE::RPCEnvironment::get();
451 my $authuser = $rpcenv->get_user();
452 my ($userid, $realm) =
453 root_permission_check($rpcenv, $authuser, $param->{userid}, $param->{password});
454
455 my $type = delete $param->{type};
456 my $value = delete $param->{value};
457 if ($type eq 'yubico') {
458 $value = validate_yubico_otp($userid, $realm, $value);
459 }
460
461 return PVE::AccessControl::lock_tfa_config(sub {
462 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
463
464 set_user_tfa_enabled($userid, $realm, $tfa_cfg);
465
466 PVE::AccessControl::configure_u2f_and_wa($tfa_cfg);
467
468 my $response = $tfa_cfg->api_add_tfa_entry(
469 $userid,
470 $param->{description},
471 $param->{totp},
472 $value,
473 $param->{challenge},
474 $type,
475 );
476
477 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
478
479 return $response;
480 });
481 }});
482
483 sub validate_yubico_otp : prototype($$) {
484 my ($userid, $realm, $value) = @_;
485
486 my $domain_cfg = cfs_read_file('domains.cfg');
487 my $realm_cfg = $domain_cfg->{ids}->{$realm};
488 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
489
490 my $realm_tfa = $realm_cfg->{tfa};
491 die "no yubico otp configuration available for realm $realm\n"
492 if !$realm_tfa;
493
494 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa);
495 die "realm is not setup for Yubico OTP\n"
496 if !$realm_tfa || $realm_tfa->{type} ne 'yubico';
497
498 my $public_key = substr($value, 0, 12);
499
500 PVE::AccessControl::authenticate_yubico_do($value, $public_key, $realm_tfa);
501
502 return $public_key;
503 }
504
505 __PACKAGE__->register_method ({
506 name => 'update_tfa_entry',
507 path => '{userid}/{id}',
508 method => 'PUT',
509 permissions => {
510 check => [ 'or',
511 ['userid-param', 'self'],
512 ['userid-group', ['User.Modify']],
513 ],
514 },
515 protected => 1, # else we can't access shadow files
516 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
517 description => 'Add a TFA entry for a user.',
518 parameters => {
519 additionalProperties => 0,
520 properties => {
521 userid => get_standard_option('userid', {
522 completion => \&PVE::AccessControl::complete_username,
523 }),
524 id => $TFA_ID_SCHEMA,
525 description => {
526 type => 'string',
527 description => 'A description to distinguish multiple entries from one another',
528 maxLength => 255,
529 optional => 1,
530 },
531 enable => {
532 type => 'boolean',
533 description => 'Whether the entry should be enabled for login.',
534 optional => 1,
535 },
536 password => $OPTIONAL_PASSWORD_SCHEMA,
537 },
538 },
539 returns => { type => 'null' },
540 code => sub {
541 my ($param) = @_;
542
543 PVE::AccessControl::assert_new_tfa_config_available();
544
545 my $rpcenv = PVE::RPCEnvironment::get();
546 my $authuser = $rpcenv->get_user();
547 my $userid =
548 root_permission_check($rpcenv, $authuser, $param->{userid}, $param->{password});
549
550 PVE::AccessControl::lock_tfa_config(sub {
551 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
552
553 $tfa_cfg->api_update_tfa_entry(
554 $userid,
555 $param->{id},
556 $param->{description},
557 $param->{enable},
558 );
559
560 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
561 });
562 }});
563
564 1;