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