]> git.proxmox.com Git - pve-access-control.git/blame - src/PVE/AccessControl.pm
merge old user.cfg keys to tfa config when adding entries
[pve-access-control.git] / src / PVE / AccessControl.pm
CommitLineData
2c3a6c0a
DM
1package PVE::AccessControl;
2
3use strict;
7c410d63 4use warnings;
2c3a6c0a
DM
5use Encode;
6use Crypt::OpenSSL::Random;
7use Crypt::OpenSSL::RSA;
cee5583b 8use Net::SSLeay;
25167526 9use Net::IP;
0fe62fa8 10use MIME::Base32;
2c3a6c0a
DM
11use MIME::Base64;
12use Digest::SHA;
21800a71
FG
13use IO::File;
14use File::stat;
fda8ca85 15use JSON;
2ee46655 16use Scalar::Util 'weaken';
0fe62fa8 17use URI::Escape;
a1f8aaae 18
972859d1 19use PVE::OTP;
a1f8aaae 20use PVE::Ticket;
2c3a6c0a
DM
21use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
22use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
ab7b19b5 23use PVE::JSONSchema qw(register_standard_option get_standard_option);
5bb4e06a 24
57098eb8
WB
25use PVE::RS::TFA;
26
5bb4e06a
DM
27use PVE::Auth::Plugin;
28use PVE::Auth::AD;
29use PVE::Auth::LDAP;
30use PVE::Auth::PVE;
31use PVE::Auth::PAM;
52d1c1b9 32use PVE::Auth::OpenId;
2c3a6c0a 33
5bb4e06a
DM
34# load and initialize all plugins
35
36PVE::Auth::AD->register();
37PVE::Auth::LDAP->register();
38PVE::Auth::PVE->register();
39PVE::Auth::PAM->register();
52d1c1b9 40PVE::Auth::OpenId->register();
5bb4e06a
DM
41PVE::Auth::Plugin->init();
42
2c3a6c0a
DM
43# $authdir must be writable by root only!
44my $confdir = "/etc/pve";
45my $authdir = "$confdir/priv";
21800a71 46
2c3a6c0a
DM
47my $pve_www_key_fn = "$confdir/pve-www.key";
48
21800a71
FG
49my $pve_auth_key_files = {
50 priv => "$authdir/authkey.key",
51 pub => "$confdir/authkey.pub",
52 pubold => "$confdir/authkey.pub.old",
53};
54
55my $pve_auth_key_cache = {};
56
243262f1 57my $ticket_lifetime = 3600 * 2; # 2 hours
8304b226 58my $auth_graceperiod = 60 * 5; # 5 minutes
243262f1 59my $authkey_lifetime = 3600 * 24; # rotate every 24 hours
2c3a6c0a
DM
60
61Crypt::OpenSSL::RSA->import_random_seed();
62
d7e8d24e
TL
63cfs_register_file('user.cfg', \&parse_user_config, \&write_user_config);
64cfs_register_file('priv/tfa.cfg', \&parse_priv_tfa_config, \&write_priv_tfa_config);
2c3a6c0a 65
5bb4e06a
DM
66sub verify_username {
67 PVE::Auth::Plugin::verify_username(@_);
2c3a6c0a
DM
68}
69
5bb4e06a
DM
70sub pve_verify_realm {
71 PVE::Auth::Plugin::pve_verify_realm(@_);
2c3a6c0a
DM
72}
73
2ee46655
WB
74# Locking both config files together is only ever allowed in one order:
75# 1) tfa config
76# 2) user config
77# If we permit the other way round, too, we might end up deadlocking!
78my $user_config_locked;
5bb4e06a 79sub lock_user_config {
2c3a6c0a
DM
80 my ($code, $errmsg) = @_;
81
2ee46655
WB
82 my $locked = 1;
83 $user_config_locked = \$locked;
84 weaken $user_config_locked; # make this scope guard signal safe...
85
5bb4e06a 86 cfs_lock_file("user.cfg", undef, $code);
2ee46655 87 $user_config_locked = undef;
5bb4e06a 88 if (my $err = $@) {
2c3a6c0a
DM
89 $errmsg ? die "$errmsg: $err" : die $err;
90 }
91}
92
07692c72
WB
93sub lock_tfa_config {
94 my ($code, $errmsg) = @_;
95
2ee46655
WB
96 die "tfa config lock cannot be acquired while holding user config lock\n"
97 if ($user_config_locked && $$user_config_locked);
98
07692c72
WB
99 my $res = cfs_lock_file("priv/tfa.cfg", undef, $code);
100 if (my $err = $@) {
101 $errmsg ? die "$errmsg: $err" : die $err;
102 }
103
104 return $res;
105}
106
21800a71
FG
107my $cache_read_key = sub {
108 my ($type) = @_;
109
110 my $path = $pve_auth_key_files->{$type};
111
112 my $read_key_and_mtime = sub {
113 my $fh = IO::File->new($path, "r");
114
115 return undef if !defined($fh);
116
117 my $st = stat($fh);
118 my $pem = PVE::Tools::safe_read_from($fh, 0, 0, $path);
119
120 close $fh;
121
122 my $key;
123 if ($type eq 'pub' || $type eq 'pubold') {
124 $key = eval { Crypt::OpenSSL::RSA->new_public_key($pem); };
125 } elsif ($type eq 'priv') {
126 $key = eval { Crypt::OpenSSL::RSA->new_private_key($pem); };
127 } else {
128 die "Invalid authkey type '$type'\n";
129 }
130
131 return { key => $key, mtime => $st->mtime };
132 };
133
134 if (!defined($pve_auth_key_cache->{$type})) {
135 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
136 } else {
137 my $st = stat($path);
138 if (!$st || $st->mtime != $pve_auth_key_cache->{$type}->{mtime}) {
139 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
140 }
141 }
142
143 return $pve_auth_key_cache->{$type};
144};
145
66931b11 146sub get_pubkey {
21800a71
FG
147 my ($old) = @_;
148
149 my $type = $old ? 'pubold' : 'pub';
150
151 my $res = $cache_read_key->($type);
152 return undef if !defined($res);
153
154 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
155}
156
157sub get_privkey {
158 my $res = $cache_read_key->('priv');
2c3a6c0a 159
21800a71
FG
160 if (!defined($res) || !check_authkey(1)) {
161 rotate_authkey();
162 $res = $cache_read_key->('priv');
163 }
2c3a6c0a 164
21800a71
FG
165 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
166}
2c3a6c0a 167
21800a71
FG
168sub check_authkey {
169 my ($quiet) = @_;
170
171 # skip check if non-quorate, as rotation is not possible anyway
172 return 1 if !PVE::Cluster::check_cfs_quorum(1);
173
174 my ($pub_key, $mtime) = get_pubkey();
175 if (!$pub_key) {
176 warn "auth key pair missing, generating new one..\n" if !$quiet;
177 return 0;
178 } else {
9de25de8
TL
179 my $now = time();
180 if ($now - $mtime >= $authkey_lifetime) {
21800a71
FG
181 warn "auth key pair too old, rotating..\n" if !$quiet;;
182 return 0;
9de25de8
TL
183 } elsif ($mtime > $now + $auth_graceperiod) {
184 # a nodes RTC had a time set in the future during key generation -> ticket
185 # validity is clamped to 0+5 min grace period until now >= mtime again
186 my (undef, $old_mtime) = get_pubkey(1);
187 if ($old_mtime && $mtime >= $old_mtime && $mtime - $old_mtime < $ticket_lifetime) {
188 warn "auth key pair generated in the future (key $mtime > host $now),"
189 ." but old key still exists and in valid grace period so avoid automatic"
190 ." fixup. Cluster time not in sync?\n" if !$quiet;
191 return 1;
192 }
193 warn "auth key pair generated in the future (key $mtime > host $now), rotating..\n" if !$quiet;
194 return 0;
21800a71
FG
195 } else {
196 warn "auth key new enough, skipping rotation\n" if !$quiet;;
197 return 1;
198 }
199 }
200}
2c3a6c0a 201
21800a71
FG
202sub rotate_authkey {
203 return if $authkey_lifetime == 0;
204
03593f3d 205 PVE::Cluster::cfs_lock_authkey(undef, sub {
21800a71
FG
206 # re-check with lock to avoid double rotation in clusters
207 return if check_authkey();
208
209 my $old = get_pubkey();
e770e667 210 my $new = Crypt::OpenSSL::RSA->generate_key(2048);
21800a71
FG
211
212 if ($old) {
213 eval {
214 my $pem = $old->get_public_key_x509_string();
b8055a4f 215 # mtime is used for caching and ticket age range calculation
21800a71
FG
216 PVE::Tools::file_set_contents($pve_auth_key_files->{pubold}, $pem);
217 };
218 die "Failed to store old auth key: $@\n" if $@;
219 }
220
21800a71
FG
221 eval {
222 my $pem = $new->get_public_key_x509_string();
b8055a4f
FG
223 # mtime is used for caching and ticket age range calculation,
224 # should be close to that of pubold above
21800a71
FG
225 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
226 };
227 if ($@) {
228 if ($old) {
229 warn "Failed to store new auth key - $@\n";
230 warn "Reverting to previous auth key\n";
231 eval {
232 my $pem = $old->get_public_key_x509_string();
233 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
234 };
235 die "Failed to restore old auth key: $@\n" if $@;
236 } else {
237 die "Failed to store new auth key - $@\n";
238 }
239 }
240
241 eval {
242 my $pem = $new->get_private_key_string();
243 PVE::Tools::file_set_contents($pve_auth_key_files->{priv}, $pem);
244 };
245 if ($@) {
246 warn "Failed to store new auth key - $@\n";
247 warn "Deleting auth key to force regeneration\n";
248 unlink $pve_auth_key_files->{pub};
249 unlink $pve_auth_key_files->{priv};
250 }
251 });
252 die $@ if $@;
2c3a6c0a
DM
253}
254
571e9d06
FG
255PVE::JSONSchema::register_standard_option('tokenid', {
256 description => "API token identifier.",
257 type => "string",
258 format => "pve-tokenid",
259});
260
28e3dc05
FG
261our $token_subid_regex = $PVE::Auth::Plugin::realm_regex;
262
263# username@realm username realm tokenid
264our $token_full_regex = qr/((${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex}))!(${token_subid_regex})/;
265
266our $userid_or_token_regex = qr/^$PVE::Auth::Plugin::user_regex\@$PVE::Auth::Plugin::realm_regex(?:!$token_subid_regex)?$/;
267
268sub split_tokenid {
269 my ($tokenid, $noerr) = @_;
270
271 if ($tokenid =~ /^${token_full_regex}$/) {
272 return ($1, $4);
273 }
274
275 die "'$tokenid' is not a valid token ID - not able to split into user and token parts\n" if !$noerr;
276
277 return undef;
278}
279
280sub join_tokenid {
281 my ($username, $tokensubid) = @_;
282
283 my $joined = "${username}!${tokensubid}";
284
285 return pve_verify_tokenid($joined);
286}
287
288PVE::JSONSchema::register_format('pve-tokenid', \&pve_verify_tokenid);
289sub pve_verify_tokenid {
290 my ($tokenid, $noerr) = @_;
291
292 if ($tokenid =~ /^${token_full_regex}$/) {
293 return wantarray ? ($tokenid, $2, $3, $4) : $tokenid;
294 }
295
296 die "value '$tokenid' does not look like a valid token ID\n" if !$noerr;
297
298 return undef;
299}
300
301
2c3a6c0a 302my $csrf_prevention_secret;
e149b1c6 303my $csrf_prevention_secret_legacy;
2c3a6c0a
DM
304my $get_csrfr_secret = sub {
305 if (!$csrf_prevention_secret) {
66931b11 306 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
51e6f56d 307 $csrf_prevention_secret = Digest::SHA::hmac_sha256_base64($input);
e149b1c6 308 $csrf_prevention_secret_legacy = Digest::SHA::sha1_base64($input);
2c3a6c0a
DM
309 }
310 return $csrf_prevention_secret;
311};
312
313sub assemble_csrf_prevention_token {
314 my ($username) = @_;
315
a1f8aaae 316 my $secret = &$get_csrfr_secret();
2c3a6c0a 317
a1f8aaae 318 return PVE::Ticket::assemble_csrf_prevention_token ($secret, $username);
2c3a6c0a
DM
319}
320
321sub verify_csrf_prevention_token {
322 my ($username, $token, $noerr) = @_;
323
e149b1c6
TL
324 my $secret = $get_csrfr_secret->();
325
326 # FIXME: remove with PVE 7 and/or refactor all into PVE::Ticket ?
327 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
328 my $sig = $2;
329 if (length($sig) == 27) {
330 # the legacy secret got populated by above get_csrfr_secret call
331 $secret = $csrf_prevention_secret_legacy;
332 }
333 }
2c3a6c0a 334
a1f8aaae 335 return PVE::Ticket::verify_csrf_prevention_token(
8304b226 336 $secret, $username, $token, -$auth_graceperiod, $ticket_lifetime, $noerr);
2c3a6c0a
DM
337}
338
21800a71
FG
339my $get_ticket_age_range = sub {
340 my ($now, $mtime, $rotated) = @_;
341
342 my $key_age = $now - $mtime;
343 $key_age = 0 if $key_age < 0;
344
8304b226 345 my $min = -$auth_graceperiod;
21800a71
FG
346 my $max = $ticket_lifetime;
347
348 if ($rotated) {
349 # ticket creation after rotation is not allowed
8304b226 350 $min = $key_age - $auth_graceperiod;
21800a71
FG
351 } else {
352 if ($key_age > $authkey_lifetime && $authkey_lifetime > 0) {
353 if (PVE::Cluster::check_cfs_quorum(1)) {
354 # key should have been rotated, clamp range accordingly
355 $min = $key_age - $authkey_lifetime;
356 } else {
357 warn "Cluster not quorate - extending auth key lifetime!\n";
358 }
359 }
360
8304b226 361 $max = $key_age + $auth_graceperiod if $key_age < $ticket_lifetime;
21800a71 362 }
2c3a6c0a 363
21800a71
FG
364 return undef if $min > $ticket_lifetime;
365 return ($min, $max);
366};
2c3a6c0a 367
afb10353
WB
368sub assemble_ticket : prototype($;$) {
369 my ($data, $aad) = @_;
2c3a6c0a
DM
370
371 my $rsa_priv = get_privkey();
372
afb10353 373 return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $data, $aad);
2c3a6c0a
DM
374}
375
afb10353
WB
376# Returns the username, "age" and tfa info.
377#
378# Note that for the new-style outh, tfa info is never set, as it only uses the `/ticket` api call
379# via the new 'tfa-challenge' parameter, so this part can go with PVE-8.
380#
381# New-style auth still uses this function, but sets `$tfa_ticket` to true when validating the tfa
382# ticket.
383sub verify_ticket : prototype($;$$) {
384 my ($ticket, $noerr, $tfa_ticket_aad) = @_;
2c3a6c0a 385
21800a71
FG
386 my $now = time();
387
388 my $check = sub {
389 my ($old) = @_;
390
391 my ($rsa_pub, $rsa_mtime) = get_pubkey($old);
392 return undef if !$rsa_pub;
393
394 my ($min, $max) = $get_ticket_age_range->($now, $rsa_mtime, $old);
5bb966fe 395 return undef if !defined($min);
21800a71
FG
396
397 return PVE::Ticket::verify_rsa_ticket(
afb10353 398 $rsa_pub, 'PVE', $ticket, $tfa_ticket_aad, $min, $max, 1);
21800a71 399 };
a1f8aaae 400
18f8ba18 401 my ($data, $age) = $check->();
a1f8aaae 402
21800a71 403 # check with old, rotated key if current key failed
18f8ba18 404 ($data, $age) = $check->(1) if !defined($data);
21800a71 405
18f8ba18 406 my $auth_failure = sub {
21800a71
FG
407 if ($noerr) {
408 return undef;
409 } else {
410 # raise error via undef ticket
411 PVE::Ticket::verify_rsa_ticket(undef, 'PVE');
412 }
18f8ba18
WB
413 };
414
415 if (!defined($data)) {
416 return $auth_failure->();
417 }
418
afb10353
WB
419 if ($tfa_ticket_aad) {
420 # We're validating a ticket-call's 'tfa-challenge' parameter, so just return its data.
421 if ($data =~ /^!tfa!(.*)$/) {
422 return $1;
423 }
424 die "bad ticket\n";
425 }
426
f25628d3 427 my ($username, $tfa_info);
afb10353
WB
428 if ($data =~ /^!tfa!(.*)$/) {
429 # PBS style half-authenticated ticket, contains a json string form of a `TfaChallenge`
430 # object.
431 # This type of ticket does not contain the user name.
432 return { type => 'new', data => $1 };
433 }
18f8ba18
WB
434 if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
435 # Ticket for u2f-users:
f25628d3 436 ($username, my $challenge) = ($1, $2);
18f8ba18
WB
437 if ($challenge eq 'verified') {
438 # u2f challenge was completed
439 $challenge = undef;
440 } elsif (!wantarray) {
441 # The caller is not aware there could be an ongoing challenge,
442 # so we treat this ticket as invalid:
443 return $auth_failure->();
444 }
f25628d3
WB
445 $tfa_info = {
446 type => 'u2f',
447 challenge => $challenge,
448 };
449 } elsif ($data =~ /^tfa!(.*)$/) {
450 # TOTP and Yubico don't require a challenge so this is the generic
451 # 'missing 2nd factor ticket'
452 $username = $1;
453 $tfa_info = { type => 'tfa' };
18f8ba18
WB
454 } else {
455 # Regular ticket (full access)
456 $username = $data;
21800a71 457 }
2c3a6c0a 458
a1f8aaae 459 return undef if !PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 460
f25628d3 461 return wantarray ? ($username, $age, $tfa_info) : $username;
2c3a6c0a
DM
462}
463
35c3ca0f
FG
464sub verify_token {
465 my ($api_token) = @_;
466
467 die "no API token specified\n" if !$api_token;
468
469 my ($tokenid, $value);
470 if ($api_token =~ /^(.*)=(.*)$/) {
471 $tokenid = $1;
472 $value = $2;
473 } else {
474 die "no tokenid specified\n";
475 }
476
477 my ($username, $token) = split_tokenid($tokenid);
478
479 my $usercfg = cfs_read_file('user.cfg');
480 check_user_enabled($usercfg, $username);
481 check_token_exist($usercfg, $username, $token);
482
35c3ca0f 483 my $user = $usercfg->{users}->{$username};
35c3ca0f 484 my $token_info = $user->{tokens}->{$token};
8a724f7b
DM
485
486 my $ctime = time();
35c3ca0f
FG
487 die "token expired\n" if $token_info->{expire} && ($token_info->{expire} < $ctime);
488
489 die "invalid token value!\n" if !PVE::Cluster::verify_token($tokenid, $value);
490
491 return wantarray ? ($tokenid) : $tokenid;
492}
493
494
adf8d771
DM
495# VNC tickets
496# - they do not contain the username in plain text
497# - they are restricted to a specific resource path (example: '/vms/100')
498sub assemble_vnc_ticket {
499 my ($username, $path) = @_;
500
501 my $rsa_priv = get_privkey();
502
adf8d771
DM
503 $path = normalize_path($path);
504
a1f8aaae 505 my $secret_data = "$username:$path";
adf8d771 506
a1f8aaae
DM
507 return PVE::Ticket::assemble_rsa_ticket(
508 $rsa_priv, 'PVEVNC', undef, $secret_data);
adf8d771
DM
509}
510
511sub verify_vnc_ticket {
512 my ($ticket, $username, $path, $noerr) = @_;
513
a1f8aaae 514 my $secret_data = "$username:$path";
adf8d771 515
21800a71 516 my ($rsa_pub, $rsa_mtime) = get_pubkey();
5efff6c1 517 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime && $authkey_lifetime > 0)) {
21800a71
FG
518 if ($noerr) {
519 return undef;
520 } else {
521 # raise error via undef ticket
522 PVE::Ticket::verify_rsa_ticket($rsa_pub, 'PVEVNC');
523 }
524 }
525
a1f8aaae
DM
526 return PVE::Ticket::verify_rsa_ticket(
527 $rsa_pub, 'PVEVNC', $ticket, $secret_data, -20, 40, $noerr);
adf8d771
DM
528}
529
23b35225 530sub assemble_spice_ticket {
bf3e6d31 531 my ($username, $vmid, $node) = @_;
23b35225 532
3f62bdbe 533 my $secret = &$get_csrfr_secret();
23b35225 534
a1f8aaae
DM
535 return PVE::Ticket::assemble_spice_ticket(
536 $secret, $username, $vmid, $node);
bf3e6d31
DM
537}
538
539sub verify_spice_connect_url {
540 my ($connect_str) = @_;
541
a1f8aaae 542 my $secret = &$get_csrfr_secret();
bf3e6d31 543
a1f8aaae 544 return PVE::Ticket::verify_spice_connect_url($secret, $connect_str);
23b35225
AD
545}
546
cee5583b
DM
547sub read_x509_subject_spice {
548 my ($filename) = @_;
549
550 # read x509 subject
551 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
44903703
FG
552 die "Could not open $filename using OpenSSL\n"
553 if !$bio;
554
cee5583b
DM
555 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
556 Net::SSLeay::BIO_free($bio);
44903703
FG
557
558 die "Could not parse X509 certificate in $filename\n"
559 if !$x509;
560
cee5583b
DM
561 my $nameobj = Net::SSLeay::X509_get_subject_name($x509);
562 my $subject = Net::SSLeay::X509_NAME_oneline($nameobj);
563 Net::SSLeay::X509_free($x509);
66931b11 564
cee5583b
DM
565 # remote-viewer wants comma as seperator (not '/')
566 $subject =~ s!^/!!;
567 $subject =~ s!/(\w+=)!,$1!g;
568
569 return $subject;
570}
571
572# helper to generate SPICE remote-viewer configuration
573sub remote_viewer_config {
574 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
575
576 if (!$proxy) {
577 my $host = `hostname -f` || PVE::INotify::nodename();
578 chomp $host;
579 $proxy = $host;
580 }
581
582 my ($ticket, $proxyticket) = assemble_spice_ticket($authuser, $vmid, $node);
583
584 my $filename = "/etc/pve/local/pve-ssl.pem";
585 my $subject = read_x509_subject_spice($filename);
586
587 my $cacert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192);
588 $cacert =~ s/\n/\\n/g;
63691fc6 589
25167526 590 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
cee5583b 591 my $config = {
63691fc6
DM
592 'secure-attention' => "Ctrl+Alt+Ins",
593 'toggle-fullscreen' => "Shift+F11",
594 'release-cursor' => "Ctrl+Alt+R",
cee5583b
DM
595 type => 'spice',
596 title => $title,
1075c589 597 host => $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
cee5583b
DM
598 proxy => "http://$proxy:3128",
599 'tls-port' => $port,
600 'host-subject' => $subject,
601 ca => $cacert,
602 password => $ticket,
603 'delete-this-file' => 1,
604 };
605
606 return ($ticket, $proxyticket, $config);
607}
608
37d45deb 609sub check_user_exist {
7070c1ae 610 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 611
5bb4e06a 612 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 613 return undef if !$username;
66931b11 614
37d45deb
DM
615 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
616
617 die "no such user ('$username')\n" if !$noerr;
66931b11 618
37d45deb
DM
619 return undef;
620}
621
622sub check_user_enabled {
623 my ($usercfg, $username, $noerr) = @_;
624
625 my $data = check_user_exist($usercfg, $username, $noerr);
626 return undef if !$data;
627
628 return 1 if $data->{enable};
2c3a6c0a 629
37d45deb 630 die "user '$username' is disabled\n" if !$noerr;
66931b11 631
8a724f7b
DM
632 my $ctime = time();
633 my $expire = $usercfg->{users}->{$username}->{expire};
634
635 die "account expired\n" if $expire && ($expire < $ctime);
636
7070c1ae 637 return undef;
2c3a6c0a
DM
638}
639
571e9d06
FG
640sub check_token_exist {
641 my ($usercfg, $username, $tokenid, $noerr) = @_;
642
643 my $user = check_user_exist($usercfg, $username, $noerr);
644 return undef if !$user;
645
646 return $user->{tokens}->{$tokenid}
647 if defined($user->{tokens}) && $user->{tokens}->{$tokenid};
648
649 die "no such token '$tokenid' for user '$username'\n" if !$noerr;
650
651 return undef;
652}
653
6adcb18c 654# deprecated
96f8ebd6 655sub verify_one_time_pw {
fda8ca85 656 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
96f8ebd6 657
1075c589 658 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
96f8ebd6
DM
659
660 # fixme: proxy support?
661 my $proxy;
662
663 if ($type eq 'yubico') {
972859d1
DM
664 PVE::OTP::yubico_verify_otp($otp, $keys, $tfa_cfg->{url},
665 $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
1abc2c0a 666 } elsif ($type eq 'oath') {
972859d1 667 PVE::OTP::oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
96f8ebd6
DM
668 } else {
669 die "unknown tfa type '$type'\n";
670 }
96f8ebd6
DM
671}
672
2c3a6c0a 673# password should be utf8 encoded
1075c589 674# Note: some plugins delay/sleep if auth fails
afb10353
WB
675sub authenticate_user : prototype($$$$;$) {
676 my ($username, $password, $otp, $new_format, $tfa_challenge) = @_;
2c3a6c0a
DM
677
678 die "no username specified\n" if !$username;
66931b11 679
5bb4e06a 680 my ($ruid, $realm);
2c3a6c0a 681
5bb4e06a 682 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
2c3a6c0a
DM
683
684 my $usercfg = cfs_read_file('user.cfg');
685
6126ab75 686 check_user_enabled($usercfg, $username);
2c3a6c0a 687
5bb4e06a 688 my $domain_cfg = cfs_read_file('domains.cfg');
2c3a6c0a 689
6126ab75 690 my $cfg = $domain_cfg->{ids}->{$realm};
3443faca 691 die "auth domain '$realm' does not exist\n" if !$cfg;
6126ab75 692 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
afb10353
WB
693
694 if ($tfa_challenge) {
695 # This is the 2nd factor, use the password for the OTP response.
696 my $tfa_challenge = authenticate_2nd_new($username, $realm, $password, $tfa_challenge);
697 return wantarray ? ($username, $tfa_challenge) : $username;
698 }
699
6126ab75 700 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
2c3a6c0a 701
afb10353
WB
702 if ($new_format) {
703 # This is the first factor with an optional immediate 2nd factor for TOTP:
704 my $tfa_challenge = authenticate_2nd_new($username, $realm, $otp, $tfa_challenge);
705 return wantarray ? ($username, $tfa_challenge) : $username;
706 } else {
707 return authenticate_2nd_old($username, $realm, $otp);
708 }
709}
710
711sub authenticate_2nd_old : prototype($$$) {
712 my ($username, $realm, $otp) = @_;
713
714 my ($type, $tfa_data) = user_get_tfa($username, $realm, 0);
fda8ca85
WB
715 if ($type) {
716 if ($type eq 'u2f') {
717 # Note that if the user did not manage to complete the initial u2f registration
718 # challenge we have a hash containing a 'challenge' entry in the user's tfa.cfg entry:
f25628d3
WB
719 $tfa_data = undef if exists $tfa_data->{challenge};
720 } elsif (!defined($otp)) {
721 # The user requires a 2nd factor but has not provided one. Return success but
722 # don't clear $tfa_data.
fda8ca85
WB
723 } else {
724 my $keys = $tfa_data->{keys};
725 my $tfa_cfg = $tfa_data->{config};
726 verify_one_time_pw($type, $username, $keys, $tfa_cfg, $otp);
f25628d3
WB
727 $tfa_data = undef;
728 }
729
730 # Return the type along with the rest:
731 if ($tfa_data) {
732 $tfa_data = {
733 type => $type,
734 data => $tfa_data,
735 };
fda8ca85 736 }
96f8ebd6
DM
737 }
738
f25628d3 739 return wantarray ? ($username, $tfa_data) : $username;
2c3a6c0a
DM
740}
741
afb10353
WB
742# Returns a tfa challenge or undef.
743sub authenticate_2nd_new : prototype($$$$) {
744 my ($username, $realm, $otp, $tfa_challenge) = @_;
745
6adcb18c 746 my $result = lock_tfa_config(sub {
afb10353
WB
747 my ($tfa_cfg, $realm_tfa) = user_get_tfa($username, $realm, 1);
748
749 if (!defined($tfa_cfg)) {
750 return undef;
751 }
752
753 my $realm_type = $realm_tfa && $realm_tfa->{type};
a0374ad0
WB
754 $realm_type = 'totp' if $realm_type eq 'oath'; # we used to call it that
755 # verify realm type unless using recovery keys:
756 if (defined($realm_type)) {
757 if ($realm_type eq 'yubico') {
758 # Yubico auth will not be supported in rust for now...
759 if (!defined($tfa_challenge)) {
760 my $challenge = { yubico => JSON::true };
761 # Even with yubico auth we do allow recovery keys to be used:
762 if (my $recovery = $tfa_cfg->recovery_state($username)) {
763 $challenge->{recovery} = $recovery;
764 }
765 return to_json($challenge);
6adcb18c 766 }
6adcb18c 767
a0374ad0
WB
768 if ($otp =~ /^yubico:(.*)$/) {
769 $otp = $1;
770 # Defer to after unlocking the TFA config:
771 return sub {
772 authenticate_yubico_new(
773 $tfa_cfg, $username, $realm_tfa, $tfa_challenge, $otp,
774 );
775 };
776 }
6adcb18c
WB
777 }
778
a0374ad0
WB
779 my $response_type;
780 if (defined($otp)) {
781 if ($otp !~ /^([^:]+):/) {
782 die "bad otp response\n";
783 }
784 $response_type = $1;
6adcb18c 785 }
a0374ad0
WB
786
787 die "realm requires $realm_type authentication\n"
788 if $response_type && $response_type ne 'recovery' && $response_type ne $realm_type;
afb10353
WB
789 }
790
791 configure_u2f_and_wa($tfa_cfg);
792
793 my $must_save = 0;
794 if (defined($tfa_challenge)) {
795 $tfa_challenge = verify_ticket($tfa_challenge, 0, $username);
796 $must_save = $tfa_cfg->authentication_verify($username, $tfa_challenge, $otp);
797 $tfa_challenge = undef;
798 } else {
799 $tfa_challenge = $tfa_cfg->authentication_challenge($username);
800 if (defined($otp)) {
801 if (defined($tfa_challenge)) {
802 $must_save = $tfa_cfg->authentication_verify($username, $tfa_challenge, $otp);
803 } else {
804 die "no such challenge\n";
805 }
806 }
807 }
808
809 if ($must_save) {
810 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
811 }
812
813 return $tfa_challenge;
814 });
6adcb18c
WB
815
816 # Yubico auth returns the authentication sub:
817 if (ref($result) eq 'CODE') {
818 $result = $result->();
819 }
820
821 return $result;
822}
823
824sub authenticate_yubico_new : prototype($$$) {
825 my ($tfa_cfg, $username, $realm, $tfa_challenge, $otp) = @_;
826
827 $tfa_challenge = verify_ticket($tfa_challenge, 0, $username);
828 $tfa_challenge = from_json($tfa_challenge);
829
830 if (!$tfa_challenge->{yubico}) {
831 die "no such challenge\n";
832 }
833
834 my $keys = $tfa_cfg->get_yubico_keys($username);
835 die "no keys configured\n" if !defined($keys) || !length($keys);
836
8c1e3ab3 837 authenticate_yubico_do($otp, $keys, $realm);
6adcb18c
WB
838
839 # return `undef` to clear the tfa challenge.
840 return undef;
afb10353
WB
841}
842
8c1e3ab3
WB
843sub authenticate_yubico_do : prototype($$$) {
844 my ($value, $keys, $realm) = @_;
845
846 # fixme: proxy support?
847 my $proxy = undef;
848
849 PVE::OTP::yubico_verify_otp($value, $keys, $realm->{url}, $realm->{id}, $realm->{key}, $proxy);
850}
851
afb10353
WB
852sub configure_u2f_and_wa : prototype($) {
853 my ($tfa_cfg) = @_;
854
855 my $dc = cfs_read_file('datacenter.cfg');
856 if (my $u2f = $dc->{u2f}) {
857 my $origin = $u2f->{origin};
858 if (!defined($origin)) {
859 my $rpcenv = PVE::RPCEnvironment::get();
860 $origin = $rpcenv->get_request_host(1);
861 if ($origin) {
862 $origin = "https://$origin";
863 } else {
864 die "failed to figure out u2f origin\n";
865 }
866 }
867 $tfa_cfg->set_u2f_config({
868 origin => $origin,
869 appid => $u2f->{appid},
870 });
871 }
872 if (my $wa = $dc->{webauthn}) {
873 $tfa_cfg->set_webauthn_config($wa);
874 }
875}
876
2c3a6c0a 877sub domain_set_password {
5bb4e06a 878 my ($realm, $username, $password) = @_;
2c3a6c0a
DM
879
880 die "no auth domain specified" if !$realm;
881
5bb4e06a
DM
882 my $domain_cfg = cfs_read_file('domains.cfg');
883
884 my $cfg = $domain_cfg->{ids}->{$realm};
1075c589 885 die "auth domain '$realm' does not exist\n" if !$cfg;
5bb4e06a
DM
886 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
887 $plugin->store_password($cfg, $realm, $username, $password);
2c3a6c0a
DM
888}
889
890sub add_user_group {
2c3a6c0a 891 my ($username, $usercfg, $group) = @_;
66931b11 892
2c3a6c0a
DM
893 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
894 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
895}
896
897sub delete_user_group {
2c3a6c0a 898 my ($username, $usercfg) = @_;
66931b11 899
2c3a6c0a
DM
900 foreach my $group (keys %{$usercfg->{groups}}) {
901
66931b11 902 delete ($usercfg->{groups}->{$group}->{users}->{$username})
2c3a6c0a
DM
903 if $usercfg->{groups}->{$group}->{users}->{$username};
904 }
905}
906
907sub delete_user_acl {
2c3a6c0a
DM
908 my ($username, $usercfg) = @_;
909
910 foreach my $acl (keys %{$usercfg->{acl}}) {
911
66931b11 912 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
2c3a6c0a
DM
913 if $usercfg->{acl}->{$acl}->{users}->{$username};
914 }
2c3a6c0a 915}
39c85db8 916
2c3a6c0a 917sub delete_group_acl {
2c3a6c0a
DM
918 my ($group, $usercfg) = @_;
919
920 foreach my $acl (keys %{$usercfg->{acl}}) {
921
66931b11 922 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
2c3a6c0a
DM
923 if $usercfg->{acl}->{$acl}->{groups}->{$group};
924 }
39c85db8
DM
925}
926
927sub delete_pool_acl {
39c85db8 928 my ($pool, $usercfg) = @_;
2c3a6c0a 929
39c85db8
DM
930 my $path = "/pool/$pool";
931
3b4a3f94 932 delete ($usercfg->{acl}->{$path})
2c3a6c0a
DM
933}
934
935# we automatically create some predefined roles by splitting privs
936# into 3 groups (per category)
937# root: only root is allowed to do that
938# admin: an administrator can to that
1075c589 939# user: a normal user/customer can to that
2c3a6c0a
DM
940my $privgroups = {
941 VM => {
942 root => [],
66931b11
DM
943 admin => [
944 'VM.Config.Disk',
945 'VM.Config.CPU',
946 'VM.Config.Memory',
947 'VM.Config.Network',
c0fead8c 948 'VM.Config.HWType',
66931b11
DM
949 'VM.Config.Options', # covers all other things
950 'VM.Allocate',
951 'VM.Clone',
2c3a6c0a 952 'VM.Migrate',
66931b11
DM
953 'VM.Monitor',
954 'VM.Snapshot',
aad513f6 955 'VM.Snapshot.Rollback',
2c3a6c0a
DM
956 ],
957 user => [
cc7bdf33 958 'VM.Config.CDROM', # change CDROM media
cb381abc 959 'VM.Config.Cloudinit',
66931b11 960 'VM.Console',
68d5a86d 961 'VM.Backup',
2c3a6c0a
DM
962 'VM.PowerMgmt',
963 ],
66931b11 964 audit => [
82b63965 965 'VM.Audit',
2c3a6c0a
DM
966 ],
967 },
968 Sys => {
969 root => [
66931b11 970 'Sys.PowerMgmt',
37d45deb 971 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
972 ],
973 admin => [
2e376c58 974 'Permissions.Modify',
66931b11 975 'Sys.Console',
2c3a6c0a
DM
976 'Sys.Syslog',
977 ],
978 user => [],
979 audit => [
980 'Sys.Audit',
981 ],
982 },
983 Datastore => {
2e376c58 984 root => [],
19f60b5e
DM
985 admin => [
986 'Datastore.Allocate',
373cb383 987 'Datastore.AllocateTemplate',
19f60b5e 988 ],
2c3a6c0a
DM
989 user => [
990 'Datastore.AllocateSpace',
991 ],
992 audit => [
993 'Datastore.Audit',
994 ],
995 },
40672671
AD
996 SDN => {
997 root => [],
998 admin => [
999 'SDN.Allocate',
1000 'SDN.Audit',
1001 ],
1002 audit => [
1003 'SDN.Audit',
1004 ],
1005 },
12683df7 1006 User => {
82b63965
DM
1007 root => [
1008 'Realm.Allocate',
1009 ],
12683df7
DM
1010 admin => [
1011 'User.Modify',
82b63965 1012 'Group.Allocate', # edit/change group settings
66931b11 1013 'Realm.AllocateUser',
19f60b5e 1014 ],
12683df7
DM
1015 user => [],
1016 audit => [],
1017 },
dee1c882
DM
1018 Pool => {
1019 root => [],
1020 admin => [
1021 'Pool.Allocate', # create/delete pools
1022 ],
6d048ad6
LS
1023 user => [
1024 'Pool.Audit',
1025 ],
1026 audit => [
1027 'Pool.Audit',
1028 ],
dee1c882 1029 },
2c3a6c0a
DM
1030};
1031
1032my $valid_privs = {};
1033
1034my $special_roles = {
1075c589
FG
1035 'NoAccess' => {}, # no privileges
1036 'Administrator' => $valid_privs, # all privileges
2c3a6c0a
DM
1037};
1038
1039sub create_roles {
1040
1041 foreach my $cat (keys %$privgroups) {
1042 my $cd = $privgroups->{$cat};
66931b11 1043 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
2c3a6c0a
DM
1044 @{$cd->{user}}, @{$cd->{audit}}) {
1045 $valid_privs->{$p} = 1;
1046 }
1047 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
1048
1049 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
1050 $special_roles->{"PVEAdmin"}->{$p} = 1;
1051 }
1052 if (scalar(@{$cd->{user}})) {
1053 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
1054 $special_roles->{"PVE${cat}User"}->{$p} = 1;
1055 }
1056 }
1057 foreach my $p (@{$cd->{audit}}) {
1058 $special_roles->{"PVEAuditor"}->{$p} = 1;
1059 }
1060 }
ff4b2235 1061
7b395f99 1062 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
1063};
1064
1065create_roles();
1066
0fea3f16
DC
1067sub create_priv_properties {
1068 my $properties = {};
1069 foreach my $priv (keys %$valid_privs) {
1070 $properties->{$priv} = {
1071 type => 'boolean',
1072 optional => 1,
1073 };
1074 }
1075 return $properties;
1076}
1077
894e6f0c
PA
1078sub role_is_special {
1079 my ($role) = @_;
b7ba86d4 1080 return (exists $special_roles->{$role}) ? 1 : 0;
894e6f0c
PA
1081}
1082
2c3a6c0a
DM
1083sub add_role_privs {
1084 my ($role, $usercfg, $privs) = @_;
1085
1086 return if !$privs;
1087
1088 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
1089
1090 foreach my $priv (split_list($privs)) {
1091 if (defined ($valid_privs->{$priv})) {
1092 $usercfg->{roles}->{$role}->{$priv} = 1;
1093 } else {
1075c589 1094 die "invalid privilege '$priv'\n";
66931b11
DM
1095 }
1096 }
2c3a6c0a
DM
1097}
1098
eb41d200 1099sub lookup_username {
f335d265 1100 my ($username, $noerr) = @_;
eb41d200
WL
1101
1102 $username =~ m!^(${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex})$!;
1103
1104 my $realm = $2;
1105 my $domain_cfg = cfs_read_file("domains.cfg");
1106 my $casesensitive = $domain_cfg->{ids}->{$realm}->{'case-sensitive'} // 1;
1107 my $usercfg = cfs_read_file('user.cfg');
1108
1109 if (!$casesensitive) {
1110 my @matches = grep { lc $username eq lc $_ } (keys %{$usercfg->{users}});
1111
1112 die "ambiguous case insensitive match of username '$username', cannot safely grant access!\n"
f335d265 1113 if scalar @matches > 1 && !$noerr;
eb41d200
WL
1114
1115 return $matches[0]
1116 }
1117
1118 return $username;
1119}
1120
2c3a6c0a
DM
1121sub normalize_path {
1122 my $path = shift;
1123
4bc17477 1124 $path =~ s|/+|/|g;
2c3a6c0a
DM
1125
1126 $path =~ s|/$||;
1127
1128 $path = '/' if !$path;
1129
4bc17477
DM
1130 $path = "/$path" if $path !~ m|^/|;
1131
e4f8fc2e 1132 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
2c3a6c0a
DM
1133
1134 return $path;
66931b11 1135}
2c3a6c0a 1136
20c60513 1137sub check_path {
91c30089
TL
1138 my ($path) = @_;
1139 return $path =~ m!^(
20c60513
LS
1140 /
1141 |/access
1142 |/access/groups
8737ff37 1143 |/access/groups/[[:alnum:]\.\-\_]+
20c60513 1144 |/access/realm
8737ff37 1145 |/access/realm/[[:alnum:]\.\-\_]+
20c60513
LS
1146 |/nodes
1147 |/nodes/[[:alnum:]\.\-\_]+
1148 |/pool
1149 |/pool/[[:alnum:]\.\-\_]+
1150 |/sdn
0a06acb1 1151 |/sdn/zones/[[:alnum:]\.\-\_]+
4100ba8d 1152 |/sdn/vnets/[[:alnum:]\.\-\_]+
20c60513
LS
1153 |/storage
1154 |/storage/[[:alnum:]\.\-\_]+
1155 |/vms
ad1ef9fc 1156 |/vms/[1-9][0-9]{2,}
20c60513
LS
1157 )$!xs;
1158}
1159
2c3a6c0a
DM
1160PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
1161sub verify_groupname {
1162 my ($groupname, $noerr) = @_;
1163
1164 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1165
1166 die "group name '$groupname' contains invalid characters\n" if !$noerr;
1167
1168 return undef;
1169 }
66931b11 1170
2c3a6c0a
DM
1171 return $groupname;
1172}
1173
1174PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
1175sub verify_rolename {
1176 my ($rolename, $noerr) = @_;
1177
1178 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
1179
1180 die "role name '$rolename' contains invalid characters\n" if !$noerr;
1181
1182 return undef;
1183 }
66931b11 1184
2c3a6c0a
DM
1185 return $rolename;
1186}
1187
16e50b59 1188PVE::JSONSchema::register_format('pve-poolid', \&verify_poolname);
39c85db8
DM
1189sub verify_poolname {
1190 my ($poolname, $noerr) = @_;
1191
1192 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1193
1194 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
1195
1196 return undef;
1197 }
66931b11 1198
39c85db8
DM
1199 return $poolname;
1200}
1201
2c3a6c0a
DM
1202PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
1203sub verify_privname {
1204 my ($priv, $noerr) = @_;
1205
1206 if (!$valid_privs->{$priv}) {
1075c589 1207 die "invalid privilege '$priv'\n" if !$noerr;
2c3a6c0a
DM
1208
1209 return undef;
1210 }
66931b11 1211
2c3a6c0a
DM
1212 return $priv;
1213}
1214
1215sub userconfig_force_defaults {
1216 my ($cfg) = @_;
1217
1218 foreach my $r (keys %$special_roles) {
1219 $cfg->{roles}->{$r} = $special_roles->{$r};
1220 }
1221
7279f31c
WL
1222 # add root user if not exists
1223 if (!$cfg->{users}->{'root@pam'}) {
66931b11 1224 $cfg->{users}->{'root@pam'}->{enable} = 1;
7279f31c 1225 }
2c3a6c0a
DM
1226}
1227
1228sub parse_user_config {
1229 my ($filename, $raw) = @_;
1230
1231 my $cfg = {};
1232
1233 userconfig_force_defaults($cfg);
1234
d6eb6621 1235 $raw = '' if !defined($raw);
62af314a 1236 while ($raw =~ /^\s*(.+?)\s*$/gm) {
2c3a6c0a 1237 my $line = $1;
2c3a6c0a
DM
1238 my @data;
1239
1240 foreach my $d (split (/:/, $line)) {
66931b11 1241 $d =~ s/^\s+//;
2c3a6c0a
DM
1242 $d =~ s/\s+$//;
1243 push @data, $d
1244 }
1245
1246 my $et = shift @data;
1247
1248 if ($et eq 'user') {
96f8ebd6 1249 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
2c3a6c0a 1250
5bb4e06a 1251 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
1252 if (!$realm) {
1253 warn "user config - ignore user '$user' - invalid user name\n";
1254 next;
1255 }
1256
1257 $enable = $enable ? 1 : 0;
1258
1259 $expire = 0 if !$expire;
1260
1261 if ($expire !~ m/^\d+$/) {
1262 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
1263 next;
1264 }
1265 $expire = int($expire);
1266
1267 #if (!verify_groupname ($group, 1)) {
1268 # warn "user config - ignore user '$user' - invalid characters in group name\n";
1269 # next;
1270 #}
1271
1272 $cfg->{users}->{$user} = {
1273 enable => $enable,
1274 # group => $group,
1275 };
1276 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
1277 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
1278 $cfg->{users}->{$user}->{email} = $email;
1279 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1280 $cfg->{users}->{$user}->{expire} = $expire;
1abc2c0a 1281 # keys: allowed yubico key ids or oath secrets (base32 encoded)
66931b11 1282 $cfg->{users}->{$user}->{keys} = $keys if $keys;
2c3a6c0a
DM
1283
1284 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
1285 #$cfg->{groups}->{$group}->{$user} = 1;
1286
1287 } elsif ($et eq 'group') {
1288 my ($group, $userlist, $comment) = @data;
1289
1290 if (!verify_groupname($group, 1)) {
1291 warn "user config - ignore group '$group' - invalid characters in group name\n";
1292 next;
1293 }
1294
1295 # make sure to add the group (even if there are no members)
1296 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
1297
1298 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1299
1300 foreach my $user (split_list($userlist)) {
1301
5bb4e06a 1302 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
2c3a6c0a
DM
1303 warn "user config - ignore invalid group member '$user'\n";
1304 next;
1305 }
1306
66931b11 1307 if ($cfg->{users}->{$user}) { # user exists
2c3a6c0a 1308 $cfg->{users}->{$user}->{groups}->{$group} = 1;
2c3a6c0a
DM
1309 } else {
1310 warn "user config - ignore invalid group member '$user'\n";
1311 }
5654260e 1312 $cfg->{groups}->{$group}->{users}->{$user} = 1;
2c3a6c0a
DM
1313 }
1314
1315 } elsif ($et eq 'role') {
1316 my ($role, $privlist) = @data;
66931b11 1317
2c3a6c0a
DM
1318 if (!verify_rolename($role, 1)) {
1319 warn "user config - ignore role '$role' - invalid characters in role name\n";
1320 next;
1321 }
1322
1323 # make sure to add the role (even if there are no privileges)
1324 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
1325
1326 foreach my $priv (split_list($privlist)) {
1327 if (defined ($valid_privs->{$priv})) {
1328 $cfg->{roles}->{$role}->{$priv} = 1;
1329 } else {
1516bfa0 1330 warn "user config - ignore invalid privilege '$priv'\n";
66931b11 1331 }
2c3a6c0a 1332 }
66931b11 1333
2c3a6c0a
DM
1334 } elsif ($et eq 'acl') {
1335 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
1336
733371da
FG
1337 $propagate = $propagate ? 1 : 0;
1338
2c3a6c0a
DM
1339 if (my $path = normalize_path($pathtxt)) {
1340 foreach my $role (split_list($rolelist)) {
66931b11 1341
2c3a6c0a
DM
1342 if (!verify_rolename($role, 1)) {
1343 warn "user config - ignore invalid role name '$role' in acl\n";
1344 next;
1345 }
1346
21f523a5
FG
1347 if (!$cfg->{roles}->{$role}) {
1348 warn "user config - ignore invalid acl role '$role'\n";
1349 next;
1350 }
1351
2c3a6c0a 1352 foreach my $ug (split_list($uglist)) {
508e11f1
FG
1353 my ($group) = $ug =~ m/^@(\S+)$/;
1354
1355 if ($group && verify_groupname($group, 1)) {
5654260e 1356 if (!$cfg->{groups}->{$group}) { # group does not exist
2c3a6c0a
DM
1357 warn "user config - ignore invalid acl group '$group'\n";
1358 }
5654260e 1359 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
5bb4e06a 1360 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
5654260e 1361 if (!$cfg->{users}->{$ug}) { # user does not exist
2c3a6c0a
DM
1362 warn "user config - ignore invalid acl member '$ug'\n";
1363 }
5654260e 1364 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
28e3dc05 1365 } elsif (my ($user, $token) = split_tokenid($ug, 1)) {
571e9d06 1366 if (check_token_exist($cfg, $user, $token, 1)) {
28e3dc05
FG
1367 $cfg->{acl}->{$path}->{tokens}->{$ug}->{$role} = $propagate;
1368 } else {
1369 warn "user config - ignore invalid acl token '$ug'\n";
1370 }
2c3a6c0a
DM
1371 } else {
1372 warn "user config - invalid user/group '$ug' in acl\n";
1373 }
1374 }
1375 }
1376 } else {
1377 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1378 }
4bc17477 1379 } elsif ($et eq 'pool') {
39c85db8 1380 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 1381
39c85db8
DM
1382 if (!verify_poolname($pool, 1)) {
1383 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1384 next;
1385 }
4bc17477 1386
39c85db8
DM
1387 # make sure to add the pool (even if there are no members)
1388 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 1389
39c85db8 1390 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 1391
39c85db8
DM
1392 foreach my $vmid (split_list($vmlist)) {
1393 if ($vmid !~ m/^\d+$/) {
1394 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1395 next;
4bc17477 1396 }
39c85db8 1397 $vmid = int($vmid);
4bc17477 1398
39c85db8
DM
1399 if ($cfg->{vms}->{$vmid}) {
1400 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1401 next;
4bc17477
DM
1402 }
1403
39c85db8 1404 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
66931b11 1405
39c85db8
DM
1406 # record vmid ==> pool relation
1407 $cfg->{vms}->{$vmid} = $pool;
1408 }
1409
1410 foreach my $storeid (split_list($storelist)) {
1411 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1412 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1413 next;
1414 }
1415 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
4bc17477 1416 }
28e3dc05
FG
1417 } elsif ($et eq 'token') {
1418 my ($tokenid, $expire, $privsep, $comment) = @data;
1419
1420 my ($user, $token) = split_tokenid($tokenid, 1);
1421 if (!($user && $token)) {
1422 warn "user config - ignore invalid tokenid '$tokenid'\n";
1423 next;
1424 }
1425
1426 $privsep = $privsep ? 1 : 0;
1427
1428 $expire = 0 if !$expire;
1429
1430 if ($expire !~ m/^\d+$/) {
1431 warn "user config - ignore token '$tokenid' - (illegal characters in expire '$expire')\n";
1432 next;
1433 }
1434 $expire = int($expire);
1435
1436 if (my $user_cfg = $cfg->{users}->{$user}) { # user exists
1437 $user_cfg->{tokens}->{$token} = {} if !$user_cfg->{tokens}->{$token};
1438 my $token_cfg = $user_cfg->{tokens}->{$token};
1439 $token_cfg->{privsep} = $privsep;
1440 $token_cfg->{expire} = $expire;
1441 $token_cfg->{comment} = PVE::Tools::decode_text($comment) if $comment;
1442 } else {
1443 warn "user config - ignore token '$tokenid' - user does not exist\n";
1444 }
2c3a6c0a
DM
1445 } else {
1446 warn "user config - ignore config line: $line\n";
1447 }
1448 }
1449
1450 userconfig_force_defaults($cfg);
1451
1452 return $cfg;
1453}
1454
2c3a6c0a
DM
1455sub write_user_config {
1456 my ($filename, $cfg) = @_;
1457
1458 my $data = '';
1459
93c7e9c3 1460 foreach my $user (sort keys %{$cfg->{users}}) {
2c3a6c0a
DM
1461 my $d = $cfg->{users}->{$user};
1462 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1463 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1464 my $email = $d->{email} || '';
1465 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 1466 my $expire = int($d->{expire} || 0);
2c3a6c0a 1467 my $enable = $d->{enable} ? 1 : 0;
96f8ebd6
DM
1468 my $keys = $d->{keys} ? $d->{keys} : '';
1469 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
28e3dc05
FG
1470
1471 my $user_tokens = $d->{tokens};
1472 foreach my $token (sort keys %$user_tokens) {
1473 my $td = $user_tokens->{$token};
1474 my $full_tokenid = join_tokenid($user, $token);
1475 my $comment = $td->{comment} ? PVE::Tools::encode_text($td->{comment}) : '';
1476 my $expire = int($td->{expire} || 0);
1477 my $privsep = $td->{privsep} ? 1 : 0;
1478 $data .= "token:$full_tokenid:$expire:$privsep:$comment:\n";
1479 }
2c3a6c0a
DM
1480 }
1481
1482 $data .= "\n";
1483
93c7e9c3 1484 foreach my $group (sort keys %{$cfg->{groups}}) {
2c3a6c0a 1485 my $d = $cfg->{groups}->{$group};
a5ec58ea 1486 my $list = join (',', sort keys %{$d->{users}});
66931b11 1487 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
2c3a6c0a
DM
1488 $data .= "group:$group:$list:$comment:\n";
1489 }
1490
1491 $data .= "\n";
1492
93c7e9c3 1493 foreach my $pool (sort keys %{$cfg->{pools}}) {
39c85db8 1494 my $d = $cfg->{pools}->{$pool};
a5ec58ea
FG
1495 my $vmlist = join (',', sort keys %{$d->{vms}});
1496 my $storelist = join (',', sort keys %{$d->{storage}});
66931b11 1497 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 1498 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
1499 }
1500
1501 $data .= "\n";
1502
93c7e9c3 1503 foreach my $role (sort keys %{$cfg->{roles}}) {
2c3a6c0a
DM
1504 next if $special_roles->{$role};
1505
1506 my $d = $cfg->{roles}->{$role};
a5ec58ea 1507 my $list = join (',', sort keys %$d);
2c3a6c0a
DM
1508 $data .= "role:$role:$list:\n";
1509 }
1510
1511 $data .= "\n";
1512
9a12a08c
FG
1513 my $collect_rolelist_members = sub {
1514 my ($acl_members, $result, $prefix, $exclude) = @_;
2c3a6c0a 1515
9a12a08c
FG
1516 foreach my $member (keys %$acl_members) {
1517 next if $exclude && $member eq $exclude;
2c3a6c0a 1518
2c3a6c0a
DM
1519 my $l0 = '';
1520 my $l1 = '';
9a12a08c
FG
1521 foreach my $role (sort keys %{$acl_members->{$member}}) {
1522 my $propagate = $acl_members->{$member}->{$role};
2c3a6c0a
DM
1523 if ($propagate) {
1524 $l1 .= ',' if $l1;
1525 $l1 .= $role;
1526 } else {
1527 $l0 .= ',' if $l0;
1528 $l0 .= $role;
1529 }
1530 }
9a12a08c
FG
1531 $result->{0}->{$l0}->{"${prefix}${member}"} = 1 if $l0;
1532 $result->{1}->{$l1}->{"${prefix}${member}"} = 1 if $l1;
2c3a6c0a 1533 }
9a12a08c 1534 };
2c3a6c0a 1535
9a12a08c
FG
1536 foreach my $path (sort keys %{$cfg->{acl}}) {
1537 my $d = $cfg->{acl}->{$path};
2c3a6c0a 1538
9a12a08c 1539 my $rolelist_members = {};
2c3a6c0a 1540
9a12a08c
FG
1541 $collect_rolelist_members->($d->{'groups'}, $rolelist_members, '@');
1542
1543 # no need to save 'root@pam', it is always 'Administrator'
1544 $collect_rolelist_members->($d->{'users'}, $rolelist_members, '', 'root@pam');
1545
28e3dc05
FG
1546 $collect_rolelist_members->($d->{'tokens'}, $rolelist_members, '');
1547
9a12a08c
FG
1548 foreach my $propagate (0,1) {
1549 my $filtered = $rolelist_members->{$propagate};
1550 foreach my $rolelist (sort keys %$filtered) {
1551 my $uglist = join (',', sort keys %{$filtered->{$rolelist}});
1552 $data .= "acl:$propagate:$path:$uglist:$rolelist:\n";
1553 }
28e3dc05 1554
2c3a6c0a
DM
1555 }
1556 }
1557
1558 return $data;
1559}
1560
57098eb8
WB
1561# Creates a `PVE::RS::TFA` instance from the raw config data.
1562# Its contained hash will also support the legacy functionality.
fda8ca85
WB
1563sub parse_priv_tfa_config {
1564 my ($filename, $raw) = @_;
1565
fda8ca85 1566 $raw = '' if !defined($raw);
57098eb8 1567 my $cfg = PVE::RS::TFA->new($raw);
fda8ca85 1568
57098eb8
WB
1569 # Purge invalid users:
1570 foreach my $user ($cfg->users()->@*) {
fda8ca85
WB
1571 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1572 if (!$realm) {
1573 warn "user tfa config - ignore user '$user' - invalid user name\n";
57098eb8 1574 $cfg->remove_user($user);
fda8ca85 1575 }
fda8ca85
WB
1576 }
1577
1578 return $cfg;
1579}
1580
1581sub write_priv_tfa_config {
1582 my ($filename, $cfg) = @_;
1583
57098eb8
WB
1584 # FIXME: Only allow this if the complete cluster has been upgraded to understand the json
1585 # config format.
1586 return $cfg->write();
fda8ca85
WB
1587}
1588
2c3a6c0a
DM
1589sub roles {
1590 my ($cfg, $user, $path) = @_;
1591
66931b11 1592 # NOTE: we do not consider pools here.
e915e9e4
FG
1593 # NOTE: for privsep tokens, this does not filter roles by those that the
1594 # corresponding user has.
a31f1d85 1595 # Use $rpcenv->permission() for any actual permission checks!
4bc17477 1596
2c3a6c0a
DM
1597 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1598
e915e9e4
FG
1599 if (pve_verify_tokenid($user, 1)) {
1600 my $tokenid = $user;
1601 my ($username, $token) = split_tokenid($tokenid);
1602
1603 my $token_info = $cfg->{users}->{$username}->{tokens}->{$token};
1604 return () if !$token_info;
1605
7e8bcaa7 1606 my $user_roles = roles($cfg, $username, $path);
e915e9e4
FG
1607
1608 # return full user privileges
7e8bcaa7 1609 return $user_roles if !$token_info->{privsep};
e915e9e4
FG
1610 }
1611
7e8bcaa7 1612 my $roles = {};
2c3a6c0a
DM
1613
1614 foreach my $p (sort keys %{$cfg->{acl}}) {
1615 my $final = ($path eq $p);
1616
1617 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1618
1619 my $acl = $cfg->{acl}->{$p};
1620
1621 #print "CHECKACL $path $p\n";
1622 #print "ACL $path = " . Dumper ($acl);
e915e9e4
FG
1623 if (my $ri = $acl->{tokens}->{$user}) {
1624 my $new;
1625 foreach my $role (keys %$ri) {
1626 my $propagate = $ri->{$role};
1627 if ($final || $propagate) {
1628 #print "APPLY ROLE $p $user $role\n";
1629 $new = {} if !$new;
7e8bcaa7 1630 $new->{$role} = $propagate;
e915e9e4
FG
1631 }
1632 }
1633 if ($new) {
7e8bcaa7 1634 $roles = $new; # overwrite previous settings
e915e9e4
FG
1635 next;
1636 }
1637 }
2c3a6c0a
DM
1638
1639 if (my $ri = $acl->{users}->{$user}) {
1640 my $new;
1641 foreach my $role (keys %$ri) {
1642 my $propagate = $ri->{$role};
1643 if ($final || $propagate) {
1644 #print "APPLY ROLE $p $user $role\n";
1645 $new = {} if !$new;
7e8bcaa7 1646 $new->{$role} = $propagate;
2c3a6c0a
DM
1647 }
1648 }
1649 if ($new) {
7e8bcaa7 1650 $roles = $new; # overwrite previous settings
2c3a6c0a
DM
1651 next; # user privs always override group privs
1652 }
1653 }
1654
1655 my $new;
1656 foreach my $g (keys %{$acl->{groups}}) {
1657 next if !$cfg->{groups}->{$g}->{users}->{$user};
1658 if (my $ri = $acl->{groups}->{$g}) {
1659 foreach my $role (keys %$ri) {
1660 my $propagate = $ri->{$role};
1661 if ($final || $propagate) {
1662 #print "APPLY ROLE $p \@$g $role\n";
1663 $new = {} if !$new;
7e8bcaa7 1664 $new->{$role} = $propagate;
2c3a6c0a
DM
1665 }
1666 }
1667 }
1668 }
1669 if ($new) {
7e8bcaa7 1670 $roles = $new; # overwrite previous settings
2c3a6c0a
DM
1671 next;
1672 }
2c3a6c0a
DM
1673 }
1674
7e8bcaa7
FG
1675 return { 'NoAccess' => $roles->{NoAccess} } if defined ($roles->{NoAccess});
1676 #return () if defined ($roles->{NoAccess});
66931b11 1677
7e8bcaa7 1678 #print "permission $user $path = " . Dumper ($roles);
2c3a6c0a
DM
1679
1680 #print "roles $user $path = " . join (',', @ra) . "\n";
1681
7e8bcaa7 1682 return $roles;
2c3a6c0a 1683}
66931b11 1684
3b4a3f94
AG
1685sub remove_vm_access {
1686 my ($vmid) = @_;
1687 my $delVMaccessFn = sub {
1688 my $usercfg = cfs_read_file("user.cfg");
57a70473 1689 my $modified;
3b4a3f94 1690
57a70473
DM
1691 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1692 delete $usercfg->{acl}->{"/vms/$vmid"};
1693 $modified = 1;
3b4a3f94
AG
1694 }
1695 if (my $pool = $usercfg->{vms}->{$vmid}) {
1696 if (my $data = $usercfg->{pools}->{$pool}) {
1697 delete $data->{vms}->{$vmid};
1698 delete $usercfg->{vms}->{$vmid};
57a70473 1699 $modified = 1;
3b4a3f94
AG
1700 }
1701 }
57a70473 1702 cfs_write_file("user.cfg", $usercfg) if $modified;
3b4a3f94
AG
1703 };
1704
1705 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1706}
1707
60844761
AG
1708sub remove_storage_access {
1709 my ($storeid) = @_;
1710
1711 my $deleteStorageAccessFn = sub {
1712 my $usercfg = cfs_read_file("user.cfg");
1713 my $modified;
1714
1715 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1716 delete $usercfg->{acl}->{"/storage/$storeid"};
1717 $modified = 1;
1718 }
1719 foreach my $pool (keys %{$usercfg->{pools}}) {
1720 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1721 $modified = 1;
1722 }
1723 cfs_write_file("user.cfg", $usercfg) if $modified;
1724 };
1725
1726 lock_user_config($deleteStorageAccessFn,
1727 "access permissions cleanup for storage $storeid failed");
1728}
1729
018ae3a9
DM
1730sub add_vm_to_pool {
1731 my ($vmid, $pool) = @_;
1732
1733 my $addVMtoPoolFn = sub {
1734 my $usercfg = cfs_read_file("user.cfg");
1735 if (my $data = $usercfg->{pools}->{$pool}) {
1736 $data->{vms}->{$vmid} = 1;
1737 $usercfg->{vms}->{$vmid} = $pool;
1738 cfs_write_file("user.cfg", $usercfg);
1739 }
1740 };
1741
1742 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1743}
1744
1745sub remove_vm_from_pool {
1746 my ($vmid) = @_;
66931b11 1747
018ae3a9
DM
1748 my $delVMfromPoolFn = sub {
1749 my $usercfg = cfs_read_file("user.cfg");
1750 if (my $pool = $usercfg->{vms}->{$vmid}) {
1751 if (my $data = $usercfg->{pools}->{$pool}) {
1752 delete $data->{vms}->{$vmid};
1753 delete $usercfg->{vms}->{$vmid};
1754 cfs_write_file("user.cfg", $usercfg);
1755 }
1756 }
1757 };
1758
1759 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1760}
1761
49b15310 1762my $USER_CONTROLLED_TFA_TYPES = {
fda8ca85
WB
1763 u2f => 1,
1764 oath => 1,
1765};
1766
07692c72
WB
1767sub assert_new_tfa_config_available() {
1768 # FIXME: Assert cluster-wide new-tfa-config support!
1769}
1770
d168ab34
WB
1771sub user_remove_tfa : prototype($) {
1772 my ($userid) = @_;
1773
1774 assert_new_tfa_config_available();
1775
1776 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1777 $tfa_cfg->remove_user($userid);
1778 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1779}
1780
0fe62fa8
WB
1781my sub add_old_yubico_keys : prototype($$$) {
1782 my ($userid, $tfa_cfg, $keys) = @_;
1783
1784 my $count = 0;
1785 foreach my $key (split_list($keys)) {
1786 my $description = "<old userconfig key $count>";
1787 ++$count;
1788 $tfa_cfg->add_yubico_entry($userid, $description, $key);
1789 }
1790}
1791
1792my sub normalize_totp_secret : prototype($) {
1793 my ($key) = @_;
1794
1795 my $binkey;
1796 # See PVE::OTP::oath_verify_otp:
1797 if ($key =~ /^v2-0x([0-9a-fA-F]+)$/) {
1798 # v2, hex
1799 $binkey = pack('H*', $1);
1800 } elsif ($key =~ /^v2-([A-Z2-7=]+)$/) {
1801 # v2, base32
1802 $binkey = MIME::Base32::decode_rfc3548($1);
1803 } elsif ($key =~ /^[A-Z2-7=]{16}$/) {
1804 $binkey = MIME::Base32::decode_rfc3548($key);
1805 } elsif ($key =~ /^[A-Fa-f0-9]{40}$/) {
1806 $binkey = pack('H*', $key);
1807 } else {
1808 return undef;
1809 }
1810
1811 return MIME::Base32::encode_rfc3548($binkey);
1812}
1813
1814my sub add_old_totp_keys : prototype($$$$) {
1815 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1816
1817 my $issuer = 'Proxmox%20VE';
1818 my $account = uri_escape("Old key for $userid");
1819 my $digits = $realm_tfa->{digits} || 6;
1820 my $step = $realm_tfa->{step} || 30;
1821 my $uri = "otpauth://totp/$issuer:$account?digits=$digits&period=$step&algorithm=SHA1&secret=";
1822
1823 my $count = 0;
1824 foreach my $key (split_list($keys)) {
1825 $key = normalize_totp_secret($key);
1826 # and just skip invalid keys:
1827 next if !defined($key);
1828
1829 my $description = "<old userconfig key $count>";
1830 ++$count;
1831 eval { $tfa_cfg->add_totp_entry($userid, $description, $uri . $key) };
1832 warn $@ if $@;
1833 }
1834}
1835
1836sub add_old_keys_to_realm_tfa : prototype($$$$) {
1837 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1838
1839 # if there's no realm tfa configured, we don't know what the keys mean, so we just ignore
1840 # them...
1841 return if !$realm_tfa;
1842
1843 my $type = $realm_tfa->{type};
1844 if ($type eq 'oath') {
1845 add_old_totp_keys($userid, $tfa_cfg, $realm_tfa, $keys);
1846 } elsif ($type eq 'yubico') {
1847 add_old_yubico_keys($userid, $tfa_cfg, $keys);
1848 } else {
1849 # invalid keys, we'll just drop them now...
1850 }
1851}
1852
afb10353
WB
1853sub user_get_tfa : prototype($$$) {
1854 my ($username, $realm, $new_format) = @_;
fda8ca85
WB
1855
1856 my $user_cfg = cfs_read_file('user.cfg');
1857 my $user = $user_cfg->{users}->{$username}
1858 or die "user '$username' not found\n";
1859
1860 my $keys = $user->{keys};
fda8ca85
WB
1861
1862 my $domain_cfg = cfs_read_file('domains.cfg');
1863 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1864 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1865
1866 my $realm_tfa = $realm_cfg->{tfa};
1867 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
1868 if $realm_tfa;
1869
6063b65b
WB
1870 if (!$keys) {
1871 return if !$realm_tfa;
1872 die "missing required 2nd keys\n";
1873 }
1874
0fe62fa8
WB
1875 if ($new_format) {
1876 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1877 if (defined($keys) && $keys !~ /^x(?:!.*)$/) {
1878 add_old_keys_to_realm_tfa($username, $tfa_cfg, $realm_tfa, $keys);
1879 }
1880 return ($tfa_cfg, $realm_tfa);
1881 }
1882
7e58c66d 1883 # new style config starts with an 'x' and optionally contains a !<type> suffix
0a956b94 1884 if ($keys !~ /^x(?:!.*)?$/) {
fda8ca85
WB
1885 # old style config, find the type via the realm
1886 return if !$realm_tfa;
1887 return ($realm_tfa->{type}, {
1888 keys => $keys,
1889 config => $realm_tfa,
1890 });
1891 } else {
1892 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
0fe62fa8
WB
1893 my $tfa = $tfa_cfg->{users}->{$username};
1894 return if !$tfa; # should not happen (user.cfg wasn't cleaned up?)
fda8ca85 1895
0fe62fa8
WB
1896 if ($realm_tfa) {
1897 # if the realm has a tfa setting we need to verify the type:
1898 die "auth domain '$realm' and user have mismatching TFA settings\n"
1899 if $realm_tfa && $realm_tfa->{type} ne $tfa->{type};
afb10353 1900 }
0fe62fa8
WB
1901
1902 return ($tfa->{type}, $tfa->{data});
fda8ca85
WB
1903 }
1904}
1905
3e5bfdf6
DM
1906# bash completion helpers
1907
ab7b19b5
SI
1908register_standard_option('userid-completed',
1909 get_standard_option('userid', { completion => \&complete_username}),
1910);
1911
3e5bfdf6
DM
1912sub complete_username {
1913
1914 my $user_cfg = cfs_read_file('user.cfg');
1915
1916 return [ keys %{$user_cfg->{users}} ];
1917}
1918
1919sub complete_group {
1920
1921 my $user_cfg = cfs_read_file('user.cfg');
1922
1923 return [ keys %{$user_cfg->{groups}} ];
1924}
1925
1926sub complete_realm {
1927
1928 my $domain_cfg = cfs_read_file('domains.cfg');
1929
1930 return [ keys %{$domain_cfg->{ids}} ];
1931}
1932
2c3a6c0a 19331;