1 package PVE
::AccessControl
;
6 use Crypt
::OpenSSL
::Random
;
7 use Crypt
::OpenSSL
::RSA
;
16 use Scalar
::Util
'weaken';
19 use PVE
::Exception
qw(raise_perm_exc raise_param_exc);
22 use PVE
::Tools
qw(run_command lock_file file_get_contents split_list safe_print);
23 use PVE
::Cluster
qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
24 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
28 use PVE
::Auth
::Plugin
;
33 use PVE
::Auth
::OpenId
;
35 # load and initialize all plugins
37 PVE
::Auth
::AD-
>register();
38 PVE
::Auth
::LDAP-
>register();
39 PVE
::Auth
::PVE-
>register();
40 PVE
::Auth
::PAM-
>register();
41 PVE
::Auth
::OpenId-
>register();
42 PVE
::Auth
::Plugin-
>init();
44 # $authdir must be writable by root only!
45 my $confdir = "/etc/pve";
46 my $authdir = "$confdir/priv";
48 my $pve_www_key_fn = "$confdir/pve-www.key";
50 my $pve_auth_key_files = {
51 priv
=> "$authdir/authkey.key",
52 pub
=> "$confdir/authkey.pub",
53 pubold
=> "$confdir/authkey.pub.old",
56 my $pve_auth_key_cache = {};
58 my $ticket_lifetime = 3600 * 2; # 2 hours
59 my $auth_graceperiod = 60 * 5; # 5 minutes
60 my $authkey_lifetime = 3600 * 24; # rotate every 24 hours
62 Crypt
::OpenSSL
::RSA-
>import_random_seed();
64 cfs_register_file
('user.cfg', \
&parse_user_config
, \
&write_user_config
);
65 cfs_register_file
('priv/tfa.cfg', \
&parse_priv_tfa_config
, \
&write_priv_tfa_config
);
68 PVE
::Auth
::Plugin
::verify_username
(@_);
71 sub pve_verify_realm
{
72 PVE
::Auth
::Plugin
::pve_verify_realm
(@_);
75 # Locking both config files together is only ever allowed in one order:
78 # If we permit the other way round, too, we might end up deadlocking!
79 my $user_config_locked;
80 sub lock_user_config
{
81 my ($code, $errmsg) = @_;
84 $user_config_locked = \
$locked;
85 weaken
$user_config_locked; # make this scope guard signal safe...
87 cfs_lock_file
("user.cfg", undef, $code);
88 $user_config_locked = undef;
90 $errmsg ?
die "$errmsg: $err" : die $err;
95 my ($code, $errmsg) = @_;
97 die "tfa config lock cannot be acquired while holding user config lock\n"
98 if ($user_config_locked && $$user_config_locked);
100 my $res = cfs_lock_file
("priv/tfa.cfg", undef, $code);
102 $errmsg ?
die "$errmsg: $err" : die $err;
108 my $cache_read_key = sub {
111 my $path = $pve_auth_key_files->{$type};
113 my $read_key_and_mtime = sub {
114 my $fh = IO
::File-
>new($path, "r");
116 return undef if !defined($fh);
119 my $pem = PVE
::Tools
::safe_read_from
($fh, 0, 0, $path);
124 if ($type eq 'pub' || $type eq 'pubold') {
125 $key = eval { Crypt
::OpenSSL
::RSA-
>new_public_key($pem); };
126 } elsif ($type eq 'priv') {
127 $key = eval { Crypt
::OpenSSL
::RSA-
>new_private_key($pem); };
129 die "Invalid authkey type '$type'\n";
132 return { key
=> $key, mtime
=> $st->mtime };
135 if (!defined($pve_auth_key_cache->{$type})) {
136 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
138 my $st = stat($path);
139 if (!$st || $st->mtime != $pve_auth_key_cache->{$type}->{mtime
}) {
140 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
144 return $pve_auth_key_cache->{$type};
150 my $type = $old ?
'pubold' : 'pub';
152 my $res = $cache_read_key->($type);
153 return undef if !defined($res);
155 return wantarray ?
($res->{key
}, $res->{mtime
}) : $res->{key
};
159 my $res = $cache_read_key->('priv');
161 if (!defined($res) || !check_authkey
(1)) {
163 $res = $cache_read_key->('priv');
166 return wantarray ?
($res->{key
}, $res->{mtime
}) : $res->{key
};
172 # skip check if non-quorate, as rotation is not possible anyway
173 return 1 if !PVE
::Cluster
::check_cfs_quorum
(1);
175 my ($pub_key, $mtime) = get_pubkey
();
177 warn "auth key pair missing, generating new one..\n" if !$quiet;
181 if ($now - $mtime >= $authkey_lifetime) {
182 warn "auth key pair too old, rotating..\n" if !$quiet;;
184 } elsif ($mtime > $now + $auth_graceperiod) {
185 # a nodes RTC had a time set in the future during key generation -> ticket
186 # validity is clamped to 0+5 min grace period until now >= mtime again
187 my (undef, $old_mtime) = get_pubkey
(1);
188 if ($old_mtime && $mtime >= $old_mtime && $mtime - $old_mtime < $ticket_lifetime) {
189 warn "auth key pair generated in the future (key $mtime > host $now),"
190 ." but old key still exists and in valid grace period so avoid automatic"
191 ." fixup. Cluster time not in sync?\n" if !$quiet;
194 warn "auth key pair generated in the future (key $mtime > host $now), rotating..\n" if !$quiet;
197 warn "auth key new enough, skipping rotation\n" if !$quiet;;
204 return if $authkey_lifetime == 0;
206 PVE
::Cluster
::cfs_lock_authkey
(undef, sub {
207 # stat() calls might be answered from the kernel page cache for up to
208 # 1s, so this special dance is needed to avoid a double rotation in
209 # clusters *despite* the cfs_lock context..
211 # drop in-process cache hash
212 $pve_auth_key_cache = {};
213 # force open/close of file to invalidate page cache entry
215 # now re-check with lock held and page cache invalidated so that stat()
216 # does the right thing, and any key updates by other nodes are visible.
217 return if check_authkey
();
219 my $old = get_pubkey
();
220 my $new = Crypt
::OpenSSL
::RSA-
>generate_key(2048);
224 my $pem = $old->get_public_key_x509_string();
225 # mtime is used for caching and ticket age range calculation
226 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pubold
}, $pem);
228 die "Failed to store old auth key: $@\n" if $@;
232 my $pem = $new->get_public_key_x509_string();
233 # mtime is used for caching and ticket age range calculation,
234 # should be close to that of pubold above
235 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pub
}, $pem);
239 warn "Failed to store new auth key - $@\n";
240 warn "Reverting to previous auth key\n";
242 my $pem = $old->get_public_key_x509_string();
243 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pub
}, $pem);
245 die "Failed to restore old auth key: $@\n" if $@;
247 die "Failed to store new auth key - $@\n";
252 my $pem = $new->get_private_key_string();
253 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{priv
}, $pem);
256 warn "Failed to store new auth key - $@\n";
257 warn "Deleting auth key to force regeneration\n";
258 unlink $pve_auth_key_files->{pub
};
259 unlink $pve_auth_key_files->{priv
};
265 PVE
::JSONSchema
::register_standard_option
('tokenid', {
266 description
=> "API token identifier.",
268 format
=> "pve-tokenid",
271 our $token_subid_regex = $PVE::Auth
::Plugin
::realm_regex
;
273 # username@realm username realm tokenid
274 our $token_full_regex = qr/((${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex}))!(${token_subid_regex})/;
276 our $userid_or_token_regex = qr/^$PVE::Auth::Plugin::user_regex\@$PVE::Auth::Plugin::realm_regex(?:!$token_subid_regex)?$/;
279 my ($tokenid, $noerr) = @_;
281 if ($tokenid =~ /^${token_full_regex}$/) {
285 die "'$tokenid' is not a valid token ID - not able to split into user and token parts\n" if !$noerr;
291 my ($username, $tokensubid) = @_;
293 my $joined = "${username}!${tokensubid}";
295 return pve_verify_tokenid
($joined);
298 PVE
::JSONSchema
::register_format
('pve-tokenid', \
&pve_verify_tokenid
);
299 sub pve_verify_tokenid
{
300 my ($tokenid, $noerr) = @_;
302 if ($tokenid =~ /^${token_full_regex}$/) {
303 return wantarray ?
($tokenid, $2, $3, $4) : $tokenid;
306 die "value '$tokenid' does not look like a valid token ID\n" if !$noerr;
312 my $csrf_prevention_secret;
313 my $csrf_prevention_secret_legacy;
314 my $get_csrfr_secret = sub {
315 if (!$csrf_prevention_secret) {
316 my $input = PVE
::Tools
::file_get_contents
($pve_www_key_fn);
317 $csrf_prevention_secret = Digest
::SHA
::hmac_sha256_base64
($input);
318 $csrf_prevention_secret_legacy = Digest
::SHA
::sha1_base64
($input);
320 return $csrf_prevention_secret;
323 sub assemble_csrf_prevention_token
{
326 my $secret = &$get_csrfr_secret();
328 return PVE
::Ticket
::assemble_csrf_prevention_token
($secret, $username);
331 sub verify_csrf_prevention_token
{
332 my ($username, $token, $noerr) = @_;
334 my $secret = $get_csrfr_secret->();
336 # FIXME: remove with PVE 7 and/or refactor all into PVE::Ticket ?
337 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
339 if (length($sig) == 27) {
340 # the legacy secret got populated by above get_csrfr_secret call
341 $secret = $csrf_prevention_secret_legacy;
345 return PVE
::Ticket
::verify_csrf_prevention_token
(
346 $secret, $username, $token, -$auth_graceperiod, $ticket_lifetime, $noerr);
349 my $get_ticket_age_range = sub {
350 my ($now, $mtime, $rotated) = @_;
352 my $key_age = $now - $mtime;
353 $key_age = 0 if $key_age < 0;
355 my $min = -$auth_graceperiod;
356 my $max = $ticket_lifetime;
359 # ticket creation after rotation is not allowed
360 $min = $key_age - $auth_graceperiod;
362 if ($key_age > $authkey_lifetime && $authkey_lifetime > 0) {
363 if (PVE
::Cluster
::check_cfs_quorum
(1)) {
364 # key should have been rotated, clamp range accordingly
365 $min = $key_age - $authkey_lifetime;
367 warn "Cluster not quorate - extending auth key lifetime!\n";
371 $max = $key_age + $auth_graceperiod if $key_age < $ticket_lifetime;
374 return undef if $min > $ticket_lifetime;
378 sub assemble_ticket
: prototype($;$) {
379 my ($data, $aad) = @_;
381 my $rsa_priv = get_privkey
();
383 return PVE
::Ticket
::assemble_rsa_ticket
($rsa_priv, 'PVE', $data, $aad);
386 # Returns the username, "age" and tfa info.
388 # Note that for the new-style outh, tfa info is never set, as it only uses the `/ticket` api call
389 # via the new 'tfa-challenge' parameter, so this part can go with PVE-8.
391 # New-style auth still uses this function, but sets `$tfa_ticket` to true when validating the tfa
393 sub verify_ticket
: prototype($;$$) {
394 my ($ticket, $noerr, $tfa_ticket_aad) = @_;
401 my ($rsa_pub, $rsa_mtime) = get_pubkey
($old);
402 return undef if !$rsa_pub;
404 my ($min, $max) = $get_ticket_age_range->($now, $rsa_mtime, $old);
405 return undef if !defined($min);
407 return PVE
::Ticket
::verify_rsa_ticket
(
408 $rsa_pub, 'PVE', $ticket, $tfa_ticket_aad, $min, $max, 1);
411 my ($data, $age) = $check->();
413 # check with old, rotated key if current key failed
414 ($data, $age) = $check->(1) if !defined($data);
416 my $auth_failure = sub {
420 # raise error via undef ticket
421 PVE
::Ticket
::verify_rsa_ticket
(undef, 'PVE');
425 if (!defined($data)) {
426 return $auth_failure->();
429 if ($tfa_ticket_aad) {
430 # We're validating a ticket-call's 'tfa-challenge' parameter, so just return its data.
431 if ($data =~ /^!tfa!(.*)$/) {
437 my ($username, $tfa_info);
438 if ($data =~ /^!tfa!(.*)$/) {
439 # PBS style half-authenticated ticket, contains a json string form of a `TfaChallenge`
441 # This type of ticket does not contain the user name.
442 return { type
=> 'new', data
=> $1 };
444 if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
445 # Ticket for u2f-users:
446 ($username, my $challenge) = ($1, $2);
447 if ($challenge eq 'verified') {
448 # u2f challenge was completed
450 } elsif (!wantarray) {
451 # The caller is not aware there could be an ongoing challenge,
452 # so we treat this ticket as invalid:
453 return $auth_failure->();
457 challenge
=> $challenge,
459 } elsif ($data =~ /^tfa!(.*)$/) {
460 # TOTP and Yubico don't require a challenge so this is the generic
461 # 'missing 2nd factor ticket'
463 $tfa_info = { type
=> 'tfa' };
465 # Regular ticket (full access)
469 return undef if !PVE
::Auth
::Plugin
::verify_username
($username, $noerr);
471 return wantarray ?
($username, $age, $tfa_info) : $username;
475 my ($api_token) = @_;
477 die "no API token specified\n" if !$api_token;
479 my ($tokenid, $value);
480 if ($api_token =~ /^(.*)=(.*)$/) {
484 die "no tokenid specified\n";
487 my ($username, $token) = split_tokenid
($tokenid);
489 my $usercfg = cfs_read_file
('user.cfg');
490 check_user_enabled
($usercfg, $username);
491 check_token_exist
($usercfg, $username, $token);
493 my $user = $usercfg->{users
}->{$username};
494 my $token_info = $user->{tokens
}->{$token};
497 die "token '$token' access expired\n" if $token_info->{expire
} && ($token_info->{expire
} < $ctime);
499 die "invalid token value!\n" if !PVE
::Cluster
::verify_token
($tokenid, $value);
501 return wantarray ?
($tokenid) : $tokenid;
504 my $assemble_short_lived_ticket = sub {
505 my ($prefix, $username, $path) = @_;
507 my $rsa_priv = get_privkey
();
509 $path = normalize_path
($path);
511 die "invalid ticket path\n" if !defined($path);
513 my $secret_data = "$username:$path";
515 return PVE
::Ticket
::assemble_rsa_ticket
(
516 $rsa_priv, $prefix, undef, $secret_data);
519 my $verify_short_lived_ticket = sub {
520 my ($ticket, $prefix, $username, $path, $noerr) = @_;
522 $path = normalize_path
($path);
524 die "invalid ticket path\n" if !defined($path);
526 my $secret_data = "$username:$path";
528 my ($rsa_pub, $rsa_mtime) = get_pubkey
();
529 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime && $authkey_lifetime > 0)) {
533 # raise error via undef ticket
534 PVE
::Ticket
::verify_rsa_ticket
($rsa_pub, $prefix);
538 return PVE
::Ticket
::verify_rsa_ticket
(
539 $rsa_pub, $prefix, $ticket, $secret_data, -20, 40, $noerr);
543 # - they do not contain the username in plain text
544 # - they are restricted to a specific resource path (example: '/vms/100')
545 sub assemble_vnc_ticket
{
546 my ($username, $path) = @_;
548 return $assemble_short_lived_ticket->('PVEVNC', $username, $path);
551 sub verify_vnc_ticket
{
552 my ($ticket, $username, $path, $noerr) = @_;
554 return $verify_short_lived_ticket->($ticket, 'PVEVNC', $username, $path, $noerr);
558 # - they do not contain the username in plain text
559 # - they are restricted to a specific resource path (example: '/vms/100', '/socket/run/qemu-server/123.storage')
560 sub assemble_tunnel_ticket
{
561 my ($username, $path) = @_;
563 return $assemble_short_lived_ticket->('PVETUNNEL', $username, $path);
566 sub verify_tunnel_ticket
{
567 my ($ticket, $username, $path, $noerr) = @_;
569 return $verify_short_lived_ticket->($ticket, 'PVETUNNEL', $username, $path, $noerr);
572 sub assemble_spice_ticket
{
573 my ($username, $vmid, $node) = @_;
575 my $secret = &$get_csrfr_secret();
577 return PVE
::Ticket
::assemble_spice_ticket
(
578 $secret, $username, $vmid, $node);
581 sub verify_spice_connect_url
{
582 my ($connect_str) = @_;
584 my $secret = &$get_csrfr_secret();
586 return PVE
::Ticket
::verify_spice_connect_url
($secret, $connect_str);
589 sub read_x509_subject_spice
{
593 my $bio = Net
::SSLeay
::BIO_new_file
($filename, 'r');
594 die "Could not open $filename using OpenSSL\n"
597 my $x509 = Net
::SSLeay
::PEM_read_bio_X509
($bio);
598 Net
::SSLeay
::BIO_free
($bio);
600 die "Could not parse X509 certificate in $filename\n"
603 my $nameobj = Net
::SSLeay
::X509_get_subject_name
($x509);
604 my $subject = Net
::SSLeay
::X509_NAME_oneline
($nameobj);
605 Net
::SSLeay
::X509_free
($x509);
607 # remote-viewer wants comma as separator (not '/')
609 $subject =~ s!/(\w+=)!,$1!g;
614 # helper to generate SPICE remote-viewer configuration
615 sub remote_viewer_config
{
616 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
619 my $host = `hostname -f` || PVE
::INotify
::nodename
();
624 my ($ticket, $proxyticket) = assemble_spice_ticket
($authuser, $vmid, $node);
626 my $filename = "/etc/pve/local/pve-ssl.pem";
627 my $subject = read_x509_subject_spice
($filename);
629 my $cacert = PVE
::Tools
::file_get_contents
("/etc/pve/pve-root-ca.pem", 8192);
630 $cacert =~ s/\n/\\n/g;
632 $proxy = "[$proxy]" if Net
::IP
::ip_is_ipv6
($proxy);
634 'secure-attention' => "Ctrl+Alt+Ins",
635 'toggle-fullscreen' => "Shift+F11",
636 'release-cursor' => "Ctrl+Alt+R",
639 host
=> $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
640 proxy
=> "http://$proxy:3128",
642 'host-subject' => $subject,
645 'delete-this-file' => 1,
648 return ($ticket, $proxyticket, $config);
651 sub check_user_exist
{
652 my ($usercfg, $username, $noerr) = @_;
654 $username = PVE
::Auth
::Plugin
::verify_username
($username, $noerr);
655 return undef if !$username;
657 return $usercfg->{users
}->{$username} if $usercfg && $usercfg->{users
}->{$username};
659 die "no such user ('$username')\n" if !$noerr;
664 sub check_user_enabled
{
665 my ($usercfg, $username, $noerr) = @_;
667 my $data = check_user_exist
($usercfg, $username, $noerr);
668 return undef if !$data;
670 if (!$data->{enable
}) {
671 die "user '$username' is disabled\n" if !$noerr;
676 my $expire = $usercfg->{users
}->{$username}->{expire
};
678 if ($expire && $expire < $ctime) {
679 die "user '$username' access expired\n" if !$noerr;
683 return 1; # enabled and not expired
686 sub check_token_exist
{
687 my ($usercfg, $username, $tokenid, $noerr) = @_;
689 my $user = check_user_exist
($usercfg, $username, $noerr);
690 return undef if !$user;
692 return $user->{tokens
}->{$tokenid}
693 if defined($user->{tokens
}) && $user->{tokens
}->{$tokenid};
695 die "no such token '$tokenid' for user '$username'\n" if !$noerr;
701 sub verify_one_time_pw
{
702 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
704 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
706 # fixme: proxy support?
709 if ($type eq 'yubico') {
710 PVE
::OTP
::yubico_verify_otp
($otp, $keys, $tfa_cfg->{url
},
711 $tfa_cfg->{id
}, $tfa_cfg->{key
}, $proxy);
712 } elsif ($type eq 'oath') {
713 PVE
::OTP
::oath_verify_otp
($otp, $keys, $tfa_cfg->{step
}, $tfa_cfg->{digits
});
715 die "unknown tfa type '$type'\n";
719 # password should be utf8 encoded
720 # Note: some plugins delay/sleep if auth fails
721 sub authenticate_user
: prototype($$$;$) {
722 my ($username, $password, $otp, $tfa_challenge) = @_;
724 die "no username specified\n" if !$username;
728 ($username, $ruid, $realm) = PVE
::Auth
::Plugin
::verify_username
($username);
730 my $usercfg = cfs_read_file
('user.cfg');
732 check_user_enabled
($usercfg, $username);
734 my $domain_cfg = cfs_read_file
('domains.cfg');
736 my $cfg = $domain_cfg->{ids
}->{$realm};
737 die "auth domain '$realm' does not exist\n" if !$cfg;
738 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
740 if ($tfa_challenge) {
741 # This is the 2nd factor, use the password for the OTP response.
742 my $tfa_challenge = authenticate_2nd_new
($username, $realm, $password, $tfa_challenge);
743 return wantarray ?
($username, $tfa_challenge) : $username;
746 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
748 # This is the first factor with an optional immediate 2nd factor for TOTP:
749 $tfa_challenge = authenticate_2nd_new
($username, $realm, $otp, undef);
750 return wantarray ?
($username, $tfa_challenge) : $username;
753 sub authenticate_2nd_new_do
: prototype($$$$) {
754 my ($username, $realm, $tfa_response, $tfa_challenge) = @_;
755 my ($tfa_cfg, $realm_tfa) = user_get_tfa
($username, $realm);
757 # FIXME: `$tfa_cfg` is now usually never undef - use cheap check for
758 # whether the user has *any* entries here instead whe it is available in
760 if (!defined($tfa_cfg)) {
764 my $realm_type = $realm_tfa && $realm_tfa->{type
};
765 # verify realm type unless using recovery keys:
766 if (defined($realm_type)) {
767 $realm_type = 'totp' if $realm_type eq 'oath'; # we used to call it that
768 if ($realm_type eq 'yubico') {
769 # Yubico auth will not be supported in rust for now...
770 if (!defined($tfa_challenge)) {
771 my $challenge = { yubico
=> JSON
::true
};
772 # Even with yubico auth we do allow recovery keys to be used:
773 if (my $recovery = $tfa_cfg->recovery_state($username)) {
774 $challenge->{recovery
} = $recovery;
776 return to_json
($challenge);
779 if ($tfa_response =~ /^yubico:(.*)$/) {
781 # Defer to after unlocking the TFA config:
783 authenticate_yubico_new
(
784 $tfa_cfg, $username, $realm_tfa, $tfa_challenge, $tfa_response,
791 if (defined($tfa_response)) {
792 if ($tfa_response !~ /^([^:]+):/) {
793 die "bad otp response\n";
798 die "realm requires $realm_type authentication\n"
799 if $response_type && $response_type ne 'recovery' && $response_type ne $realm_type;
802 configure_u2f_and_wa
($tfa_cfg);
804 my ($result, $tfa_done);
805 if (defined($tfa_challenge)) {
807 $tfa_challenge = verify_ticket
($tfa_challenge, 0, $username);
808 $result = $tfa_cfg->authentication_verify2($username, $tfa_challenge, $tfa_response);
809 $tfa_challenge = undef;
811 $tfa_challenge = $tfa_cfg->authentication_challenge($username);
813 die "missing required 2nd keys\n"
814 if $realm_tfa && !defined($tfa_challenge);
816 if (defined($tfa_response)) {
817 if (defined($tfa_challenge)) {
819 $result = $tfa_cfg->authentication_verify2($username, $tfa_challenge, $tfa_response);
821 die "no such challenge\n";
828 # authentication_verify2 somehow returned undef - should be unreachable
829 die "2nd factor failed\n";
832 if ($result->{'needs-saving'}) {
833 cfs_write_file
('priv/tfa.cfg', $tfa_cfg);
835 if ($result->{'totp-limit-reached'}) {
836 # FIXME: send mail to the user (or admin/root if no email configured)
837 die "failed 2nd factor: TOTP limit reached, locked\n";
839 if ($result->{'tfa-limit-reached'}) {
840 # FIXME: send mail to the user (or admin/root if no email configured)
841 die "failed 1nd factor: TFA limit reached, user locked out\n";
843 if (!$result->{result
}) {
844 die "failed 2nd factor\n";
848 return $tfa_challenge;
851 # Returns a tfa challenge or undef.
852 sub authenticate_2nd_new
: prototype($$$$) {
853 my ($username, $realm, $tfa_response, $tfa_challenge) = @_;
857 if (defined($tfa_response) && $tfa_response =~ m/^recovery:/) {
858 $result = lock_tfa_config
(sub {
859 authenticate_2nd_new_do
($username, $realm, $tfa_response, $tfa_challenge);
862 $result = authenticate_2nd_new_do
($username, $realm, $tfa_response, $tfa_challenge);
865 # Yubico auth returns the authentication sub:
866 if (ref($result) eq 'CODE') {
867 $result = $result->();
873 sub authenticate_yubico_new
: prototype($$$) {
874 my ($tfa_cfg, $username, $realm, $tfa_challenge, $otp) = @_;
876 $tfa_challenge = verify_ticket
($tfa_challenge, 0, $username);
877 $tfa_challenge = from_json
($tfa_challenge);
879 if (!$tfa_challenge->{yubico
}) {
880 die "no such challenge\n";
883 my $keys = $tfa_cfg->get_yubico_keys($username);
884 die "no keys configured\n" if !defined($keys) || !length($keys);
886 authenticate_yubico_do
($otp, $keys, $realm);
888 # return `undef` to clear the tfa challenge.
892 sub authenticate_yubico_do
: prototype($$$) {
893 my ($value, $keys, $realm) = @_;
895 # fixme: proxy support?
898 PVE
::OTP
::yubico_verify_otp
($value, $keys, $realm->{url
}, $realm->{id
}, $realm->{key
}, $proxy);
901 sub configure_u2f_and_wa
: prototype($) {
905 my $get_origin = sub {
906 return $rpc_origin if defined($rpc_origin);
907 my $rpcenv = PVE
::RPCEnvironment
::get
();
908 if (my $origin = $rpcenv->get_request_host(1)) {
909 $rpc_origin = "https://$origin";
912 die "failed to figure out origin\n";
915 my $dc = cfs_read_file
('datacenter.cfg');
916 if (my $u2f = $dc->{u2f
}) {
918 $tfa_cfg->set_u2f_config({
919 origin
=> $u2f->{origin
} // $get_origin->(),
920 appid
=> $u2f->{appid
},
923 warn "u2f unavailable, configuration error: $@\n" if $@;
925 if (my $wa = $dc->{webauthn
}) {
926 $wa->{origin
} //= $get_origin->();
927 eval { $tfa_cfg->set_webauthn_config({%$wa}) };
928 warn "webauthn unavailable, configuration error: $@\n" if $@;
932 sub domain_set_password
{
933 my ($realm, $username, $password) = @_;
935 die "no auth domain specified" if !$realm;
937 my $domain_cfg = cfs_read_file
('domains.cfg');
939 my $cfg = $domain_cfg->{ids
}->{$realm};
940 die "auth domain '$realm' does not exist\n" if !$cfg;
941 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
942 $plugin->store_password($cfg, $realm, $username, $password);
945 sub iterate_acl_tree
{
946 my ($path, $node, $code) = @_;
948 $code->($path, $node);
950 $path = '' if $path eq '/'; # avoid leading '//'
952 my $children = $node->{children
};
954 foreach my $child (keys %$children) {
955 iterate_acl_tree
("$path/$child", $children->{$child}, $code);
959 # find ACL node corresponding to normalized $path under $root
960 sub find_acl_tree_node
{
961 my ($root, $path) = @_;
963 my $split_path = [ split("/", $path) ];
970 for my $p (@$split_path) {
973 $node->{children
} = {} if !$node->{children
};
974 $node->{children
}->{$p} = {} if !$node->{children
}->{$p};
976 $node = $node->{children
}->{$p};
983 my ($username, $usercfg, $group) = @_;
985 $usercfg->{users
}->{$username}->{groups
}->{$group} = 1;
986 $usercfg->{groups
}->{$group}->{users
}->{$username} = 1;
989 sub delete_user_group
{
990 my ($username, $usercfg) = @_;
992 foreach my $group (keys %{$usercfg->{groups
}}) {
994 delete ($usercfg->{groups
}->{$group}->{users
}->{$username})
995 if $usercfg->{groups
}->{$group}->{users
}->{$username};
999 sub delete_user_acl
{
1000 my ($username, $usercfg) = @_;
1003 my ($path, $acl_node) = @_;
1005 delete ($acl_node->{users
}->{$username})
1006 if $acl_node->{users
}->{$username};
1009 iterate_acl_tree
("/", $usercfg->{acl_root
}, $code);
1012 sub delete_group_acl
{
1013 my ($group, $usercfg) = @_;
1016 my ($path, $acl_node) = @_;
1018 delete ($acl_node->{groups
}->{$group})
1019 if $acl_node->{groups
}->{$group};
1022 iterate_acl_tree
("/", $usercfg->{acl_root
}, $code);
1025 sub delete_pool_acl
{
1026 my ($pool, $usercfg) = @_;
1028 delete ($usercfg->{acl_root
}->{children
}->{pool
}->{children
}->{$pool});
1031 # we automatically create some predefined roles by splitting privs
1032 # into 3 groups (per category)
1033 # root: only root is allowed to do that
1034 # admin: an administrator can to that
1035 # user: a normal user/customer can to that
1043 'VM.Config.Network',
1045 'VM.Config.Options', # covers all other things
1051 'VM.Snapshot.Rollback',
1054 'VM.Config.CDROM', # change CDROM media
1055 'VM.Config.Cloudinit',
1067 'Sys.Modify', # edit/change node settings
1068 'Sys.Incoming', # incoming storage/guest migrations
1069 'Sys.AccessNetwork', # for, e.g., downloading ISOs from any URL
1083 'Datastore.Allocate',
1084 'Datastore.AllocateTemplate',
1087 'Datastore.AllocateSpace',
1112 'Group.Allocate', # edit/change group settings
1113 'Realm.AllocateUser',
1121 'Pool.Allocate', # create/delete pools
1145 'Permissions.Modify' => 1, # not contained in a group
1148 my $special_roles = {
1149 'NoAccess' => {}, # no privileges
1150 'Administrator' => $valid_privs, # all privileges
1155 for my $cat (keys %$privgroups) {
1156 my $cd = $privgroups->{$cat};
1157 # create map to easily check if a privilege is valid
1158 for my $priv (@{$cd->{root
}}, @{$cd->{admin
}}, @{$cd->{user
}}, @{$cd->{audit
}}) {
1159 $valid_privs->{$priv} = 1;
1161 # create grouped admin roles and PVEAdmin
1162 for my $priv (@{$cd->{admin
}}, @{$cd->{user
}}, @{$cd->{audit
}}) {
1163 $special_roles->{"PVE${cat}Admin"}->{$priv} = 1;
1164 $special_roles->{"PVEAdmin"}->{$priv} = 1;
1166 # create grouped user and audit roles
1167 if (scalar(@{$cd->{user
}})) {
1168 for my $priv (@{$cd->{user
}}, @{$cd->{audit
}}) {
1169 $special_roles->{"PVE${cat}User"}->{$priv} = 1;
1172 for my $priv (@{$cd->{audit
}}) {
1173 $special_roles->{"PVEAuditor"}->{$priv} = 1;
1177 # remove Mapping.Modify from PVEAdmin, only Administrator, root@pam and
1178 # PVEMappingAdmin should be able to use that for now
1179 delete $special_roles->{"PVEAdmin"}->{"Mapping.Modify"};
1181 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
1186 sub create_priv_properties
{
1187 my $properties = {};
1188 foreach my $priv (keys %$valid_privs) {
1189 $properties->{$priv} = {
1197 sub role_is_special
{
1199 return (exists $special_roles->{$role}) ?
1 : 0;
1202 sub add_role_privs
{
1203 my ($role, $usercfg, $privs) = @_;
1207 die "role '$role' does not exist\n" if !$usercfg->{roles
}->{$role};
1209 foreach my $priv (split_list
($privs)) {
1210 if (defined ($valid_privs->{$priv})) {
1211 $usercfg->{roles
}->{$role}->{$priv} = 1;
1213 die "invalid privilege '$priv'\n";
1218 sub lookup_username
{
1219 my ($username, $noerr) = @_;
1221 $username =~ m!^(${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex})$!;
1224 my $domain_cfg = cfs_read_file
("domains.cfg");
1225 my $casesensitive = $domain_cfg->{ids
}->{$realm}->{'case-sensitive'} // 1;
1226 my $usercfg = cfs_read_file
('user.cfg');
1228 if (!$casesensitive) {
1229 my @matches = grep { lc $username eq lc $_ } (keys %{$usercfg->{users
}});
1231 die "ambiguous case insensitive match of username '$username', cannot safely grant access!\n"
1232 if scalar @matches > 1 && !$noerr;
1240 sub normalize_path
{
1243 return undef if !$path;
1249 $path = '/' if !$path;
1251 $path = "/$path" if $path !~ m
|^/|;
1253 return undef if $path !~ m
|^[[:alnum
:]\
.\
-\_\
/]+$|;
1260 return $path =~ m
!^(
1264 |/access/groups
/[[:alnum
:]\
.\
-\_
]+
1266 |/access/realm
/[[:alnum
:]\
.\
-\_
]+
1268 |/nodes/[[:alnum
:]\
.\
-\_
]+
1270 |/pool/[A-Za-z0-9\
.\
-_
]+(?
:/[A-Za-z0-9\
.\
-_
]+){0,2}
1273 |/sdn/controllers
/[[:alnum
:]\_\
-]+
1275 |/sdn/dns
/[[:alnum
:]]+
1277 |/sdn/ipams/[[:alnum
:]]+
1279 |/sdn/zones
/[[:alnum
:]\
.\
-\_
]+
1280 |/sdn/zones
/[[:alnum:]\.\-\_]+/[[:alnum
:]\
.\
-\_
]+
1281 |/sdn/zones
/[[:alnum
:]\
.\
-\_
]+/[[:alnum
:]\
.\
-\_
]+/[1-9][0-9]{0,3}
1283 |/storage/[[:alnum
:]\
.\
-\_
]+
1285 |/vms/[1-9][0-9]{2,}
1287 |/mapping/[[:alnum
:]\
.\
-\_
]+
1288 |/mapping/[[:alnum
:]\
.\
-\_
]+/[[:alnum
:]\
.\
-\_
]+
1292 PVE
::JSONSchema
::register_format
('pve-groupid', \
&verify_groupname
);
1293 sub verify_groupname
{
1294 my ($groupname, $noerr) = @_;
1296 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1298 die "group name '$groupname' contains invalid characters\n" if !$noerr;
1306 PVE
::JSONSchema
::register_format
('pve-roleid', \
&verify_rolename
);
1307 sub verify_rolename
{
1308 my ($rolename, $noerr) = @_;
1310 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
1312 die "role name '$rolename' contains invalid characters\n" if !$noerr;
1320 PVE
::JSONSchema
::register_format
('pve-poolid', \
&verify_poolname
);
1321 sub verify_poolname
{
1322 my ($poolname, $noerr) = @_;
1324 if (split("/", $poolname) > 3) {
1325 die "pool name '$poolname' nested too deeply (max levels = 3)\n" if !$noerr;
1330 # also adapt check_path above if changed!
1331 if ($poolname !~ m!^[A-Za-z0-9\.\-_]+(?:/[A-Za-z0-9\.\-_]+){0,2}$!) {
1332 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
1340 PVE
::JSONSchema
::register_format
('pve-priv', \
&verify_privname
);
1341 sub verify_privname
{
1342 my ($priv, $noerr) = @_;
1344 if (!$valid_privs->{$priv}) {
1345 die "invalid privilege '$priv'\n" if !$noerr;
1353 sub userconfig_force_defaults
{
1356 foreach my $r (keys %$special_roles) {
1357 $cfg->{roles
}->{$r} = $special_roles->{$r};
1360 # add root user if not exists
1361 if (!$cfg->{users
}->{'root@pam'}) {
1362 $cfg->{users
}->{'root@pam'}->{enable
} = 1;
1365 # add (empty) ACL tree root node
1366 if (!$cfg->{acl_root
}) {
1367 $cfg->{acl_root
} = {};
1371 sub parse_user_config
{
1372 my ($filename, $raw) = @_;
1376 userconfig_force_defaults
($cfg);
1378 $raw = '' if !defined($raw);
1379 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1383 foreach my $d (split (/:/, $line)) {
1389 my $et = shift @data;
1391 if ($et eq 'user') {
1392 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
1394 my (undef, undef, $realm) = PVE
::Auth
::Plugin
::verify_username
($user, 1);
1396 warn "user config - ignore user '$user' - invalid user name\n";
1400 $enable = $enable ?
1 : 0;
1402 $expire = 0 if !$expire;
1404 if ($expire !~ m/^\d+$/) {
1405 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
1408 $expire = int($expire);
1410 #if (!verify_groupname ($group, 1)) {
1411 # warn "user config - ignore user '$user' - invalid characters in group name\n";
1415 $cfg->{users
}->{$user} = {
1419 $cfg->{users
}->{$user}->{firstname
} = PVE
::Tools
::decode_text
($firstname) if $firstname;
1420 $cfg->{users
}->{$user}->{lastname
} = PVE
::Tools
::decode_text
($lastname) if $lastname;
1421 $cfg->{users
}->{$user}->{email
} = $email;
1422 $cfg->{users
}->{$user}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1423 $cfg->{users
}->{$user}->{expire
} = $expire;
1424 # keys: allowed yubico key ids or oath secrets (base32 encoded)
1425 $cfg->{users
}->{$user}->{keys} = $keys if $keys;
1427 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
1428 #$cfg->{groups}->{$group}->{$user} = 1;
1430 } elsif ($et eq 'group') {
1431 my ($group, $userlist, $comment) = @data;
1433 if (!verify_groupname
($group, 1)) {
1434 warn "user config - ignore group '$group' - invalid characters in group name\n";
1438 # make sure to add the group (even if there are no members)
1439 $cfg->{groups
}->{$group} = { users
=> {} } if !$cfg->{groups
}->{$group};
1441 $cfg->{groups
}->{$group}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1443 foreach my $user (split_list
($userlist)) {
1445 if (!PVE
::Auth
::Plugin
::verify_username
($user, 1)) {
1446 warn "user config - ignore invalid group member '$user'\n";
1450 if ($cfg->{users
}->{$user}) { # user exists
1451 $cfg->{users
}->{$user}->{groups
}->{$group} = 1;
1453 warn "user config - ignore invalid group member '$user'\n";
1455 $cfg->{groups
}->{$group}->{users
}->{$user} = 1;
1458 } elsif ($et eq 'role') {
1459 my ($role, $privlist) = @data;
1461 if (!verify_rolename
($role, 1)) {
1462 warn "user config - ignore role '$role' - invalid characters in role name\n";
1466 # make sure to add the role (even if there are no privileges)
1467 $cfg->{roles
}->{$role} = {} if !$cfg->{roles
}->{$role};
1469 foreach my $priv (split_list
($privlist)) {
1470 if (defined ($valid_privs->{$priv})) {
1471 $cfg->{roles
}->{$role}->{$priv} = 1;
1473 warn "user config - ignore invalid privilege '$priv'\n";
1477 } elsif ($et eq 'acl') {
1478 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
1480 $propagate = $propagate ?
1 : 0;
1482 if (my $path = normalize_path
($pathtxt)) {
1484 foreach my $role (split_list
($rolelist)) {
1486 if (!verify_rolename
($role, 1)) {
1487 warn "user config - ignore invalid role name '$role' in acl\n";
1491 if (!$cfg->{roles
}->{$role}) {
1492 warn "user config - ignore invalid acl role '$role'\n";
1496 foreach my $ug (split_list
($uglist)) {
1497 my ($group) = $ug =~ m/^@(\S+)$/;
1499 if ($group && verify_groupname
($group, 1)) {
1500 if (!$cfg->{groups
}->{$group}) { # group does not exist
1501 warn "user config - ignore invalid acl group '$group'\n";
1503 $acl_node = find_acl_tree_node
($cfg->{acl_root
}, $path) if !$acl_node;
1504 $acl_node->{groups
}->{$group}->{$role} = $propagate;
1505 } elsif (PVE
::Auth
::Plugin
::verify_username
($ug, 1)) {
1506 if (!$cfg->{users
}->{$ug}) { # user does not exist
1507 warn "user config - ignore invalid acl member '$ug'\n";
1509 $acl_node = find_acl_tree_node
($cfg->{acl_root
}, $path) if !$acl_node;
1510 $acl_node->{users
}->{$ug}->{$role} = $propagate;
1511 } elsif (my ($user, $token) = split_tokenid
($ug, 1)) {
1512 if (check_token_exist
($cfg, $user, $token, 1)) {
1513 $acl_node = find_acl_tree_node
($cfg->{acl_root
}, $path) if !$acl_node;
1514 $acl_node->{tokens
}->{$ug}->{$role} = $propagate;
1516 warn "user config - ignore invalid acl token '$ug'\n";
1519 warn "user config - invalid user/group '$ug' in acl\n";
1524 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1526 } elsif ($et eq 'pool') {
1527 my ($pool, $comment, $vmlist, $storelist) = @data;
1529 if (!verify_poolname
($pool, 1)) {
1530 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1534 # make sure to add the pool (even if there are no members)
1535 $cfg->{pools
}->{$pool} = { vms
=> {}, storage
=> {}, pools
=> {} }
1536 if !$cfg->{pools
}->{$pool};
1538 if ($pool =~ m!/!) {
1540 while ($curr =~ m!^(.+)/[^/]+$!) {
1541 # ensure nested pool info is correctly recorded
1543 $cfg->{pools
}->{$curr}->{parent
} = $parent;
1544 $cfg->{pools
}->{$parent} = { vms
=> {}, storage
=> {}, pools
=> {} }
1545 if !$cfg->{pools
}->{$parent};
1546 $cfg->{pools
}->{$parent}->{pools
}->{$curr} = 1;
1551 $cfg->{pools
}->{$pool}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1553 foreach my $vmid (split_list
($vmlist)) {
1554 if ($vmid !~ m/^\d+$/) {
1555 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1560 if ($cfg->{vms
}->{$vmid}) {
1561 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1565 $cfg->{pools
}->{$pool}->{vms
}->{$vmid} = 1;
1567 # record vmid ==> pool relation
1568 $cfg->{vms
}->{$vmid} = $pool;
1571 foreach my $storeid (split_list
($storelist)) {
1572 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1573 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1576 $cfg->{pools
}->{$pool}->{storage
}->{$storeid} = 1;
1578 } elsif ($et eq 'token') {
1579 my ($tokenid, $expire, $privsep, $comment) = @data;
1581 my ($user, $token) = split_tokenid
($tokenid, 1);
1582 if (!($user && $token)) {
1583 warn "user config - ignore invalid tokenid '$tokenid'\n";
1587 $privsep = $privsep ?
1 : 0;
1589 $expire = 0 if !$expire;
1591 if ($expire !~ m/^\d+$/) {
1592 warn "user config - ignore token '$tokenid' - (illegal characters in expire '$expire')\n";
1595 $expire = int($expire);
1597 if (my $user_cfg = $cfg->{users
}->{$user}) { # user exists
1598 $user_cfg->{tokens
}->{$token} = {} if !$user_cfg->{tokens
}->{$token};
1599 my $token_cfg = $user_cfg->{tokens
}->{$token};
1600 $token_cfg->{privsep
} = $privsep;
1601 $token_cfg->{expire
} = $expire;
1602 $token_cfg->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1604 warn "user config - ignore token '$tokenid' - user does not exist\n";
1607 warn "user config - ignore config line: $line\n";
1611 userconfig_force_defaults
($cfg);
1616 sub write_user_config
{
1617 my ($filename, $cfg) = @_;
1621 foreach my $user (sort keys %{$cfg->{users
}}) {
1622 my $d = $cfg->{users
}->{$user};
1623 my $firstname = $d->{firstname
} ? PVE
::Tools
::encode_text
($d->{firstname
}) : '';
1624 my $lastname = $d->{lastname
} ? PVE
::Tools
::encode_text
($d->{lastname
}) : '';
1625 my $email = $d->{email
} || '';
1626 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1627 my $expire = int($d->{expire
} || 0);
1628 my $enable = $d->{enable
} ?
1 : 0;
1629 my $keys = $d->{keys} ?
$d->{keys} : '';
1630 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1632 my $user_tokens = $d->{tokens
};
1633 foreach my $token (sort keys %$user_tokens) {
1634 my $td = $user_tokens->{$token};
1635 my $full_tokenid = join_tokenid
($user, $token);
1636 my $comment = $td->{comment
} ? PVE
::Tools
::encode_text
($td->{comment
}) : '';
1637 my $expire = int($td->{expire
} || 0);
1638 my $privsep = $td->{privsep
} ?
1 : 0;
1639 $data .= "token:$full_tokenid:$expire:$privsep:$comment:\n";
1645 foreach my $group (sort keys %{$cfg->{groups
}}) {
1646 my $d = $cfg->{groups
}->{$group};
1647 my $list = join (',', sort keys %{$d->{users
}});
1648 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1649 $data .= "group:$group:$list:$comment:\n";
1654 foreach my $pool (sort keys %{$cfg->{pools
}}) {
1655 my $d = $cfg->{pools
}->{$pool};
1656 my $vmlist = join (',', sort keys %{$d->{vms
}});
1657 my $storelist = join (',', sort keys %{$d->{storage
}});
1658 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1659 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1664 foreach my $role (sort keys %{$cfg->{roles
}}) {
1665 next if $special_roles->{$role};
1667 my $d = $cfg->{roles
}->{$role};
1668 my $list = join (',', sort keys %$d);
1669 $data .= "role:$role:$list:\n";
1674 my $collect_rolelist_members = sub {
1675 my ($acl_members, $result, $prefix, $exclude) = @_;
1677 foreach my $member (keys %$acl_members) {
1678 next if $exclude && $member eq $exclude;
1682 foreach my $role (sort keys %{$acl_members->{$member}}) {
1683 my $propagate = $acl_members->{$member}->{$role};
1692 $result->{0}->{$l0}->{"${prefix}${member}"} = 1 if $l0;
1693 $result->{1}->{$l1}->{"${prefix}${member}"} = 1 if $l1;
1697 iterate_acl_tree
("/", $cfg->{acl_root
}, sub {
1698 my ($path, $d) = @_;
1700 my $rolelist_members = {};
1702 $collect_rolelist_members->($d->{'groups'}, $rolelist_members, '@');
1704 # no need to save 'root@pam', it is always 'Administrator'
1705 $collect_rolelist_members->($d->{'users'}, $rolelist_members, '', 'root@pam');
1707 $collect_rolelist_members->($d->{'tokens'}, $rolelist_members, '');
1709 foreach my $propagate (0,1) {
1710 my $filtered = $rolelist_members->{$propagate};
1711 foreach my $rolelist (sort keys %$filtered) {
1712 my $uglist = join (',', sort keys %{$filtered->{$rolelist}});
1713 $data .= "acl:$propagate:$path:$uglist:$rolelist:\n";
1722 # Creates a `PVE::RS::TFA` instance from the raw config data.
1723 # Its contained hash will also support the legacy functionality.
1724 sub parse_priv_tfa_config
{
1725 my ($filename, $raw) = @_;
1727 $raw = '' if !defined($raw);
1728 my $cfg = PVE
::RS
::TFA-
>new($raw);
1730 # Purge invalid users:
1731 foreach my $user ($cfg->users()->@*) {
1732 my (undef, undef, $realm) = PVE
::Auth
::Plugin
::verify_username
($user, 1);
1734 warn "user tfa config - ignore user '$user' - invalid user name\n";
1735 $cfg->remove_user($user);
1742 sub write_priv_tfa_config
{
1743 my ($filename, $cfg) = @_;
1745 return $cfg->write();
1749 my ($cfg, $user, $path) = @_;
1751 # NOTE: we do not consider pools here.
1752 # NOTE: for privsep tokens, this does not filter roles by those that the
1753 # corresponding user has.
1754 # Use $rpcenv->permission() for any actual permission checks!
1756 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1758 if (!defined($path)) {
1759 # this shouldn't happen!
1760 warn "internal error: ACL check called for undefined ACL path!\n";
1764 if (pve_verify_tokenid
($user, 1)) {
1765 my $tokenid = $user;
1766 my ($username, $token) = split_tokenid
($tokenid);
1768 my $token_info = $cfg->{users
}->{$username}->{tokens
}->{$token};
1769 return () if !$token_info;
1771 my $user_roles = roles
($cfg, $username, $path);
1773 # return full user privileges
1774 return $user_roles if !$token_info->{privsep
};
1779 my $split = [ split("/", $path) ];
1784 my $acl = $cfg->{acl_root
};
1788 my $p = shift @$split;
1789 my $final = !@$split;
1791 $acl = $acl->{children
}->{$p};
1794 #print "CHECKACL $path $p\n";
1795 #print "ACL $path = " . Dumper ($acl);
1796 if (my $ri = $acl->{tokens
}->{$user}) {
1798 foreach my $role (keys %$ri) {
1799 my $propagate = $ri->{$role};
1800 if ($final || $propagate) {
1801 #print "APPLY ROLE $p $user $role\n";
1803 $new->{$role} = $propagate;
1807 $roles = $new; # overwrite previous settings
1812 if (my $ri = $acl->{users
}->{$user}) {
1814 foreach my $role (keys %$ri) {
1815 my $propagate = $ri->{$role};
1816 if ($final || $propagate) {
1817 #print "APPLY ROLE $p $user $role\n";
1819 $new->{$role} = $propagate;
1823 $roles = $new; # overwrite previous settings
1824 next; # user privs always override group privs
1829 foreach my $g (keys %{$acl->{groups
}}) {
1830 next if !$cfg->{groups
}->{$g}->{users
}->{$user};
1831 if (my $ri = $acl->{groups
}->{$g}) {
1832 foreach my $role (keys %$ri) {
1833 my $propagate = $ri->{$role};
1834 if ($final || $propagate) {
1835 #print "APPLY ROLE $p \@$g $role\n";
1837 $new->{$role} = $propagate;
1843 $roles = $new; # overwrite previous settings
1848 return { 'NoAccess' => $roles->{NoAccess
} } if defined ($roles->{NoAccess
});
1849 #return () if defined ($roles->{NoAccess});
1851 #print "permission $user $path = " . Dumper ($roles);
1853 #print "roles $user $path = " . join (',', @ra) . "\n";
1858 sub remove_vm_access
{
1860 my $delVMaccessFn = sub {
1861 my $usercfg = cfs_read_file
("user.cfg");
1864 if (my $acl = $usercfg->{acl_root
}->{children
}->{vms
}->{children
}->{$vmid}) {
1865 delete $usercfg->{acl_root
}->{children
}->{vms
}->{children
}->{$vmid};
1868 if (my $pool = $usercfg->{vms
}->{$vmid}) {
1869 if (my $data = $usercfg->{pools
}->{$pool}) {
1870 delete $data->{vms
}->{$vmid};
1871 delete $usercfg->{vms
}->{$vmid};
1875 cfs_write_file
("user.cfg", $usercfg) if $modified;
1878 lock_user_config
($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1881 sub remove_storage_access
{
1884 my $deleteStorageAccessFn = sub {
1885 my $usercfg = cfs_read_file
("user.cfg");
1888 if (my $acl = $usercfg->{acl_root
}->{children
}->{storage
}->{children
}->{$storeid}) {
1889 delete $usercfg->{acl_root
}->{children
}->{storage
}->{children
}->{$storeid};
1892 foreach my $pool (keys %{$usercfg->{pools
}}) {
1893 delete $usercfg->{pools
}->{$pool}->{storage
}->{$storeid};
1896 cfs_write_file
("user.cfg", $usercfg) if $modified;
1899 lock_user_config
($deleteStorageAccessFn,
1900 "access permissions cleanup for storage $storeid failed");
1903 sub add_vm_to_pool
{
1904 my ($vmid, $pool) = @_;
1906 my $addVMtoPoolFn = sub {
1907 my $usercfg = cfs_read_file
("user.cfg");
1908 if (my $data = $usercfg->{pools
}->{$pool}) {
1909 $data->{vms
}->{$vmid} = 1;
1910 $usercfg->{vms
}->{$vmid} = $pool;
1911 cfs_write_file
("user.cfg", $usercfg);
1915 lock_user_config
($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1918 sub remove_vm_from_pool
{
1921 my $delVMfromPoolFn = sub {
1922 my $usercfg = cfs_read_file
("user.cfg");
1923 if (my $pool = $usercfg->{vms
}->{$vmid}) {
1924 if (my $data = $usercfg->{pools
}->{$pool}) {
1925 delete $data->{vms
}->{$vmid};
1926 delete $usercfg->{vms
}->{$vmid};
1927 cfs_write_file
("user.cfg", $usercfg);
1932 lock_user_config
($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1935 my $USER_CONTROLLED_TFA_TYPES = {
1940 sub user_remove_tfa
: prototype($) {
1943 my $tfa_cfg = cfs_read_file
('priv/tfa.cfg');
1944 $tfa_cfg->remove_user($userid);
1945 cfs_write_file
('priv/tfa.cfg', $tfa_cfg);
1948 my sub add_old_yubico_keys
: prototype($$$) {
1949 my ($userid, $tfa_cfg, $keys) = @_;
1952 foreach my $key (split_list
($keys)) {
1953 my $description = "<old userconfig key $count>";
1955 $tfa_cfg->add_yubico_entry($userid, $description, $key);
1959 my sub normalize_totp_secret
: prototype($) {
1963 # See PVE::OTP::oath_verify_otp:
1964 if ($key =~ /^v2-0x([0-9a-fA-F]+)$/) {
1966 $binkey = pack('H*', $1);
1967 } elsif ($key =~ /^v2-([A-Z2-7=]+)$/) {
1969 $binkey = MIME
::Base32
::decode_rfc3548
($1);
1970 } elsif ($key =~ /^[A-Z2-7=]{16}$/) {
1971 $binkey = MIME
::Base32
::decode_rfc3548
($key);
1972 } elsif ($key =~ /^[A-Fa-f0-9]{40}$/) {
1973 $binkey = pack('H*', $key);
1978 return MIME
::Base32
::encode_rfc3548
($binkey);
1981 my sub add_old_totp_keys
: prototype($$$$) {
1982 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1984 my $issuer = 'Proxmox%20VE';
1985 my $account = uri_escape
("Old key for $userid");
1986 my $digits = $realm_tfa->{digits
} || 6;
1987 my $step = $realm_tfa->{step
} || 30;
1988 my $uri = "otpauth://totp/$issuer:$account?digits=$digits&period=$step&algorithm=SHA1&secret=";
1991 foreach my $key (split_list
($keys)) {
1992 $key = normalize_totp_secret
($key);
1993 # and just skip invalid keys:
1994 next if !defined($key);
1996 my $description = "<old userconfig key $count>";
1998 eval { $tfa_cfg->add_totp_entry($userid, $description, $uri . $key) };
2003 sub add_old_keys_to_realm_tfa
: prototype($$$$) {
2004 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
2006 # if there's no realm tfa configured, we don't know what the keys mean, so we just ignore
2008 return if !$realm_tfa;
2010 my $type = $realm_tfa->{type
};
2011 if ($type eq 'oath') {
2012 add_old_totp_keys
($userid, $tfa_cfg, $realm_tfa, $keys);
2013 } elsif ($type eq 'yubico') {
2014 add_old_yubico_keys
($userid, $tfa_cfg, $keys);
2016 # invalid keys, we'll just drop them now...
2020 sub user_get_tfa
: prototype($$$) {
2021 my ($username, $realm) = @_;
2023 my $user_cfg = cfs_read_file
('user.cfg');
2024 my $user = $user_cfg->{users
}->{$username}
2025 or die "user '$username' not found\n";
2027 my $keys = $user->{keys};
2029 my $domain_cfg = cfs_read_file
('domains.cfg');
2030 my $realm_cfg = $domain_cfg->{ids
}->{$realm};
2031 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
2033 my $realm_tfa = $realm_cfg->{tfa
};
2034 $realm_tfa = PVE
::Auth
::Plugin
::parse_tfa_config
($realm_tfa)
2037 my $tfa_cfg = cfs_read_file
('priv/tfa.cfg');
2038 if (defined($keys) && $keys !~ /^x(?:!.*)$/) {
2039 add_old_keys_to_realm_tfa
($username, $tfa_cfg, $realm_tfa, $keys);
2042 return ($tfa_cfg, $realm_tfa);
2045 # bash completion helpers
2047 register_standard_option
('userid-completed',
2048 get_standard_option
('userid', { completion
=> \
&complete_username
}),
2051 sub complete_username
{
2053 my $user_cfg = cfs_read_file
('user.cfg');
2055 return [ keys %{$user_cfg->{users
}} ];
2058 sub complete_group
{
2060 my $user_cfg = cfs_read_file
('user.cfg');
2062 return [ keys %{$user_cfg->{groups
}} ];
2065 sub complete_realm
{
2067 my $domain_cfg = cfs_read_file
('domains.cfg');
2069 return [ keys %{$domain_cfg->{ids
}} ];