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