]> git.proxmox.com Git - pve-access-control.git/blob - src/PVE/API2/TFA.pm
support registering yubico otp keys
[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 ### OLD API
123
124 __PACKAGE__->register_method({
125 name => 'verify_tfa',
126 path => '',
127 method => 'POST',
128 permissions => { user => 'all' },
129 protected => 1, # else we can't access shadow files
130 allowtoken => 0, # we don't want tokens to access TFA information
131 description => 'Finish a u2f challenge.',
132 parameters => {
133 additionalProperties => 0,
134 properties => {
135 response => {
136 type => 'string',
137 description => 'The response to the current authentication challenge.',
138 },
139 }
140 },
141 returns => {
142 type => 'object',
143 properties => {
144 ticket => { type => 'string' },
145 # cap
146 }
147 },
148 code => sub {
149 my ($param) = @_;
150
151 my $rpcenv = PVE::RPCEnvironment::get();
152 my $authuser = $rpcenv->get_user();
153 my ($username, undef, $realm) = PVE::AccessControl::verify_username($authuser);
154
155 my ($tfa_type, $tfa_data) = PVE::AccessControl::user_get_tfa($username, $realm, 0);
156 if (!defined($tfa_type)) {
157 raise('no u2f data available');
158 }
159
160 eval {
161 if ($tfa_type eq 'u2f') {
162 my $challenge = $rpcenv->get_u2f_challenge()
163 or raise('no active challenge');
164
165 my $keyHandle = $tfa_data->{keyHandle};
166 my $publicKey = $tfa_data->{publicKey};
167 raise("incomplete u2f setup")
168 if !defined($keyHandle) || !defined($publicKey);
169
170 my $u2f = PVE::API2::AccessControl::get_u2f_instance($rpcenv, $publicKey, $keyHandle);
171 $u2f->set_challenge($challenge);
172
173 my ($counter, $present) = $u2f->auth_verify($param->{response});
174 # Do we want to do anything with these?
175 } else {
176 # sanity check before handing off to the verification code:
177 my $keys = $tfa_data->{keys} or die "missing tfa keys\n";
178 my $config = $tfa_data->{config} or die "bad tfa entry\n";
179 PVE::AccessControl::verify_one_time_pw($tfa_type, $authuser, $keys, $config, $param->{response});
180 }
181 };
182 if (my $err = $@) {
183 my $clientip = $rpcenv->get_client_ip() || '';
184 syslog('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
185 die PVE::Exception->new("authentication failure\n", code => 401);
186 }
187
188 return {
189 ticket => PVE::AccessControl::assemble_ticket($authuser),
190 cap => $rpcenv->compute_api_permission($authuser),
191 }
192 }});
193
194 ### END OLD API
195
196 __PACKAGE__->register_method ({
197 name => 'list_user_tfa',
198 path => '{userid}',
199 method => 'GET',
200 permissions => {
201 check => [ 'or',
202 ['userid-param', 'self'],
203 ['userid-group', ['User.Modify', 'Sys.Audit']],
204 ],
205 },
206 protected => 1, # else we can't access shadow files
207 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
208 description => 'List TFA configurations of users.',
209 parameters => {
210 additionalProperties => 0,
211 properties => {
212 userid => get_standard_option('userid', {
213 completion => \&PVE::AccessControl::complete_username,
214 }),
215 }
216 },
217 returns => {
218 description => "A list of the user's TFA entries.",
219 type => 'array',
220 items => $TYPED_TFA_ENTRY_SCHEMA,
221 },
222 code => sub {
223 my ($param) = @_;
224 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
225 return $tfa_cfg->api_list_user_tfa($param->{userid});
226 }});
227
228 __PACKAGE__->register_method ({
229 name => 'get_tfa_entry',
230 path => '{userid}/{id}',
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 => 'Fetch a requested TFA entry if present.',
241 parameters => {
242 additionalProperties => 0,
243 properties => {
244 userid => get_standard_option('userid', {
245 completion => \&PVE::AccessControl::complete_username,
246 }),
247 id => $TFA_ID_SCHEMA,
248 }
249 },
250 returns => $TYPED_TFA_ENTRY_SCHEMA,
251 code => sub {
252 my ($param) = @_;
253 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
254 my $id = $param->{id};
255 my $entry = $tfa_cfg->api_get_tfa_entry($param->{userid}, $id);
256 raise("No such tfa entry '$id'", 404) if !$entry;
257 return $entry;
258 }});
259
260 __PACKAGE__->register_method ({
261 name => 'delete_tfa',
262 path => '{userid}/{id}',
263 method => 'DELETE',
264 permissions => {
265 check => [ 'or',
266 ['userid-param', 'self'],
267 ['userid-group', ['User.Modify']],
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 => 'Delete a TFA entry by ID.',
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 password => $OPTIONAL_PASSWORD_SCHEMA,
281 }
282 },
283 returns => { type => 'null' },
284 code => sub {
285 my ($param) = @_;
286
287 PVE::AccessControl::assert_new_tfa_config_available();
288
289 my $rpcenv = PVE::RPCEnvironment::get();
290 my $authuser = $rpcenv->get_user();
291 my $userid =
292 root_permission_check($rpcenv, $authuser, $param->{userid}, $param->{password});
293
294 return PVE::AccessControl::lock_tfa_config(sub {
295 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
296 $tfa_cfg->api_delete_tfa($userid, $param->{id});
297 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
298 });
299 }});
300
301 __PACKAGE__->register_method ({
302 name => 'list_tfa',
303 path => '',
304 method => 'GET',
305 permissions => {
306 description => "Returns all or just the logged-in user, depending on privileges.",
307 user => 'all',
308 },
309 protected => 1, # else we can't access shadow files
310 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
311 description => 'List TFA configurations of users.',
312 parameters => {
313 additionalProperties => 0,
314 properties => {}
315 },
316 returns => {
317 description => "The list tuples of user and TFA entries.",
318 type => 'array',
319 items => {
320 type => 'object',
321 properties => {
322 userid => {
323 type => 'string',
324 description => 'User this entry belongs to.',
325 },
326 entries => {
327 type => 'array',
328 items => $TYPED_TFA_ENTRY_SCHEMA,
329 },
330 },
331 },
332 },
333 code => sub {
334 my ($param) = @_;
335
336 my $rpcenv = PVE::RPCEnvironment::get();
337 my $authuser = $rpcenv->get_user();
338 my $top_level_allowed = ($authuser eq 'root@pam');
339
340 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
341 return $tfa_cfg->api_list_tfa($authuser, $top_level_allowed);
342 }});
343
344 __PACKAGE__->register_method ({
345 name => 'add_tfa_entry',
346 path => '{userid}',
347 method => 'POST',
348 permissions => {
349 check => [ 'or',
350 ['userid-param', 'self'],
351 ['userid-group', ['User.Modify']],
352 ],
353 },
354 protected => 1, # else we can't access shadow files
355 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
356 description => 'Add a TFA entry for a user.',
357 parameters => {
358 additionalProperties => 0,
359 properties => {
360 userid => get_standard_option('userid', {
361 completion => \&PVE::AccessControl::complete_username,
362 }),
363 type => $TFA_TYPE_SCHEMA,
364 description => {
365 type => 'string',
366 description => 'A description to distinguish multiple entries from one another',
367 maxLength => 255,
368 optional => 1,
369 },
370 totp => {
371 type => 'string',
372 description => "A totp URI.",
373 optional => 1,
374 },
375 value => {
376 type => 'string',
377 description =>
378 'The current value for the provided totp URI, or a Webauthn/U2F'
379 .' challenge response',
380 optional => 1,
381 },
382 challenge => {
383 type => 'string',
384 description => 'When responding to a u2f challenge: the original challenge string',
385 optional => 1,
386 },
387 password => $OPTIONAL_PASSWORD_SCHEMA,
388 },
389 },
390 returns => $TFA_UPDATE_INFO_SCHEMA,
391 code => sub {
392 my ($param) = @_;
393
394 PVE::AccessControl::assert_new_tfa_config_available();
395
396 my $rpcenv = PVE::RPCEnvironment::get();
397 my $authuser = $rpcenv->get_user();
398 my ($userid, $realm) =
399 root_permission_check($rpcenv, $authuser, $param->{userid}, $param->{password});
400
401 my $type = delete $param->{type};
402 my $value = delete $param->{value};
403 if ($type eq 'yubico') {
404 $value = validate_yubico_otp($userid, $realm, $value);
405 }
406
407 return PVE::AccessControl::lock_tfa_config(sub {
408 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
409 PVE::AccessControl::configure_u2f_and_wa($tfa_cfg);
410
411 my $response = $tfa_cfg->api_add_tfa_entry(
412 $userid,
413 $param->{description},
414 $param->{totp},
415 $value,
416 $param->{challenge},
417 $type,
418 );
419
420 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
421
422 return $response;
423 });
424 }});
425
426 sub validate_yubico_otp : prototype($$) {
427 my ($userid, $realm, $value) = @_;
428
429 my $domain_cfg = cfs_read_file('domains.cfg');
430 my $realm_cfg = $domain_cfg->{ids}->{$realm};
431 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
432
433 my $realm_tfa = $realm_cfg->{tfa};
434 die "no yubico otp configuration available for realm $realm\n"
435 if !$realm_tfa;
436
437 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa);
438 die "realm is not setup for Yubico OTP\n"
439 if !$realm_tfa || $realm_tfa->{type} ne 'yubico';
440
441 my $public_key = substr($value, 0, 12);
442
443 PVE::AccessControl::authenticate_yubico_do($value, $public_key, $realm_tfa);
444
445 return $public_key;
446 }
447
448 __PACKAGE__->register_method ({
449 name => 'update_tfa_entry',
450 path => '{userid}/{id}',
451 method => 'PUT',
452 permissions => {
453 check => [ 'or',
454 ['userid-param', 'self'],
455 ['userid-group', ['User.Modify']],
456 ],
457 },
458 protected => 1, # else we can't access shadow files
459 allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
460 description => 'Add a TFA entry for a user.',
461 parameters => {
462 additionalProperties => 0,
463 properties => {
464 userid => get_standard_option('userid', {
465 completion => \&PVE::AccessControl::complete_username,
466 }),
467 id => $TFA_ID_SCHEMA,
468 description => {
469 type => 'string',
470 description => 'A description to distinguish multiple entries from one another',
471 maxLength => 255,
472 optional => 1,
473 },
474 enable => {
475 type => 'boolean',
476 description => 'Whether the entry should be enabled for login.',
477 optional => 1,
478 },
479 password => $OPTIONAL_PASSWORD_SCHEMA,
480 },
481 },
482 returns => { type => 'null' },
483 code => sub {
484 my ($param) = @_;
485
486 PVE::AccessControl::assert_new_tfa_config_available();
487
488 my $rpcenv = PVE::RPCEnvironment::get();
489 my $authuser = $rpcenv->get_user();
490 my $userid =
491 root_permission_check($rpcenv, $authuser, $param->{userid}, $param->{password});
492
493 PVE::AccessControl::lock_tfa_config(sub {
494 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
495
496 $tfa_cfg->api_update_tfa_entry(
497 $userid,
498 $param->{id},
499 $param->{description},
500 $param->{enable},
501 );
502
503 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
504 });
505 }});
506
507 1;