1 package PVE
::AccessControl
;
6 use Crypt
::OpenSSL
::Random
;
7 use Crypt
::OpenSSL
::RSA
;
16 use Scalar
::Util
'weaken';
21 use PVE
::Tools
qw(run_command lock_file file_get_contents split_list safe_print);
22 use PVE
::Cluster
qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
23 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
27 use PVE
::Auth
::Plugin
;
32 use PVE
::Auth
::OpenId
;
34 # load and initialize all plugins
36 PVE
::Auth
::AD-
>register();
37 PVE
::Auth
::LDAP-
>register();
38 PVE
::Auth
::PVE-
>register();
39 PVE
::Auth
::PAM-
>register();
40 PVE
::Auth
::OpenId-
>register();
41 PVE
::Auth
::Plugin-
>init();
43 # $authdir must be writable by root only!
44 my $confdir = "/etc/pve";
45 my $authdir = "$confdir/priv";
47 my $pve_www_key_fn = "$confdir/pve-www.key";
49 my $pve_auth_key_files = {
50 priv
=> "$authdir/authkey.key",
51 pub
=> "$confdir/authkey.pub",
52 pubold
=> "$confdir/authkey.pub.old",
55 my $pve_auth_key_cache = {};
57 my $ticket_lifetime = 3600 * 2; # 2 hours
58 my $auth_graceperiod = 60 * 5; # 5 minutes
59 my $authkey_lifetime = 3600 * 24; # rotate every 24 hours
61 Crypt
::OpenSSL
::RSA-
>import_random_seed();
63 cfs_register_file
('user.cfg', \
&parse_user_config
, \
&write_user_config
);
64 cfs_register_file
('priv/tfa.cfg', \
&parse_priv_tfa_config
, \
&write_priv_tfa_config
);
67 PVE
::Auth
::Plugin
::verify_username
(@_);
70 sub pve_verify_realm
{
71 PVE
::Auth
::Plugin
::pve_verify_realm
(@_);
74 # Locking both config files together is only ever allowed in one order:
77 # If we permit the other way round, too, we might end up deadlocking!
78 my $user_config_locked;
79 sub lock_user_config
{
80 my ($code, $errmsg) = @_;
83 $user_config_locked = \
$locked;
84 weaken
$user_config_locked; # make this scope guard signal safe...
86 cfs_lock_file
("user.cfg", undef, $code);
87 $user_config_locked = undef;
89 $errmsg ?
die "$errmsg: $err" : die $err;
94 my ($code, $errmsg) = @_;
96 die "tfa config lock cannot be acquired while holding user config lock\n"
97 if ($user_config_locked && $$user_config_locked);
99 my $res = cfs_lock_file
("priv/tfa.cfg", undef, $code);
101 $errmsg ?
die "$errmsg: $err" : die $err;
107 my $cache_read_key = sub {
110 my $path = $pve_auth_key_files->{$type};
112 my $read_key_and_mtime = sub {
113 my $fh = IO
::File-
>new($path, "r");
115 return undef if !defined($fh);
118 my $pem = PVE
::Tools
::safe_read_from
($fh, 0, 0, $path);
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); };
128 die "Invalid authkey type '$type'\n";
131 return { key
=> $key, mtime
=> $st->mtime };
134 if (!defined($pve_auth_key_cache->{$type})) {
135 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
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->();
143 return $pve_auth_key_cache->{$type};
149 my $type = $old ?
'pubold' : 'pub';
151 my $res = $cache_read_key->($type);
152 return undef if !defined($res);
154 return wantarray ?
($res->{key
}, $res->{mtime
}) : $res->{key
};
158 my $res = $cache_read_key->('priv');
160 if (!defined($res) || !check_authkey
(1)) {
162 $res = $cache_read_key->('priv');
165 return wantarray ?
($res->{key
}, $res->{mtime
}) : $res->{key
};
171 # skip check if non-quorate, as rotation is not possible anyway
172 return 1 if !PVE
::Cluster
::check_cfs_quorum
(1);
174 my ($pub_key, $mtime) = get_pubkey
();
176 warn "auth key pair missing, generating new one..\n" if !$quiet;
180 if ($now - $mtime >= $authkey_lifetime) {
181 warn "auth key pair too old, rotating..\n" if !$quiet;;
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;
193 warn "auth key pair generated in the future (key $mtime > host $now), rotating..\n" if !$quiet;
196 warn "auth key new enough, skipping rotation\n" if !$quiet;;
203 return if $authkey_lifetime == 0;
205 PVE
::Cluster
::cfs_lock_authkey
(undef, sub {
206 # re-check with lock to avoid double rotation in clusters
207 return if check_authkey
();
209 my $old = get_pubkey
();
210 my $new = Crypt
::OpenSSL
::RSA-
>generate_key(2048);
214 my $pem = $old->get_public_key_x509_string();
215 # mtime is used for caching and ticket age range calculation
216 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pubold
}, $pem);
218 die "Failed to store old auth key: $@\n" if $@;
222 my $pem = $new->get_public_key_x509_string();
223 # mtime is used for caching and ticket age range calculation,
224 # should be close to that of pubold above
225 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pub
}, $pem);
229 warn "Failed to store new auth key - $@\n";
230 warn "Reverting to previous auth key\n";
232 my $pem = $old->get_public_key_x509_string();
233 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pub
}, $pem);
235 die "Failed to restore old auth key: $@\n" if $@;
237 die "Failed to store new auth key - $@\n";
242 my $pem = $new->get_private_key_string();
243 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{priv
}, $pem);
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
};
255 PVE
::JSONSchema
::register_standard_option
('tokenid', {
256 description
=> "API token identifier.",
258 format
=> "pve-tokenid",
261 our $token_subid_regex = $PVE::Auth
::Plugin
::realm_regex
;
263 # username@realm username realm tokenid
264 our $token_full_regex = qr/((${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex}))!(${token_subid_regex})/;
266 our $userid_or_token_regex = qr/^$PVE::Auth::Plugin::user_regex\@$PVE::Auth::Plugin::realm_regex(?:!$token_subid_regex)?$/;
269 my ($tokenid, $noerr) = @_;
271 if ($tokenid =~ /^${token_full_regex}$/) {
275 die "'$tokenid' is not a valid token ID - not able to split into user and token parts\n" if !$noerr;
281 my ($username, $tokensubid) = @_;
283 my $joined = "${username}!${tokensubid}";
285 return pve_verify_tokenid
($joined);
288 PVE
::JSONSchema
::register_format
('pve-tokenid', \
&pve_verify_tokenid
);
289 sub pve_verify_tokenid
{
290 my ($tokenid, $noerr) = @_;
292 if ($tokenid =~ /^${token_full_regex}$/) {
293 return wantarray ?
($tokenid, $2, $3, $4) : $tokenid;
296 die "value '$tokenid' does not look like a valid token ID\n" if !$noerr;
302 my $csrf_prevention_secret;
303 my $csrf_prevention_secret_legacy;
304 my $get_csrfr_secret = sub {
305 if (!$csrf_prevention_secret) {
306 my $input = PVE
::Tools
::file_get_contents
($pve_www_key_fn);
307 $csrf_prevention_secret = Digest
::SHA
::hmac_sha256_base64
($input);
308 $csrf_prevention_secret_legacy = Digest
::SHA
::sha1_base64
($input);
310 return $csrf_prevention_secret;
313 sub assemble_csrf_prevention_token
{
316 my $secret = &$get_csrfr_secret();
318 return PVE
::Ticket
::assemble_csrf_prevention_token
($secret, $username);
321 sub verify_csrf_prevention_token
{
322 my ($username, $token, $noerr) = @_;
324 my $secret = $get_csrfr_secret->();
326 # FIXME: remove with PVE 7 and/or refactor all into PVE::Ticket ?
327 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
329 if (length($sig) == 27) {
330 # the legacy secret got populated by above get_csrfr_secret call
331 $secret = $csrf_prevention_secret_legacy;
335 return PVE
::Ticket
::verify_csrf_prevention_token
(
336 $secret, $username, $token, -$auth_graceperiod, $ticket_lifetime, $noerr);
339 my $get_ticket_age_range = sub {
340 my ($now, $mtime, $rotated) = @_;
342 my $key_age = $now - $mtime;
343 $key_age = 0 if $key_age < 0;
345 my $min = -$auth_graceperiod;
346 my $max = $ticket_lifetime;
349 # ticket creation after rotation is not allowed
350 $min = $key_age - $auth_graceperiod;
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;
357 warn "Cluster not quorate - extending auth key lifetime!\n";
361 $max = $key_age + $auth_graceperiod if $key_age < $ticket_lifetime;
364 return undef if $min > $ticket_lifetime;
368 sub assemble_ticket
: prototype($;$) {
369 my ($data, $aad) = @_;
371 my $rsa_priv = get_privkey
();
373 return PVE
::Ticket
::assemble_rsa_ticket
($rsa_priv, 'PVE', $data, $aad);
376 # Returns the username, "age" and tfa info.
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.
381 # New-style auth still uses this function, but sets `$tfa_ticket` to true when validating the tfa
383 sub verify_ticket
: prototype($;$$) {
384 my ($ticket, $noerr, $tfa_ticket_aad) = @_;
391 my ($rsa_pub, $rsa_mtime) = get_pubkey
($old);
392 return undef if !$rsa_pub;
394 my ($min, $max) = $get_ticket_age_range->($now, $rsa_mtime, $old);
395 return undef if !defined($min);
397 return PVE
::Ticket
::verify_rsa_ticket
(
398 $rsa_pub, 'PVE', $ticket, $tfa_ticket_aad, $min, $max, 1);
401 my ($data, $age) = $check->();
403 # check with old, rotated key if current key failed
404 ($data, $age) = $check->(1) if !defined($data);
406 my $auth_failure = sub {
410 # raise error via undef ticket
411 PVE
::Ticket
::verify_rsa_ticket
(undef, 'PVE');
415 if (!defined($data)) {
416 return $auth_failure->();
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!(.*)$/) {
427 my ($username, $tfa_info);
428 if ($data =~ /^!tfa!(.*)$/) {
429 # PBS style half-authenticated ticket, contains a json string form of a `TfaChallenge`
431 # This type of ticket does not contain the user name.
432 return { type
=> 'new', data
=> $1 };
434 if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
435 # Ticket for u2f-users:
436 ($username, my $challenge) = ($1, $2);
437 if ($challenge eq 'verified') {
438 # u2f challenge was completed
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->();
447 challenge
=> $challenge,
449 } elsif ($data =~ /^tfa!(.*)$/) {
450 # TOTP and Yubico don't require a challenge so this is the generic
451 # 'missing 2nd factor ticket'
453 $tfa_info = { type
=> 'tfa' };
455 # Regular ticket (full access)
459 return undef if !PVE
::Auth
::Plugin
::verify_username
($username, $noerr);
461 return wantarray ?
($username, $age, $tfa_info) : $username;
465 my ($api_token) = @_;
467 die "no API token specified\n" if !$api_token;
469 my ($tokenid, $value);
470 if ($api_token =~ /^(.*)=(.*)$/) {
474 die "no tokenid specified\n";
477 my ($username, $token) = split_tokenid
($tokenid);
479 my $usercfg = cfs_read_file
('user.cfg');
480 check_user_enabled
($usercfg, $username);
481 check_token_exist
($usercfg, $username, $token);
483 my $user = $usercfg->{users
}->{$username};
484 my $token_info = $user->{tokens
}->{$token};
487 die "token expired\n" if $token_info->{expire
} && ($token_info->{expire
} < $ctime);
489 die "invalid token value!\n" if !PVE
::Cluster
::verify_token
($tokenid, $value);
491 return wantarray ?
($tokenid) : $tokenid;
494 my $assemble_short_lived_ticket = sub {
495 my ($prefix, $username, $path) = @_;
497 my $rsa_priv = get_privkey
();
499 $path = normalize_path
($path);
501 my $secret_data = "$username:$path";
503 return PVE
::Ticket
::assemble_rsa_ticket
(
504 $rsa_priv, $prefix, undef, $secret_data);
507 my $verify_short_lived_ticket = sub {
508 my ($ticket, $prefix, $username, $path, $noerr) = @_;
510 $path = normalize_path
($path);
512 my $secret_data = "$username:$path";
514 my ($rsa_pub, $rsa_mtime) = get_pubkey
();
515 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime && $authkey_lifetime > 0)) {
519 # raise error via undef ticket
520 PVE
::Ticket
::verify_rsa_ticket
($rsa_pub, $prefix);
524 return PVE
::Ticket
::verify_rsa_ticket
(
525 $rsa_pub, $prefix, $ticket, $secret_data, -20, 40, $noerr);
529 # - they do not contain the username in plain text
530 # - they are restricted to a specific resource path (example: '/vms/100')
531 sub assemble_vnc_ticket
{
532 my ($username, $path) = @_;
534 return $assemble_short_lived_ticket->('PVEVNC', $username, $path);
537 sub verify_vnc_ticket
{
538 my ($ticket, $username, $path, $noerr) = @_;
540 return $verify_short_lived_ticket->($ticket, 'PVEVNC', $username, $path, $noerr);
544 # - they do not contain the username in plain text
545 # - they are restricted to a specific resource path (example: '/vms/100', '/socket/run/qemu-server/123.storage')
546 sub assemble_tunnel_ticket
{
547 my ($username, $path) = @_;
549 return $assemble_short_lived_ticket->('PVETUNNEL', $username, $path);
552 sub verify_tunnel_ticket
{
553 my ($ticket, $username, $path, $noerr) = @_;
555 return $verify_short_lived_ticket->($ticket, 'PVETUNNEL', $username, $path, $noerr);
558 sub assemble_spice_ticket
{
559 my ($username, $vmid, $node) = @_;
561 my $secret = &$get_csrfr_secret();
563 return PVE
::Ticket
::assemble_spice_ticket
(
564 $secret, $username, $vmid, $node);
567 sub verify_spice_connect_url
{
568 my ($connect_str) = @_;
570 my $secret = &$get_csrfr_secret();
572 return PVE
::Ticket
::verify_spice_connect_url
($secret, $connect_str);
575 sub read_x509_subject_spice
{
579 my $bio = Net
::SSLeay
::BIO_new_file
($filename, 'r');
580 die "Could not open $filename using OpenSSL\n"
583 my $x509 = Net
::SSLeay
::PEM_read_bio_X509
($bio);
584 Net
::SSLeay
::BIO_free
($bio);
586 die "Could not parse X509 certificate in $filename\n"
589 my $nameobj = Net
::SSLeay
::X509_get_subject_name
($x509);
590 my $subject = Net
::SSLeay
::X509_NAME_oneline
($nameobj);
591 Net
::SSLeay
::X509_free
($x509);
593 # remote-viewer wants comma as seperator (not '/')
595 $subject =~ s!/(\w+=)!,$1!g;
600 # helper to generate SPICE remote-viewer configuration
601 sub remote_viewer_config
{
602 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
605 my $host = `hostname -f` || PVE
::INotify
::nodename
();
610 my ($ticket, $proxyticket) = assemble_spice_ticket
($authuser, $vmid, $node);
612 my $filename = "/etc/pve/local/pve-ssl.pem";
613 my $subject = read_x509_subject_spice
($filename);
615 my $cacert = PVE
::Tools
::file_get_contents
("/etc/pve/pve-root-ca.pem", 8192);
616 $cacert =~ s/\n/\\n/g;
618 $proxy = "[$proxy]" if Net
::IP
::ip_is_ipv6
($proxy);
620 'secure-attention' => "Ctrl+Alt+Ins",
621 'toggle-fullscreen' => "Shift+F11",
622 'release-cursor' => "Ctrl+Alt+R",
625 host
=> $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
626 proxy
=> "http://$proxy:3128",
628 'host-subject' => $subject,
631 'delete-this-file' => 1,
634 return ($ticket, $proxyticket, $config);
637 sub check_user_exist
{
638 my ($usercfg, $username, $noerr) = @_;
640 $username = PVE
::Auth
::Plugin
::verify_username
($username, $noerr);
641 return undef if !$username;
643 return $usercfg->{users
}->{$username} if $usercfg && $usercfg->{users
}->{$username};
645 die "no such user ('$username')\n" if !$noerr;
650 sub check_user_enabled
{
651 my ($usercfg, $username, $noerr) = @_;
653 my $data = check_user_exist
($usercfg, $username, $noerr);
654 return undef if !$data;
656 return 1 if $data->{enable
};
658 die "user '$username' is disabled\n" if !$noerr;
661 my $expire = $usercfg->{users
}->{$username}->{expire
};
663 die "account expired\n" if $expire && ($expire < $ctime);
668 sub check_token_exist
{
669 my ($usercfg, $username, $tokenid, $noerr) = @_;
671 my $user = check_user_exist
($usercfg, $username, $noerr);
672 return undef if !$user;
674 return $user->{tokens
}->{$tokenid}
675 if defined($user->{tokens
}) && $user->{tokens
}->{$tokenid};
677 die "no such token '$tokenid' for user '$username'\n" if !$noerr;
683 sub verify_one_time_pw
{
684 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
686 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
688 # fixme: proxy support?
691 if ($type eq 'yubico') {
692 PVE
::OTP
::yubico_verify_otp
($otp, $keys, $tfa_cfg->{url
},
693 $tfa_cfg->{id
}, $tfa_cfg->{key
}, $proxy);
694 } elsif ($type eq 'oath') {
695 PVE
::OTP
::oath_verify_otp
($otp, $keys, $tfa_cfg->{step
}, $tfa_cfg->{digits
});
697 die "unknown tfa type '$type'\n";
701 # password should be utf8 encoded
702 # Note: some plugins delay/sleep if auth fails
703 sub authenticate_user
: prototype($$$$;$) {
704 my ($username, $password, $otp, $new_format, $tfa_challenge) = @_;
706 die "no username specified\n" if !$username;
710 ($username, $ruid, $realm) = PVE
::Auth
::Plugin
::verify_username
($username);
712 my $usercfg = cfs_read_file
('user.cfg');
714 check_user_enabled
($usercfg, $username);
716 my $domain_cfg = cfs_read_file
('domains.cfg');
718 my $cfg = $domain_cfg->{ids
}->{$realm};
719 die "auth domain '$realm' does not exist\n" if !$cfg;
720 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
722 if ($tfa_challenge) {
723 # This is the 2nd factor, use the password for the OTP response.
724 my $tfa_challenge = authenticate_2nd_new
($username, $realm, $password, $tfa_challenge);
725 return wantarray ?
($username, $tfa_challenge) : $username;
728 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
731 # This is the first factor with an optional immediate 2nd factor for TOTP:
732 my $tfa_challenge = authenticate_2nd_new
($username, $realm, $otp, $tfa_challenge);
733 return wantarray ?
($username, $tfa_challenge) : $username;
735 return authenticate_2nd_old
($username, $realm, $otp);
739 sub authenticate_2nd_old
: prototype($$$) {
740 my ($username, $realm, $otp) = @_;
742 my ($type, $tfa_data) = user_get_tfa
($username, $realm, 0);
744 if ($type eq 'u2f') {
745 # Note that if the user did not manage to complete the initial u2f registration
746 # challenge we have a hash containing a 'challenge' entry in the user's tfa.cfg entry:
747 $tfa_data = undef if exists $tfa_data->{challenge
};
748 } elsif (!defined($otp)) {
749 # The user requires a 2nd factor but has not provided one. Return success but
750 # don't clear $tfa_data.
752 my $keys = $tfa_data->{keys};
753 my $tfa_cfg = $tfa_data->{config
};
754 verify_one_time_pw
($type, $username, $keys, $tfa_cfg, $otp);
758 # Return the type along with the rest:
767 return wantarray ?
($username, $tfa_data) : $username;
770 # Returns a tfa challenge or undef.
771 sub authenticate_2nd_new
: prototype($$$$) {
772 my ($username, $realm, $otp, $tfa_challenge) = @_;
774 my $result = lock_tfa_config
(sub {
775 my ($tfa_cfg, $realm_tfa) = user_get_tfa
($username, $realm, 1);
777 if (!defined($tfa_cfg)) {
781 my $realm_type = $realm_tfa && $realm_tfa->{type
};
782 $realm_type = 'totp' if $realm_type eq 'oath'; # we used to call it that
783 # verify realm type unless using recovery keys:
784 if (defined($realm_type)) {
785 if ($realm_type eq 'yubico') {
786 # Yubico auth will not be supported in rust for now...
787 if (!defined($tfa_challenge)) {
788 my $challenge = { yubico
=> JSON
::true
};
789 # Even with yubico auth we do allow recovery keys to be used:
790 if (my $recovery = $tfa_cfg->recovery_state($username)) {
791 $challenge->{recovery
} = $recovery;
793 return to_json
($challenge);
796 if ($otp =~ /^yubico:(.*)$/) {
798 # Defer to after unlocking the TFA config:
800 authenticate_yubico_new
(
801 $tfa_cfg, $username, $realm_tfa, $tfa_challenge, $otp,
809 if ($otp !~ /^([^:]+):/) {
810 die "bad otp response\n";
815 die "realm requires $realm_type authentication\n"
816 if $response_type && $response_type ne 'recovery' && $response_type ne $realm_type;
819 configure_u2f_and_wa
($tfa_cfg);
822 if (defined($tfa_challenge)) {
823 $tfa_challenge = verify_ticket
($tfa_challenge, 0, $username);
824 $must_save = $tfa_cfg->authentication_verify($username, $tfa_challenge, $otp);
825 $tfa_challenge = undef;
827 $tfa_challenge = $tfa_cfg->authentication_challenge($username);
829 if (defined($tfa_challenge)) {
830 $must_save = $tfa_cfg->authentication_verify($username, $tfa_challenge, $otp);
832 die "no such challenge\n";
838 cfs_write_file
('priv/tfa.cfg', $tfa_cfg);
841 return $tfa_challenge;
844 # Yubico auth returns the authentication sub:
845 if (ref($result) eq 'CODE') {
846 $result = $result->();
852 sub authenticate_yubico_new
: prototype($$$) {
853 my ($tfa_cfg, $username, $realm, $tfa_challenge, $otp) = @_;
855 $tfa_challenge = verify_ticket
($tfa_challenge, 0, $username);
856 $tfa_challenge = from_json
($tfa_challenge);
858 if (!$tfa_challenge->{yubico
}) {
859 die "no such challenge\n";
862 my $keys = $tfa_cfg->get_yubico_keys($username);
863 die "no keys configured\n" if !defined($keys) || !length($keys);
865 authenticate_yubico_do
($otp, $keys, $realm);
867 # return `undef` to clear the tfa challenge.
871 sub authenticate_yubico_do
: prototype($$$) {
872 my ($value, $keys, $realm) = @_;
874 # fixme: proxy support?
877 PVE
::OTP
::yubico_verify_otp
($value, $keys, $realm->{url
}, $realm->{id
}, $realm->{key
}, $proxy);
880 sub configure_u2f_and_wa
: prototype($) {
883 my $dc = cfs_read_file
('datacenter.cfg');
884 if (my $u2f = $dc->{u2f
}) {
885 my $origin = $u2f->{origin
};
886 if (!defined($origin)) {
887 my $rpcenv = PVE
::RPCEnvironment
::get
();
888 $origin = $rpcenv->get_request_host(1);
890 $origin = "https://$origin";
892 die "failed to figure out u2f origin\n";
895 $tfa_cfg->set_u2f_config({
897 appid
=> $u2f->{appid
},
900 if (my $wa = $dc->{webauthn
}) {
901 $tfa_cfg->set_webauthn_config($wa);
905 sub domain_set_password
{
906 my ($realm, $username, $password) = @_;
908 die "no auth domain specified" if !$realm;
910 my $domain_cfg = cfs_read_file
('domains.cfg');
912 my $cfg = $domain_cfg->{ids
}->{$realm};
913 die "auth domain '$realm' does not exist\n" if !$cfg;
914 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
915 $plugin->store_password($cfg, $realm, $username, $password);
919 my ($username, $usercfg, $group) = @_;
921 $usercfg->{users
}->{$username}->{groups
}->{$group} = 1;
922 $usercfg->{groups
}->{$group}->{users
}->{$username} = 1;
925 sub delete_user_group
{
926 my ($username, $usercfg) = @_;
928 foreach my $group (keys %{$usercfg->{groups
}}) {
930 delete ($usercfg->{groups
}->{$group}->{users
}->{$username})
931 if $usercfg->{groups
}->{$group}->{users
}->{$username};
935 sub delete_user_acl
{
936 my ($username, $usercfg) = @_;
938 foreach my $acl (keys %{$usercfg->{acl
}}) {
940 delete ($usercfg->{acl
}->{$acl}->{users
}->{$username})
941 if $usercfg->{acl
}->{$acl}->{users
}->{$username};
945 sub delete_group_acl
{
946 my ($group, $usercfg) = @_;
948 foreach my $acl (keys %{$usercfg->{acl
}}) {
950 delete ($usercfg->{acl
}->{$acl}->{groups
}->{$group})
951 if $usercfg->{acl
}->{$acl}->{groups
}->{$group};
955 sub delete_pool_acl
{
956 my ($pool, $usercfg) = @_;
958 my $path = "/pool/$pool";
960 delete ($usercfg->{acl
}->{$path})
963 # we automatically create some predefined roles by splitting privs
964 # into 3 groups (per category)
965 # root: only root is allowed to do that
966 # admin: an administrator can to that
967 # user: a normal user/customer can to that
977 'VM.Config.Options', # covers all other things
983 'VM.Snapshot.Rollback',
986 'VM.Config.CDROM', # change CDROM media
987 'VM.Config.Cloudinit',
999 'Sys.Modify', # edit/change node settings
1002 'Permissions.Modify',
1014 'Datastore.Allocate',
1015 'Datastore.AllocateTemplate',
1018 'Datastore.AllocateSpace',
1040 'Group.Allocate', # edit/change group settings
1041 'Realm.AllocateUser',
1049 'Pool.Allocate', # create/delete pools
1060 my $valid_privs = {};
1062 my $special_roles = {
1063 'NoAccess' => {}, # no privileges
1064 'Administrator' => $valid_privs, # all privileges
1069 foreach my $cat (keys %$privgroups) {
1070 my $cd = $privgroups->{$cat};
1071 foreach my $p (@{$cd->{root
}}, @{$cd->{admin
}},
1072 @{$cd->{user
}}, @{$cd->{audit
}}) {
1073 $valid_privs->{$p} = 1;
1075 foreach my $p (@{$cd->{admin
}}, @{$cd->{user
}}, @{$cd->{audit
}}) {
1077 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
1078 $special_roles->{"PVEAdmin"}->{$p} = 1;
1080 if (scalar(@{$cd->{user
}})) {
1081 foreach my $p (@{$cd->{user
}}, @{$cd->{audit
}}) {
1082 $special_roles->{"PVE${cat}User"}->{$p} = 1;
1085 foreach my $p (@{$cd->{audit
}}) {
1086 $special_roles->{"PVEAuditor"}->{$p} = 1;
1090 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
1095 sub create_priv_properties
{
1096 my $properties = {};
1097 foreach my $priv (keys %$valid_privs) {
1098 $properties->{$priv} = {
1106 sub role_is_special
{
1108 return (exists $special_roles->{$role}) ?
1 : 0;
1111 sub add_role_privs
{
1112 my ($role, $usercfg, $privs) = @_;
1116 die "role '$role' does not exist\n" if !$usercfg->{roles
}->{$role};
1118 foreach my $priv (split_list
($privs)) {
1119 if (defined ($valid_privs->{$priv})) {
1120 $usercfg->{roles
}->{$role}->{$priv} = 1;
1122 die "invalid privilege '$priv'\n";
1127 sub lookup_username
{
1128 my ($username, $noerr) = @_;
1130 $username =~ m!^(${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex})$!;
1133 my $domain_cfg = cfs_read_file
("domains.cfg");
1134 my $casesensitive = $domain_cfg->{ids
}->{$realm}->{'case-sensitive'} // 1;
1135 my $usercfg = cfs_read_file
('user.cfg');
1137 if (!$casesensitive) {
1138 my @matches = grep { lc $username eq lc $_ } (keys %{$usercfg->{users
}});
1140 die "ambiguous case insensitive match of username '$username', cannot safely grant access!\n"
1141 if scalar @matches > 1 && !$noerr;
1149 sub normalize_path
{
1156 $path = '/' if !$path;
1158 $path = "/$path" if $path !~ m
|^/|;
1160 return undef if $path !~ m
|^[[:alnum
:]\
.\
-\_\
/]+$|;
1167 return $path =~ m
!^(
1171 |/access/groups
/[[:alnum
:]\
.\
-\_
]+
1173 |/access/realm
/[[:alnum
:]\
.\
-\_
]+
1175 |/nodes/[[:alnum
:]\
.\
-\_
]+
1177 |/pool/[[:alnum
:]\
.\
-\_
]+
1179 |/sdn/zones
/[[:alnum
:]\
.\
-\_
]+
1180 |/sdn/vnets
/[[:alnum
:]\
.\
-\_
]+
1182 |/storage/[[:alnum
:]\
.\
-\_
]+
1184 |/vms/[1-9][0-9]{2,}
1188 PVE
::JSONSchema
::register_format
('pve-groupid', \
&verify_groupname
);
1189 sub verify_groupname
{
1190 my ($groupname, $noerr) = @_;
1192 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1194 die "group name '$groupname' contains invalid characters\n" if !$noerr;
1202 PVE
::JSONSchema
::register_format
('pve-roleid', \
&verify_rolename
);
1203 sub verify_rolename
{
1204 my ($rolename, $noerr) = @_;
1206 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
1208 die "role name '$rolename' contains invalid characters\n" if !$noerr;
1216 PVE
::JSONSchema
::register_format
('pve-poolid', \
&verify_poolname
);
1217 sub verify_poolname
{
1218 my ($poolname, $noerr) = @_;
1220 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1222 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
1230 PVE
::JSONSchema
::register_format
('pve-priv', \
&verify_privname
);
1231 sub verify_privname
{
1232 my ($priv, $noerr) = @_;
1234 if (!$valid_privs->{$priv}) {
1235 die "invalid privilege '$priv'\n" if !$noerr;
1243 sub userconfig_force_defaults
{
1246 foreach my $r (keys %$special_roles) {
1247 $cfg->{roles
}->{$r} = $special_roles->{$r};
1250 # add root user if not exists
1251 if (!$cfg->{users
}->{'root@pam'}) {
1252 $cfg->{users
}->{'root@pam'}->{enable
} = 1;
1256 sub parse_user_config
{
1257 my ($filename, $raw) = @_;
1261 userconfig_force_defaults
($cfg);
1263 $raw = '' if !defined($raw);
1264 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1268 foreach my $d (split (/:/, $line)) {
1274 my $et = shift @data;
1276 if ($et eq 'user') {
1277 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
1279 my (undef, undef, $realm) = PVE
::Auth
::Plugin
::verify_username
($user, 1);
1281 warn "user config - ignore user '$user' - invalid user name\n";
1285 $enable = $enable ?
1 : 0;
1287 $expire = 0 if !$expire;
1289 if ($expire !~ m/^\d+$/) {
1290 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
1293 $expire = int($expire);
1295 #if (!verify_groupname ($group, 1)) {
1296 # warn "user config - ignore user '$user' - invalid characters in group name\n";
1300 $cfg->{users
}->{$user} = {
1304 $cfg->{users
}->{$user}->{firstname
} = PVE
::Tools
::decode_text
($firstname) if $firstname;
1305 $cfg->{users
}->{$user}->{lastname
} = PVE
::Tools
::decode_text
($lastname) if $lastname;
1306 $cfg->{users
}->{$user}->{email
} = $email;
1307 $cfg->{users
}->{$user}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1308 $cfg->{users
}->{$user}->{expire
} = $expire;
1309 # keys: allowed yubico key ids or oath secrets (base32 encoded)
1310 $cfg->{users
}->{$user}->{keys} = $keys if $keys;
1312 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
1313 #$cfg->{groups}->{$group}->{$user} = 1;
1315 } elsif ($et eq 'group') {
1316 my ($group, $userlist, $comment) = @data;
1318 if (!verify_groupname
($group, 1)) {
1319 warn "user config - ignore group '$group' - invalid characters in group name\n";
1323 # make sure to add the group (even if there are no members)
1324 $cfg->{groups
}->{$group} = { users
=> {} } if !$cfg->{groups
}->{$group};
1326 $cfg->{groups
}->{$group}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1328 foreach my $user (split_list
($userlist)) {
1330 if (!PVE
::Auth
::Plugin
::verify_username
($user, 1)) {
1331 warn "user config - ignore invalid group member '$user'\n";
1335 if ($cfg->{users
}->{$user}) { # user exists
1336 $cfg->{users
}->{$user}->{groups
}->{$group} = 1;
1338 warn "user config - ignore invalid group member '$user'\n";
1340 $cfg->{groups
}->{$group}->{users
}->{$user} = 1;
1343 } elsif ($et eq 'role') {
1344 my ($role, $privlist) = @data;
1346 if (!verify_rolename
($role, 1)) {
1347 warn "user config - ignore role '$role' - invalid characters in role name\n";
1351 # make sure to add the role (even if there are no privileges)
1352 $cfg->{roles
}->{$role} = {} if !$cfg->{roles
}->{$role};
1354 foreach my $priv (split_list
($privlist)) {
1355 if (defined ($valid_privs->{$priv})) {
1356 $cfg->{roles
}->{$role}->{$priv} = 1;
1358 warn "user config - ignore invalid privilege '$priv'\n";
1362 } elsif ($et eq 'acl') {
1363 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
1365 $propagate = $propagate ?
1 : 0;
1367 if (my $path = normalize_path
($pathtxt)) {
1368 foreach my $role (split_list
($rolelist)) {
1370 if (!verify_rolename
($role, 1)) {
1371 warn "user config - ignore invalid role name '$role' in acl\n";
1375 if (!$cfg->{roles
}->{$role}) {
1376 warn "user config - ignore invalid acl role '$role'\n";
1380 foreach my $ug (split_list
($uglist)) {
1381 my ($group) = $ug =~ m/^@(\S+)$/;
1383 if ($group && verify_groupname
($group, 1)) {
1384 if (!$cfg->{groups
}->{$group}) { # group does not exist
1385 warn "user config - ignore invalid acl group '$group'\n";
1387 $cfg->{acl
}->{$path}->{groups
}->{$group}->{$role} = $propagate;
1388 } elsif (PVE
::Auth
::Plugin
::verify_username
($ug, 1)) {
1389 if (!$cfg->{users
}->{$ug}) { # user does not exist
1390 warn "user config - ignore invalid acl member '$ug'\n";
1392 $cfg->{acl
}->{$path}->{users
}->{$ug}->{$role} = $propagate;
1393 } elsif (my ($user, $token) = split_tokenid
($ug, 1)) {
1394 if (check_token_exist
($cfg, $user, $token, 1)) {
1395 $cfg->{acl
}->{$path}->{tokens
}->{$ug}->{$role} = $propagate;
1397 warn "user config - ignore invalid acl token '$ug'\n";
1400 warn "user config - invalid user/group '$ug' in acl\n";
1405 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1407 } elsif ($et eq 'pool') {
1408 my ($pool, $comment, $vmlist, $storelist) = @data;
1410 if (!verify_poolname
($pool, 1)) {
1411 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1415 # make sure to add the pool (even if there are no members)
1416 $cfg->{pools
}->{$pool} = { vms
=> {}, storage
=> {} } if !$cfg->{pools
}->{$pool};
1418 $cfg->{pools
}->{$pool}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1420 foreach my $vmid (split_list
($vmlist)) {
1421 if ($vmid !~ m/^\d+$/) {
1422 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1427 if ($cfg->{vms
}->{$vmid}) {
1428 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1432 $cfg->{pools
}->{$pool}->{vms
}->{$vmid} = 1;
1434 # record vmid ==> pool relation
1435 $cfg->{vms
}->{$vmid} = $pool;
1438 foreach my $storeid (split_list
($storelist)) {
1439 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1440 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1443 $cfg->{pools
}->{$pool}->{storage
}->{$storeid} = 1;
1445 } elsif ($et eq 'token') {
1446 my ($tokenid, $expire, $privsep, $comment) = @data;
1448 my ($user, $token) = split_tokenid
($tokenid, 1);
1449 if (!($user && $token)) {
1450 warn "user config - ignore invalid tokenid '$tokenid'\n";
1454 $privsep = $privsep ?
1 : 0;
1456 $expire = 0 if !$expire;
1458 if ($expire !~ m/^\d+$/) {
1459 warn "user config - ignore token '$tokenid' - (illegal characters in expire '$expire')\n";
1462 $expire = int($expire);
1464 if (my $user_cfg = $cfg->{users
}->{$user}) { # user exists
1465 $user_cfg->{tokens
}->{$token} = {} if !$user_cfg->{tokens
}->{$token};
1466 my $token_cfg = $user_cfg->{tokens
}->{$token};
1467 $token_cfg->{privsep
} = $privsep;
1468 $token_cfg->{expire
} = $expire;
1469 $token_cfg->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1471 warn "user config - ignore token '$tokenid' - user does not exist\n";
1474 warn "user config - ignore config line: $line\n";
1478 userconfig_force_defaults
($cfg);
1483 sub write_user_config
{
1484 my ($filename, $cfg) = @_;
1488 foreach my $user (sort keys %{$cfg->{users
}}) {
1489 my $d = $cfg->{users
}->{$user};
1490 my $firstname = $d->{firstname
} ? PVE
::Tools
::encode_text
($d->{firstname
}) : '';
1491 my $lastname = $d->{lastname
} ? PVE
::Tools
::encode_text
($d->{lastname
}) : '';
1492 my $email = $d->{email
} || '';
1493 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1494 my $expire = int($d->{expire
} || 0);
1495 my $enable = $d->{enable
} ?
1 : 0;
1496 my $keys = $d->{keys} ?
$d->{keys} : '';
1497 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1499 my $user_tokens = $d->{tokens
};
1500 foreach my $token (sort keys %$user_tokens) {
1501 my $td = $user_tokens->{$token};
1502 my $full_tokenid = join_tokenid
($user, $token);
1503 my $comment = $td->{comment
} ? PVE
::Tools
::encode_text
($td->{comment
}) : '';
1504 my $expire = int($td->{expire
} || 0);
1505 my $privsep = $td->{privsep
} ?
1 : 0;
1506 $data .= "token:$full_tokenid:$expire:$privsep:$comment:\n";
1512 foreach my $group (sort keys %{$cfg->{groups
}}) {
1513 my $d = $cfg->{groups
}->{$group};
1514 my $list = join (',', sort keys %{$d->{users
}});
1515 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1516 $data .= "group:$group:$list:$comment:\n";
1521 foreach my $pool (sort keys %{$cfg->{pools
}}) {
1522 my $d = $cfg->{pools
}->{$pool};
1523 my $vmlist = join (',', sort keys %{$d->{vms
}});
1524 my $storelist = join (',', sort keys %{$d->{storage
}});
1525 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1526 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1531 foreach my $role (sort keys %{$cfg->{roles
}}) {
1532 next if $special_roles->{$role};
1534 my $d = $cfg->{roles
}->{$role};
1535 my $list = join (',', sort keys %$d);
1536 $data .= "role:$role:$list:\n";
1541 my $collect_rolelist_members = sub {
1542 my ($acl_members, $result, $prefix, $exclude) = @_;
1544 foreach my $member (keys %$acl_members) {
1545 next if $exclude && $member eq $exclude;
1549 foreach my $role (sort keys %{$acl_members->{$member}}) {
1550 my $propagate = $acl_members->{$member}->{$role};
1559 $result->{0}->{$l0}->{"${prefix}${member}"} = 1 if $l0;
1560 $result->{1}->{$l1}->{"${prefix}${member}"} = 1 if $l1;
1564 foreach my $path (sort keys %{$cfg->{acl
}}) {
1565 my $d = $cfg->{acl
}->{$path};
1567 my $rolelist_members = {};
1569 $collect_rolelist_members->($d->{'groups'}, $rolelist_members, '@');
1571 # no need to save 'root@pam', it is always 'Administrator'
1572 $collect_rolelist_members->($d->{'users'}, $rolelist_members, '', 'root@pam');
1574 $collect_rolelist_members->($d->{'tokens'}, $rolelist_members, '');
1576 foreach my $propagate (0,1) {
1577 my $filtered = $rolelist_members->{$propagate};
1578 foreach my $rolelist (sort keys %$filtered) {
1579 my $uglist = join (',', sort keys %{$filtered->{$rolelist}});
1580 $data .= "acl:$propagate:$path:$uglist:$rolelist:\n";
1589 # Creates a `PVE::RS::TFA` instance from the raw config data.
1590 # Its contained hash will also support the legacy functionality.
1591 sub parse_priv_tfa_config
{
1592 my ($filename, $raw) = @_;
1594 $raw = '' if !defined($raw);
1595 my $cfg = PVE
::RS
::TFA-
>new($raw);
1597 # Purge invalid users:
1598 foreach my $user ($cfg->users()->@*) {
1599 my (undef, undef, $realm) = PVE
::Auth
::Plugin
::verify_username
($user, 1);
1601 warn "user tfa config - ignore user '$user' - invalid user name\n";
1602 $cfg->remove_user($user);
1609 sub write_priv_tfa_config
{
1610 my ($filename, $cfg) = @_;
1612 assert_new_tfa_config_available
();
1614 return $cfg->write();
1618 my ($cfg, $user, $path) = @_;
1620 # NOTE: we do not consider pools here.
1621 # NOTE: for privsep tokens, this does not filter roles by those that the
1622 # corresponding user has.
1623 # Use $rpcenv->permission() for any actual permission checks!
1625 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1627 if (pve_verify_tokenid
($user, 1)) {
1628 my $tokenid = $user;
1629 my ($username, $token) = split_tokenid
($tokenid);
1631 my $token_info = $cfg->{users
}->{$username}->{tokens
}->{$token};
1632 return () if !$token_info;
1634 my $user_roles = roles
($cfg, $username, $path);
1636 # return full user privileges
1637 return $user_roles if !$token_info->{privsep
};
1642 foreach my $p (sort keys %{$cfg->{acl
}}) {
1643 my $final = ($path eq $p);
1645 next if !(($p eq '/') || $final || ($path =~ m
|^$p/|));
1647 my $acl = $cfg->{acl
}->{$p};
1649 #print "CHECKACL $path $p\n";
1650 #print "ACL $path = " . Dumper ($acl);
1651 if (my $ri = $acl->{tokens
}->{$user}) {
1653 foreach my $role (keys %$ri) {
1654 my $propagate = $ri->{$role};
1655 if ($final || $propagate) {
1656 #print "APPLY ROLE $p $user $role\n";
1658 $new->{$role} = $propagate;
1662 $roles = $new; # overwrite previous settings
1667 if (my $ri = $acl->{users
}->{$user}) {
1669 foreach my $role (keys %$ri) {
1670 my $propagate = $ri->{$role};
1671 if ($final || $propagate) {
1672 #print "APPLY ROLE $p $user $role\n";
1674 $new->{$role} = $propagate;
1678 $roles = $new; # overwrite previous settings
1679 next; # user privs always override group privs
1684 foreach my $g (keys %{$acl->{groups
}}) {
1685 next if !$cfg->{groups
}->{$g}->{users
}->{$user};
1686 if (my $ri = $acl->{groups
}->{$g}) {
1687 foreach my $role (keys %$ri) {
1688 my $propagate = $ri->{$role};
1689 if ($final || $propagate) {
1690 #print "APPLY ROLE $p \@$g $role\n";
1692 $new->{$role} = $propagate;
1698 $roles = $new; # overwrite previous settings
1703 return { 'NoAccess' => $roles->{NoAccess
} } if defined ($roles->{NoAccess
});
1704 #return () if defined ($roles->{NoAccess});
1706 #print "permission $user $path = " . Dumper ($roles);
1708 #print "roles $user $path = " . join (',', @ra) . "\n";
1713 sub remove_vm_access
{
1715 my $delVMaccessFn = sub {
1716 my $usercfg = cfs_read_file
("user.cfg");
1719 if (my $acl = $usercfg->{acl
}->{"/vms/$vmid"}) {
1720 delete $usercfg->{acl
}->{"/vms/$vmid"};
1723 if (my $pool = $usercfg->{vms
}->{$vmid}) {
1724 if (my $data = $usercfg->{pools
}->{$pool}) {
1725 delete $data->{vms
}->{$vmid};
1726 delete $usercfg->{vms
}->{$vmid};
1730 cfs_write_file
("user.cfg", $usercfg) if $modified;
1733 lock_user_config
($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1736 sub remove_storage_access
{
1739 my $deleteStorageAccessFn = sub {
1740 my $usercfg = cfs_read_file
("user.cfg");
1743 if (my $storage = $usercfg->{acl
}->{"/storage/$storeid"}) {
1744 delete $usercfg->{acl
}->{"/storage/$storeid"};
1747 foreach my $pool (keys %{$usercfg->{pools
}}) {
1748 delete $usercfg->{pools
}->{$pool}->{storage
}->{$storeid};
1751 cfs_write_file
("user.cfg", $usercfg) if $modified;
1754 lock_user_config
($deleteStorageAccessFn,
1755 "access permissions cleanup for storage $storeid failed");
1758 sub add_vm_to_pool
{
1759 my ($vmid, $pool) = @_;
1761 my $addVMtoPoolFn = sub {
1762 my $usercfg = cfs_read_file
("user.cfg");
1763 if (my $data = $usercfg->{pools
}->{$pool}) {
1764 $data->{vms
}->{$vmid} = 1;
1765 $usercfg->{vms
}->{$vmid} = $pool;
1766 cfs_write_file
("user.cfg", $usercfg);
1770 lock_user_config
($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1773 sub remove_vm_from_pool
{
1776 my $delVMfromPoolFn = sub {
1777 my $usercfg = cfs_read_file
("user.cfg");
1778 if (my $pool = $usercfg->{vms
}->{$vmid}) {
1779 if (my $data = $usercfg->{pools
}->{$pool}) {
1780 delete $data->{vms
}->{$vmid};
1781 delete $usercfg->{vms
}->{$vmid};
1782 cfs_write_file
("user.cfg", $usercfg);
1787 lock_user_config
($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1790 my $USER_CONTROLLED_TFA_TYPES = {
1795 sub assert_new_tfa_config_available
() {
1796 PVE
::Cluster
::cfs_update
();
1797 my $version_info = PVE
::Cluster
::get_node_kv
('version-info');
1798 die "cannot update tfa config, please make sure all cluster nodes are up to date\n"
1800 my $members = PVE
::Cluster
::get_members
() or return; # get_members returns undef on no cluster
1802 foreach my $node (keys $members->%*) {
1803 my $info = $version_info->{$node};
1805 $old .= " cluster node '$node' is too old, did not broadcast its version info\n";
1808 $info = from_json
($info);
1809 my $ver = $info->{version
};
1810 if ($ver !~ /^(\d+\.\d+)-(\d+)/) {
1811 $old .= " cluster node '$node' provided an invalid version string: '$ver'\n";
1814 my ($maj, $rel) = ($1, $2);
1815 if (!($maj > 7.0 || ($maj == 7.0 && $rel >= 15))) {
1816 $old .= " cluster node '$node' is too old ($ver < 7.0-15)\n";
1820 die "cannot update tfa config, following nodes are not up to date:\n$old" if length($old);
1823 sub user_remove_tfa
: prototype($) {
1826 assert_new_tfa_config_available
();
1828 my $tfa_cfg = cfs_read_file
('priv/tfa.cfg');
1829 $tfa_cfg->remove_user($userid);
1830 cfs_write_file
('priv/tfa.cfg', $tfa_cfg);
1833 my sub add_old_yubico_keys
: prototype($$$) {
1834 my ($userid, $tfa_cfg, $keys) = @_;
1837 foreach my $key (split_list
($keys)) {
1838 my $description = "<old userconfig key $count>";
1840 $tfa_cfg->add_yubico_entry($userid, $description, $key);
1844 my sub normalize_totp_secret
: prototype($) {
1848 # See PVE::OTP::oath_verify_otp:
1849 if ($key =~ /^v2-0x([0-9a-fA-F]+)$/) {
1851 $binkey = pack('H*', $1);
1852 } elsif ($key =~ /^v2-([A-Z2-7=]+)$/) {
1854 $binkey = MIME
::Base32
::decode_rfc3548
($1);
1855 } elsif ($key =~ /^[A-Z2-7=]{16}$/) {
1856 $binkey = MIME
::Base32
::decode_rfc3548
($key);
1857 } elsif ($key =~ /^[A-Fa-f0-9]{40}$/) {
1858 $binkey = pack('H*', $key);
1863 return MIME
::Base32
::encode_rfc3548
($binkey);
1866 my sub add_old_totp_keys
: prototype($$$$) {
1867 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1869 my $issuer = 'Proxmox%20VE';
1870 my $account = uri_escape
("Old key for $userid");
1871 my $digits = $realm_tfa->{digits
} || 6;
1872 my $step = $realm_tfa->{step
} || 30;
1873 my $uri = "otpauth://totp/$issuer:$account?digits=$digits&period=$step&algorithm=SHA1&secret=";
1876 foreach my $key (split_list
($keys)) {
1877 $key = normalize_totp_secret
($key);
1878 # and just skip invalid keys:
1879 next if !defined($key);
1881 my $description = "<old userconfig key $count>";
1883 eval { $tfa_cfg->add_totp_entry($userid, $description, $uri . $key) };
1888 sub add_old_keys_to_realm_tfa
: prototype($$$$) {
1889 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1891 # if there's no realm tfa configured, we don't know what the keys mean, so we just ignore
1893 return if !$realm_tfa;
1895 my $type = $realm_tfa->{type
};
1896 if ($type eq 'oath') {
1897 add_old_totp_keys
($userid, $tfa_cfg, $realm_tfa, $keys);
1898 } elsif ($type eq 'yubico') {
1899 add_old_yubico_keys
($userid, $tfa_cfg, $keys);
1901 # invalid keys, we'll just drop them now...
1905 sub user_get_tfa
: prototype($$$) {
1906 my ($username, $realm, $new_format) = @_;
1908 my $user_cfg = cfs_read_file
('user.cfg');
1909 my $user = $user_cfg->{users
}->{$username}
1910 or die "user '$username' not found\n";
1912 my $keys = $user->{keys};
1914 my $domain_cfg = cfs_read_file
('domains.cfg');
1915 my $realm_cfg = $domain_cfg->{ids
}->{$realm};
1916 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1918 my $realm_tfa = $realm_cfg->{tfa
};
1919 $realm_tfa = PVE
::Auth
::Plugin
::parse_tfa_config
($realm_tfa)
1923 return if !$realm_tfa;
1924 die "missing required 2nd keys\n";
1928 my $tfa_cfg = cfs_read_file
('priv/tfa.cfg');
1929 if (defined($keys) && $keys !~ /^x(?:!.*)$/) {
1930 add_old_keys_to_realm_tfa
($username, $tfa_cfg, $realm_tfa, $keys);
1932 return ($tfa_cfg, $realm_tfa);
1935 # new style config starts with an 'x' and optionally contains a !<type> suffix
1936 if ($keys !~ /^x(?:!.*)?$/) {
1937 # old style config, find the type via the realm
1938 return if !$realm_tfa;
1939 return ($realm_tfa->{type
}, {
1941 config
=> $realm_tfa,
1944 my $tfa_cfg = cfs_read_file
('priv/tfa.cfg');
1945 my $tfa = $tfa_cfg->{users
}->{$username};
1946 return if !$tfa; # should not happen (user.cfg wasn't cleaned up?)
1949 # if the realm has a tfa setting we need to verify the type:
1950 die "auth domain '$realm' and user have mismatching TFA settings\n"
1951 if $realm_tfa && $realm_tfa->{type
} ne $tfa->{type
};
1954 return ($tfa->{type
}, $tfa->{data
});
1958 # bash completion helpers
1960 register_standard_option
('userid-completed',
1961 get_standard_option
('userid', { completion
=> \
&complete_username
}),
1964 sub complete_username
{
1966 my $user_cfg = cfs_read_file
('user.cfg');
1968 return [ keys %{$user_cfg->{users
}} ];
1971 sub complete_group
{
1973 my $user_cfg = cfs_read_file
('user.cfg');
1975 return [ keys %{$user_cfg->{groups
}} ];
1978 sub complete_realm
{
1980 my $domain_cfg = cfs_read_file
('domains.cfg');
1982 return [ keys %{$domain_cfg->{ids
}} ];