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 # stat() calls might be answered from the kernel page cache for up to
207 # 1s, so this special dance is needed to avoid a double rotation in
208 # clusters *despite* the cfs_lock context..
210 # drop in-process cache hash
211 $pve_auth_key_cache = {};
212 # force open/close of file to invalidate page cache entry
214 # now re-check with lock held and page cache invalidated so that stat()
215 # does the right thing, and any key updates by other nodes are visible.
216 return if check_authkey
();
218 my $old = get_pubkey
();
219 my $new = Crypt
::OpenSSL
::RSA-
>generate_key(2048);
223 my $pem = $old->get_public_key_x509_string();
224 # mtime is used for caching and ticket age range calculation
225 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pubold
}, $pem);
227 die "Failed to store old auth key: $@\n" if $@;
231 my $pem = $new->get_public_key_x509_string();
232 # mtime is used for caching and ticket age range calculation,
233 # should be close to that of pubold above
234 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pub
}, $pem);
238 warn "Failed to store new auth key - $@\n";
239 warn "Reverting to previous auth key\n";
241 my $pem = $old->get_public_key_x509_string();
242 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{pub
}, $pem);
244 die "Failed to restore old auth key: $@\n" if $@;
246 die "Failed to store new auth key - $@\n";
251 my $pem = $new->get_private_key_string();
252 PVE
::Tools
::file_set_contents
($pve_auth_key_files->{priv
}, $pem);
255 warn "Failed to store new auth key - $@\n";
256 warn "Deleting auth key to force regeneration\n";
257 unlink $pve_auth_key_files->{pub
};
258 unlink $pve_auth_key_files->{priv
};
264 PVE
::JSONSchema
::register_standard_option
('tokenid', {
265 description
=> "API token identifier.",
267 format
=> "pve-tokenid",
270 our $token_subid_regex = $PVE::Auth
::Plugin
::realm_regex
;
272 # username@realm username realm tokenid
273 our $token_full_regex = qr/((${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex}))!(${token_subid_regex})/;
275 our $userid_or_token_regex = qr/^$PVE::Auth::Plugin::user_regex\@$PVE::Auth::Plugin::realm_regex(?:!$token_subid_regex)?$/;
278 my ($tokenid, $noerr) = @_;
280 if ($tokenid =~ /^${token_full_regex}$/) {
284 die "'$tokenid' is not a valid token ID - not able to split into user and token parts\n" if !$noerr;
290 my ($username, $tokensubid) = @_;
292 my $joined = "${username}!${tokensubid}";
294 return pve_verify_tokenid
($joined);
297 PVE
::JSONSchema
::register_format
('pve-tokenid', \
&pve_verify_tokenid
);
298 sub pve_verify_tokenid
{
299 my ($tokenid, $noerr) = @_;
301 if ($tokenid =~ /^${token_full_regex}$/) {
302 return wantarray ?
($tokenid, $2, $3, $4) : $tokenid;
305 die "value '$tokenid' does not look like a valid token ID\n" if !$noerr;
311 my $csrf_prevention_secret;
312 my $csrf_prevention_secret_legacy;
313 my $get_csrfr_secret = sub {
314 if (!$csrf_prevention_secret) {
315 my $input = PVE
::Tools
::file_get_contents
($pve_www_key_fn);
316 $csrf_prevention_secret = Digest
::SHA
::hmac_sha256_base64
($input);
317 $csrf_prevention_secret_legacy = Digest
::SHA
::sha1_base64
($input);
319 return $csrf_prevention_secret;
322 sub assemble_csrf_prevention_token
{
325 my $secret = &$get_csrfr_secret();
327 return PVE
::Ticket
::assemble_csrf_prevention_token
($secret, $username);
330 sub verify_csrf_prevention_token
{
331 my ($username, $token, $noerr) = @_;
333 my $secret = $get_csrfr_secret->();
335 # FIXME: remove with PVE 7 and/or refactor all into PVE::Ticket ?
336 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
338 if (length($sig) == 27) {
339 # the legacy secret got populated by above get_csrfr_secret call
340 $secret = $csrf_prevention_secret_legacy;
344 return PVE
::Ticket
::verify_csrf_prevention_token
(
345 $secret, $username, $token, -$auth_graceperiod, $ticket_lifetime, $noerr);
348 my $get_ticket_age_range = sub {
349 my ($now, $mtime, $rotated) = @_;
351 my $key_age = $now - $mtime;
352 $key_age = 0 if $key_age < 0;
354 my $min = -$auth_graceperiod;
355 my $max = $ticket_lifetime;
358 # ticket creation after rotation is not allowed
359 $min = $key_age - $auth_graceperiod;
361 if ($key_age > $authkey_lifetime && $authkey_lifetime > 0) {
362 if (PVE
::Cluster
::check_cfs_quorum
(1)) {
363 # key should have been rotated, clamp range accordingly
364 $min = $key_age - $authkey_lifetime;
366 warn "Cluster not quorate - extending auth key lifetime!\n";
370 $max = $key_age + $auth_graceperiod if $key_age < $ticket_lifetime;
373 return undef if $min > $ticket_lifetime;
377 sub assemble_ticket
: prototype($;$) {
378 my ($data, $aad) = @_;
380 my $rsa_priv = get_privkey
();
382 return PVE
::Ticket
::assemble_rsa_ticket
($rsa_priv, 'PVE', $data, $aad);
385 # Returns the username, "age" and tfa info.
387 # Note that for the new-style outh, tfa info is never set, as it only uses the `/ticket` api call
388 # via the new 'tfa-challenge' parameter, so this part can go with PVE-8.
390 # New-style auth still uses this function, but sets `$tfa_ticket` to true when validating the tfa
392 sub verify_ticket
: prototype($;$$) {
393 my ($ticket, $noerr, $tfa_ticket_aad) = @_;
400 my ($rsa_pub, $rsa_mtime) = get_pubkey
($old);
401 return undef if !$rsa_pub;
403 my ($min, $max) = $get_ticket_age_range->($now, $rsa_mtime, $old);
404 return undef if !defined($min);
406 return PVE
::Ticket
::verify_rsa_ticket
(
407 $rsa_pub, 'PVE', $ticket, $tfa_ticket_aad, $min, $max, 1);
410 my ($data, $age) = $check->();
412 # check with old, rotated key if current key failed
413 ($data, $age) = $check->(1) if !defined($data);
415 my $auth_failure = sub {
419 # raise error via undef ticket
420 PVE
::Ticket
::verify_rsa_ticket
(undef, 'PVE');
424 if (!defined($data)) {
425 return $auth_failure->();
428 if ($tfa_ticket_aad) {
429 # We're validating a ticket-call's 'tfa-challenge' parameter, so just return its data.
430 if ($data =~ /^!tfa!(.*)$/) {
436 my ($username, $tfa_info);
437 if ($data =~ /^!tfa!(.*)$/) {
438 # PBS style half-authenticated ticket, contains a json string form of a `TfaChallenge`
440 # This type of ticket does not contain the user name.
441 return { type
=> 'new', data
=> $1 };
443 if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
444 # Ticket for u2f-users:
445 ($username, my $challenge) = ($1, $2);
446 if ($challenge eq 'verified') {
447 # u2f challenge was completed
449 } elsif (!wantarray) {
450 # The caller is not aware there could be an ongoing challenge,
451 # so we treat this ticket as invalid:
452 return $auth_failure->();
456 challenge
=> $challenge,
458 } elsif ($data =~ /^tfa!(.*)$/) {
459 # TOTP and Yubico don't require a challenge so this is the generic
460 # 'missing 2nd factor ticket'
462 $tfa_info = { type
=> 'tfa' };
464 # Regular ticket (full access)
468 return undef if !PVE
::Auth
::Plugin
::verify_username
($username, $noerr);
470 return wantarray ?
($username, $age, $tfa_info) : $username;
474 my ($api_token) = @_;
476 die "no API token specified\n" if !$api_token;
478 my ($tokenid, $value);
479 if ($api_token =~ /^(.*)=(.*)$/) {
483 die "no tokenid specified\n";
486 my ($username, $token) = split_tokenid
($tokenid);
488 my $usercfg = cfs_read_file
('user.cfg');
489 check_user_enabled
($usercfg, $username);
490 check_token_exist
($usercfg, $username, $token);
492 my $user = $usercfg->{users
}->{$username};
493 my $token_info = $user->{tokens
}->{$token};
496 die "token '$token' access expired\n" if $token_info->{expire
} && ($token_info->{expire
} < $ctime);
498 die "invalid token value!\n" if !PVE
::Cluster
::verify_token
($tokenid, $value);
500 return wantarray ?
($tokenid) : $tokenid;
503 my $assemble_short_lived_ticket = sub {
504 my ($prefix, $username, $path) = @_;
506 my $rsa_priv = get_privkey
();
508 $path = normalize_path
($path);
510 die "invalid ticket path\n" if !defined($path);
512 my $secret_data = "$username:$path";
514 return PVE
::Ticket
::assemble_rsa_ticket
(
515 $rsa_priv, $prefix, undef, $secret_data);
518 my $verify_short_lived_ticket = sub {
519 my ($ticket, $prefix, $username, $path, $noerr) = @_;
521 $path = normalize_path
($path);
523 die "invalid ticket path\n" if !defined($path);
525 my $secret_data = "$username:$path";
527 my ($rsa_pub, $rsa_mtime) = get_pubkey
();
528 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime && $authkey_lifetime > 0)) {
532 # raise error via undef ticket
533 PVE
::Ticket
::verify_rsa_ticket
($rsa_pub, $prefix);
537 return PVE
::Ticket
::verify_rsa_ticket
(
538 $rsa_pub, $prefix, $ticket, $secret_data, -20, 40, $noerr);
542 # - they do not contain the username in plain text
543 # - they are restricted to a specific resource path (example: '/vms/100')
544 sub assemble_vnc_ticket
{
545 my ($username, $path) = @_;
547 return $assemble_short_lived_ticket->('PVEVNC', $username, $path);
550 sub verify_vnc_ticket
{
551 my ($ticket, $username, $path, $noerr) = @_;
553 return $verify_short_lived_ticket->($ticket, 'PVEVNC', $username, $path, $noerr);
557 # - they do not contain the username in plain text
558 # - they are restricted to a specific resource path (example: '/vms/100', '/socket/run/qemu-server/123.storage')
559 sub assemble_tunnel_ticket
{
560 my ($username, $path) = @_;
562 return $assemble_short_lived_ticket->('PVETUNNEL', $username, $path);
565 sub verify_tunnel_ticket
{
566 my ($ticket, $username, $path, $noerr) = @_;
568 return $verify_short_lived_ticket->($ticket, 'PVETUNNEL', $username, $path, $noerr);
571 sub assemble_spice_ticket
{
572 my ($username, $vmid, $node) = @_;
574 my $secret = &$get_csrfr_secret();
576 return PVE
::Ticket
::assemble_spice_ticket
(
577 $secret, $username, $vmid, $node);
580 sub verify_spice_connect_url
{
581 my ($connect_str) = @_;
583 my $secret = &$get_csrfr_secret();
585 return PVE
::Ticket
::verify_spice_connect_url
($secret, $connect_str);
588 sub read_x509_subject_spice
{
592 my $bio = Net
::SSLeay
::BIO_new_file
($filename, 'r');
593 die "Could not open $filename using OpenSSL\n"
596 my $x509 = Net
::SSLeay
::PEM_read_bio_X509
($bio);
597 Net
::SSLeay
::BIO_free
($bio);
599 die "Could not parse X509 certificate in $filename\n"
602 my $nameobj = Net
::SSLeay
::X509_get_subject_name
($x509);
603 my $subject = Net
::SSLeay
::X509_NAME_oneline
($nameobj);
604 Net
::SSLeay
::X509_free
($x509);
606 # remote-viewer wants comma as separator (not '/')
608 $subject =~ s!/(\w+=)!,$1!g;
613 # helper to generate SPICE remote-viewer configuration
614 sub remote_viewer_config
{
615 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
618 my $host = `hostname -f` || PVE
::INotify
::nodename
();
623 my ($ticket, $proxyticket) = assemble_spice_ticket
($authuser, $vmid, $node);
625 my $filename = "/etc/pve/local/pve-ssl.pem";
626 my $subject = read_x509_subject_spice
($filename);
628 my $cacert = PVE
::Tools
::file_get_contents
("/etc/pve/pve-root-ca.pem", 8192);
629 $cacert =~ s/\n/\\n/g;
631 $proxy = "[$proxy]" if Net
::IP
::ip_is_ipv6
($proxy);
633 'secure-attention' => "Ctrl+Alt+Ins",
634 'toggle-fullscreen' => "Shift+F11",
635 'release-cursor' => "Ctrl+Alt+R",
638 host
=> $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
639 proxy
=> "http://$proxy:3128",
641 'host-subject' => $subject,
644 'delete-this-file' => 1,
647 return ($ticket, $proxyticket, $config);
650 sub check_user_exist
{
651 my ($usercfg, $username, $noerr) = @_;
653 $username = PVE
::Auth
::Plugin
::verify_username
($username, $noerr);
654 return undef if !$username;
656 return $usercfg->{users
}->{$username} if $usercfg && $usercfg->{users
}->{$username};
658 die "no such user ('$username')\n" if !$noerr;
663 sub check_user_enabled
{
664 my ($usercfg, $username, $noerr) = @_;
666 my $data = check_user_exist
($usercfg, $username, $noerr);
667 return undef if !$data;
669 if (!$data->{enable
}) {
670 die "user '$username' is disabled\n" if !$noerr;
675 my $expire = $usercfg->{users
}->{$username}->{expire
};
677 if ($expire && $expire < $ctime) {
678 die "user '$username' access expired\n" if !$noerr;
682 return 1; # enabled and not expired
685 sub check_token_exist
{
686 my ($usercfg, $username, $tokenid, $noerr) = @_;
688 my $user = check_user_exist
($usercfg, $username, $noerr);
689 return undef if !$user;
691 return $user->{tokens
}->{$tokenid}
692 if defined($user->{tokens
}) && $user->{tokens
}->{$tokenid};
694 die "no such token '$tokenid' for user '$username'\n" if !$noerr;
700 sub verify_one_time_pw
{
701 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
703 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
705 # fixme: proxy support?
708 if ($type eq 'yubico') {
709 PVE
::OTP
::yubico_verify_otp
($otp, $keys, $tfa_cfg->{url
},
710 $tfa_cfg->{id
}, $tfa_cfg->{key
}, $proxy);
711 } elsif ($type eq 'oath') {
712 PVE
::OTP
::oath_verify_otp
($otp, $keys, $tfa_cfg->{step
}, $tfa_cfg->{digits
});
714 die "unknown tfa type '$type'\n";
718 # password should be utf8 encoded
719 # Note: some plugins delay/sleep if auth fails
720 sub authenticate_user
: prototype($$$;$) {
721 my ($username, $password, $otp, $tfa_challenge) = @_;
723 die "no username specified\n" if !$username;
727 ($username, $ruid, $realm) = PVE
::Auth
::Plugin
::verify_username
($username);
729 my $usercfg = cfs_read_file
('user.cfg');
731 check_user_enabled
($usercfg, $username);
733 my $domain_cfg = cfs_read_file
('domains.cfg');
735 my $cfg = $domain_cfg->{ids
}->{$realm};
736 die "auth domain '$realm' does not exist\n" if !$cfg;
737 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
739 if ($tfa_challenge) {
740 # This is the 2nd factor, use the password for the OTP response.
741 my $tfa_challenge = authenticate_2nd_new
($username, $realm, $password, $tfa_challenge);
742 return wantarray ?
($username, $tfa_challenge) : $username;
745 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
747 # This is the first factor with an optional immediate 2nd factor for TOTP:
748 $tfa_challenge = authenticate_2nd_new
($username, $realm, $otp, undef);
749 return wantarray ?
($username, $tfa_challenge) : $username;
752 sub authenticate_2nd_new_do
: prototype($$$$) {
753 my ($username, $realm, $tfa_response, $tfa_challenge) = @_;
754 my ($tfa_cfg, $realm_tfa) = user_get_tfa
($username, $realm);
756 # FIXME: `$tfa_cfg` is now usually never undef - use cheap check for
757 # whether the user has *any* entries here instead whe it is available in
759 if (!defined($tfa_cfg)) {
763 my $realm_type = $realm_tfa && $realm_tfa->{type
};
764 # verify realm type unless using recovery keys:
765 if (defined($realm_type)) {
766 $realm_type = 'totp' if $realm_type eq 'oath'; # we used to call it that
767 if ($realm_type eq 'yubico') {
768 # Yubico auth will not be supported in rust for now...
769 if (!defined($tfa_challenge)) {
770 my $challenge = { yubico
=> JSON
::true
};
771 # Even with yubico auth we do allow recovery keys to be used:
772 if (my $recovery = $tfa_cfg->recovery_state($username)) {
773 $challenge->{recovery
} = $recovery;
775 return to_json
($challenge);
778 if ($tfa_response =~ /^yubico:(.*)$/) {
780 # Defer to after unlocking the TFA config:
782 authenticate_yubico_new
(
783 $tfa_cfg, $username, $realm_tfa, $tfa_challenge, $tfa_response,
790 if (defined($tfa_response)) {
791 if ($tfa_response !~ /^([^:]+):/) {
792 die "bad otp response\n";
797 die "realm requires $realm_type authentication\n"
798 if $response_type && $response_type ne 'recovery' && $response_type ne $realm_type;
801 configure_u2f_and_wa
($tfa_cfg);
803 my ($result, $tfa_done);
804 if (defined($tfa_challenge)) {
806 $tfa_challenge = verify_ticket
($tfa_challenge, 0, $username);
807 $result = $tfa_cfg->authentication_verify2($username, $tfa_challenge, $tfa_response);
808 $tfa_challenge = undef;
810 $tfa_challenge = $tfa_cfg->authentication_challenge($username);
812 die "missing required 2nd keys\n"
813 if $realm_tfa && !defined($tfa_challenge);
815 if (defined($tfa_response)) {
816 if (defined($tfa_challenge)) {
818 $result = $tfa_cfg->authentication_verify2($username, $tfa_challenge, $tfa_response);
820 die "no such challenge\n";
827 # authentication_verify2 somehow returned undef - should be unreachable
828 die "2nd factor failed\n";
831 if ($result->{'needs-saving'}) {
832 cfs_write_file
('priv/tfa.cfg', $tfa_cfg);
834 if ($result->{'totp-limit-reached'}) {
835 # FIXME: send mail to the user (or admin/root if no email configured)
836 die "failed 2nd factor: TOTP limit reached, locked\n";
838 if ($result->{'tfa-limit-reached'}) {
839 # FIXME: send mail to the user (or admin/root if no email configured)
840 die "failed 1nd factor: TFA limit reached, user locked out\n";
842 if (!$result->{result
}) {
843 die "failed 2nd factor\n";
847 return $tfa_challenge;
850 # Returns a tfa challenge or undef.
851 sub authenticate_2nd_new
: prototype($$$$) {
852 my ($username, $realm, $tfa_response, $tfa_challenge) = @_;
856 if (defined($tfa_response) && $tfa_response =~ m/^recovery:/) {
857 $result = lock_tfa_config
(sub {
858 authenticate_2nd_new_do
($username, $realm, $tfa_response, $tfa_challenge);
861 $result = authenticate_2nd_new_do
($username, $realm, $tfa_response, $tfa_challenge);
864 # Yubico auth returns the authentication sub:
865 if (ref($result) eq 'CODE') {
866 $result = $result->();
872 sub authenticate_yubico_new
: prototype($$$) {
873 my ($tfa_cfg, $username, $realm, $tfa_challenge, $otp) = @_;
875 $tfa_challenge = verify_ticket
($tfa_challenge, 0, $username);
876 $tfa_challenge = from_json
($tfa_challenge);
878 if (!$tfa_challenge->{yubico
}) {
879 die "no such challenge\n";
882 my $keys = $tfa_cfg->get_yubico_keys($username);
883 die "no keys configured\n" if !defined($keys) || !length($keys);
885 authenticate_yubico_do
($otp, $keys, $realm);
887 # return `undef` to clear the tfa challenge.
891 sub authenticate_yubico_do
: prototype($$$) {
892 my ($value, $keys, $realm) = @_;
894 # fixme: proxy support?
897 PVE
::OTP
::yubico_verify_otp
($value, $keys, $realm->{url
}, $realm->{id
}, $realm->{key
}, $proxy);
900 sub configure_u2f_and_wa
: prototype($) {
904 my $get_origin = sub {
905 return $rpc_origin if defined($rpc_origin);
906 my $rpcenv = PVE
::RPCEnvironment
::get
();
907 if (my $origin = $rpcenv->get_request_host(1)) {
908 $rpc_origin = "https://$origin";
911 die "failed to figure out origin\n";
914 my $dc = cfs_read_file
('datacenter.cfg');
915 if (my $u2f = $dc->{u2f
}) {
917 $tfa_cfg->set_u2f_config({
918 origin
=> $u2f->{origin
} // $get_origin->(),
919 appid
=> $u2f->{appid
},
922 warn "u2f unavailable, configuration error: $@\n" if $@;
924 if (my $wa = $dc->{webauthn
}) {
925 $wa->{origin
} //= $get_origin->();
926 eval { $tfa_cfg->set_webauthn_config({%$wa}) };
927 warn "webauthn unavailable, configuration error: $@\n" if $@;
931 sub domain_set_password
{
932 my ($realm, $username, $password) = @_;
934 die "no auth domain specified" if !$realm;
936 my $domain_cfg = cfs_read_file
('domains.cfg');
938 my $cfg = $domain_cfg->{ids
}->{$realm};
939 die "auth domain '$realm' does not exist\n" if !$cfg;
940 my $plugin = PVE
::Auth
::Plugin-
>lookup($cfg->{type
});
941 $plugin->store_password($cfg, $realm, $username, $password);
944 sub iterate_acl_tree
{
945 my ($path, $node, $code) = @_;
947 $code->($path, $node);
949 $path = '' if $path eq '/'; # avoid leading '//'
951 my $children = $node->{children
};
953 foreach my $child (keys %$children) {
954 iterate_acl_tree
("$path/$child", $children->{$child}, $code);
958 # find ACL node corresponding to normalized $path under $root
959 sub find_acl_tree_node
{
960 my ($root, $path) = @_;
962 my $split_path = [ split("/", $path) ];
969 for my $p (@$split_path) {
972 $node->{children
} = {} if !$node->{children
};
973 $node->{children
}->{$p} = {} if !$node->{children
}->{$p};
975 $node = $node->{children
}->{$p};
982 my ($username, $usercfg, $group) = @_;
984 $usercfg->{users
}->{$username}->{groups
}->{$group} = 1;
985 $usercfg->{groups
}->{$group}->{users
}->{$username} = 1;
988 sub delete_user_group
{
989 my ($username, $usercfg) = @_;
991 foreach my $group (keys %{$usercfg->{groups
}}) {
993 delete ($usercfg->{groups
}->{$group}->{users
}->{$username})
994 if $usercfg->{groups
}->{$group}->{users
}->{$username};
998 sub delete_user_acl
{
999 my ($username, $usercfg) = @_;
1002 my ($path, $acl_node) = @_;
1004 delete ($acl_node->{users
}->{$username})
1005 if $acl_node->{users
}->{$username};
1008 iterate_acl_tree
("/", $usercfg->{acl_root
}, $code);
1011 sub delete_group_acl
{
1012 my ($group, $usercfg) = @_;
1015 my ($path, $acl_node) = @_;
1017 delete ($acl_node->{groups
}->{$group})
1018 if $acl_node->{groups
}->{$group};
1021 iterate_acl_tree
("/", $usercfg->{acl_root
}, $code);
1024 sub delete_pool_acl
{
1025 my ($pool, $usercfg) = @_;
1027 delete ($usercfg->{acl_root
}->{children
}->{pool
}->{children
}->{$pool});
1030 # we automatically create some predefined roles by splitting privs
1031 # into 3 groups (per category)
1032 # root: only root is allowed to do that
1033 # admin: an administrator can to that
1034 # user: a normal user/customer can to that
1042 'VM.Config.Network',
1044 'VM.Config.Options', # covers all other things
1050 'VM.Snapshot.Rollback',
1053 'VM.Config.CDROM', # change CDROM media
1054 'VM.Config.Cloudinit',
1066 'Sys.Modify', # edit/change node settings
1067 'Sys.Incoming', # incoming storage/guest migrations
1081 'Datastore.Allocate',
1082 'Datastore.AllocateTemplate',
1085 'Datastore.AllocateSpace',
1110 'Group.Allocate', # edit/change group settings
1111 'Realm.AllocateUser',
1119 'Pool.Allocate', # create/delete pools
1143 'Permissions.Modify' => 1, # not contained in a group
1146 my $special_roles = {
1147 'NoAccess' => {}, # no privileges
1148 'Administrator' => $valid_privs, # all privileges
1153 for my $cat (keys %$privgroups) {
1154 my $cd = $privgroups->{$cat};
1155 # create map to easily check if a privilege is valid
1156 for my $priv (@{$cd->{root
}}, @{$cd->{admin
}}, @{$cd->{user
}}, @{$cd->{audit
}}) {
1157 $valid_privs->{$priv} = 1;
1159 # create grouped admin roles and PVEAdmin
1160 for my $priv (@{$cd->{admin
}}, @{$cd->{user
}}, @{$cd->{audit
}}) {
1161 $special_roles->{"PVE${cat}Admin"}->{$priv} = 1;
1162 $special_roles->{"PVEAdmin"}->{$priv} = 1;
1164 # create grouped user and audit roles
1165 if (scalar(@{$cd->{user
}})) {
1166 for my $priv (@{$cd->{user
}}, @{$cd->{audit
}}) {
1167 $special_roles->{"PVE${cat}User"}->{$priv} = 1;
1170 for my $priv (@{$cd->{audit
}}) {
1171 $special_roles->{"PVEAuditor"}->{$priv} = 1;
1175 # remove Mapping.Modify from PVEAdmin, only Administrator, root@pam and
1176 # PVEMappingAdmin should be able to use that for now
1177 delete $special_roles->{"PVEAdmin"}->{"Mapping.Modify"};
1179 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
1184 sub create_priv_properties
{
1185 my $properties = {};
1186 foreach my $priv (keys %$valid_privs) {
1187 $properties->{$priv} = {
1195 sub role_is_special
{
1197 return (exists $special_roles->{$role}) ?
1 : 0;
1200 sub add_role_privs
{
1201 my ($role, $usercfg, $privs) = @_;
1205 die "role '$role' does not exist\n" if !$usercfg->{roles
}->{$role};
1207 foreach my $priv (split_list
($privs)) {
1208 if (defined ($valid_privs->{$priv})) {
1209 $usercfg->{roles
}->{$role}->{$priv} = 1;
1211 die "invalid privilege '$priv'\n";
1216 sub lookup_username
{
1217 my ($username, $noerr) = @_;
1219 $username =~ m!^(${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex})$!;
1222 my $domain_cfg = cfs_read_file
("domains.cfg");
1223 my $casesensitive = $domain_cfg->{ids
}->{$realm}->{'case-sensitive'} // 1;
1224 my $usercfg = cfs_read_file
('user.cfg');
1226 if (!$casesensitive) {
1227 my @matches = grep { lc $username eq lc $_ } (keys %{$usercfg->{users
}});
1229 die "ambiguous case insensitive match of username '$username', cannot safely grant access!\n"
1230 if scalar @matches > 1 && !$noerr;
1238 sub normalize_path
{
1241 return undef if !$path;
1247 $path = '/' if !$path;
1249 $path = "/$path" if $path !~ m
|^/|;
1251 return undef if $path !~ m
|^[[:alnum
:]\
.\
-\_\
/]+$|;
1258 return $path =~ m
!^(
1262 |/access/groups
/[[:alnum
:]\
.\
-\_
]+
1264 |/access/realm
/[[:alnum
:]\
.\
-\_
]+
1266 |/nodes/[[:alnum
:]\
.\
-\_
]+
1268 |/pool/[A-Za-z0-9\
.\
-_
]+(?
:/[A-Za-z0-9\
.\
-_
]+){0,2}
1271 |/sdn/controllers
/[[:alnum
:]\_\
-]+
1273 |/sdn/dns
/[[:alnum
:]]+
1275 |/sdn/ipams/[[:alnum
:]]+
1277 |/sdn/zones
/[[:alnum
:]\
.\
-\_
]+
1278 |/sdn/zones
/[[:alnum:]\.\-\_]+/[[:alnum
:]\
.\
-\_
]+
1279 |/sdn/zones
/[[:alnum
:]\
.\
-\_
]+/[[:alnum
:]\
.\
-\_
]+/[1-9][0-9]{0,3}
1281 |/storage/[[:alnum
:]\
.\
-\_
]+
1283 |/vms/[1-9][0-9]{2,}
1285 |/mapping/[[:alnum
:]\
.\
-\_
]+
1286 |/mapping/[[:alnum
:]\
.\
-\_
]+/[[:alnum
:]\
.\
-\_
]+
1290 PVE
::JSONSchema
::register_format
('pve-groupid', \
&verify_groupname
);
1291 sub verify_groupname
{
1292 my ($groupname, $noerr) = @_;
1294 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1296 die "group name '$groupname' contains invalid characters\n" if !$noerr;
1304 PVE
::JSONSchema
::register_format
('pve-roleid', \
&verify_rolename
);
1305 sub verify_rolename
{
1306 my ($rolename, $noerr) = @_;
1308 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
1310 die "role name '$rolename' contains invalid characters\n" if !$noerr;
1318 PVE
::JSONSchema
::register_format
('pve-poolid', \
&verify_poolname
);
1319 sub verify_poolname
{
1320 my ($poolname, $noerr) = @_;
1322 if (split("/", $poolname) > 3) {
1323 die "pool name '$poolname' nested too deeply (max levels = 3)\n" if !$noerr;
1328 # also adapt check_path above if changed!
1329 if ($poolname !~ m!^[A-Za-z0-9\.\-_]+(?:/[A-Za-z0-9\.\-_]+){0,2}$!) {
1330 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
1338 PVE
::JSONSchema
::register_format
('pve-priv', \
&verify_privname
);
1339 sub verify_privname
{
1340 my ($priv, $noerr) = @_;
1342 if (!$valid_privs->{$priv}) {
1343 die "invalid privilege '$priv'\n" if !$noerr;
1351 sub userconfig_force_defaults
{
1354 foreach my $r (keys %$special_roles) {
1355 $cfg->{roles
}->{$r} = $special_roles->{$r};
1358 # add root user if not exists
1359 if (!$cfg->{users
}->{'root@pam'}) {
1360 $cfg->{users
}->{'root@pam'}->{enable
} = 1;
1363 # add (empty) ACL tree root node
1364 if (!$cfg->{acl_root
}) {
1365 $cfg->{acl_root
} = {};
1369 sub parse_user_config
{
1370 my ($filename, $raw) = @_;
1374 userconfig_force_defaults
($cfg);
1376 $raw = '' if !defined($raw);
1377 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1381 foreach my $d (split (/:/, $line)) {
1387 my $et = shift @data;
1389 if ($et eq 'user') {
1390 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
1392 my (undef, undef, $realm) = PVE
::Auth
::Plugin
::verify_username
($user, 1);
1394 warn "user config - ignore user '$user' - invalid user name\n";
1398 $enable = $enable ?
1 : 0;
1400 $expire = 0 if !$expire;
1402 if ($expire !~ m/^\d+$/) {
1403 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
1406 $expire = int($expire);
1408 #if (!verify_groupname ($group, 1)) {
1409 # warn "user config - ignore user '$user' - invalid characters in group name\n";
1413 $cfg->{users
}->{$user} = {
1417 $cfg->{users
}->{$user}->{firstname
} = PVE
::Tools
::decode_text
($firstname) if $firstname;
1418 $cfg->{users
}->{$user}->{lastname
} = PVE
::Tools
::decode_text
($lastname) if $lastname;
1419 $cfg->{users
}->{$user}->{email
} = $email;
1420 $cfg->{users
}->{$user}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1421 $cfg->{users
}->{$user}->{expire
} = $expire;
1422 # keys: allowed yubico key ids or oath secrets (base32 encoded)
1423 $cfg->{users
}->{$user}->{keys} = $keys if $keys;
1425 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
1426 #$cfg->{groups}->{$group}->{$user} = 1;
1428 } elsif ($et eq 'group') {
1429 my ($group, $userlist, $comment) = @data;
1431 if (!verify_groupname
($group, 1)) {
1432 warn "user config - ignore group '$group' - invalid characters in group name\n";
1436 # make sure to add the group (even if there are no members)
1437 $cfg->{groups
}->{$group} = { users
=> {} } if !$cfg->{groups
}->{$group};
1439 $cfg->{groups
}->{$group}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1441 foreach my $user (split_list
($userlist)) {
1443 if (!PVE
::Auth
::Plugin
::verify_username
($user, 1)) {
1444 warn "user config - ignore invalid group member '$user'\n";
1448 if ($cfg->{users
}->{$user}) { # user exists
1449 $cfg->{users
}->{$user}->{groups
}->{$group} = 1;
1451 warn "user config - ignore invalid group member '$user'\n";
1453 $cfg->{groups
}->{$group}->{users
}->{$user} = 1;
1456 } elsif ($et eq 'role') {
1457 my ($role, $privlist) = @data;
1459 if (!verify_rolename
($role, 1)) {
1460 warn "user config - ignore role '$role' - invalid characters in role name\n";
1464 # make sure to add the role (even if there are no privileges)
1465 $cfg->{roles
}->{$role} = {} if !$cfg->{roles
}->{$role};
1467 foreach my $priv (split_list
($privlist)) {
1468 if (defined ($valid_privs->{$priv})) {
1469 $cfg->{roles
}->{$role}->{$priv} = 1;
1471 warn "user config - ignore invalid privilege '$priv'\n";
1475 } elsif ($et eq 'acl') {
1476 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
1478 $propagate = $propagate ?
1 : 0;
1480 if (my $path = normalize_path
($pathtxt)) {
1482 foreach my $role (split_list
($rolelist)) {
1484 if (!verify_rolename
($role, 1)) {
1485 warn "user config - ignore invalid role name '$role' in acl\n";
1489 if (!$cfg->{roles
}->{$role}) {
1490 warn "user config - ignore invalid acl role '$role'\n";
1494 foreach my $ug (split_list
($uglist)) {
1495 my ($group) = $ug =~ m/^@(\S+)$/;
1497 if ($group && verify_groupname
($group, 1)) {
1498 if (!$cfg->{groups
}->{$group}) { # group does not exist
1499 warn "user config - ignore invalid acl group '$group'\n";
1501 $acl_node = find_acl_tree_node
($cfg->{acl_root
}, $path) if !$acl_node;
1502 $acl_node->{groups
}->{$group}->{$role} = $propagate;
1503 } elsif (PVE
::Auth
::Plugin
::verify_username
($ug, 1)) {
1504 if (!$cfg->{users
}->{$ug}) { # user does not exist
1505 warn "user config - ignore invalid acl member '$ug'\n";
1507 $acl_node = find_acl_tree_node
($cfg->{acl_root
}, $path) if !$acl_node;
1508 $acl_node->{users
}->{$ug}->{$role} = $propagate;
1509 } elsif (my ($user, $token) = split_tokenid
($ug, 1)) {
1510 if (check_token_exist
($cfg, $user, $token, 1)) {
1511 $acl_node = find_acl_tree_node
($cfg->{acl_root
}, $path) if !$acl_node;
1512 $acl_node->{tokens
}->{$ug}->{$role} = $propagate;
1514 warn "user config - ignore invalid acl token '$ug'\n";
1517 warn "user config - invalid user/group '$ug' in acl\n";
1522 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1524 } elsif ($et eq 'pool') {
1525 my ($pool, $comment, $vmlist, $storelist) = @data;
1527 if (!verify_poolname
($pool, 1)) {
1528 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1532 # make sure to add the pool (even if there are no members)
1533 $cfg->{pools
}->{$pool} = { vms
=> {}, storage
=> {}, pools
=> {} }
1534 if !$cfg->{pools
}->{$pool};
1536 if ($pool =~ m!/!) {
1538 while ($curr =~ m!^(.+)/[^/]+$!) {
1539 # ensure nested pool info is correctly recorded
1541 $cfg->{pools
}->{$curr}->{parent
} = $parent;
1542 $cfg->{pools
}->{$parent} = { vms
=> {}, storage
=> {}, pools
=> {} }
1543 if !$cfg->{pools
}->{$parent};
1544 $cfg->{pools
}->{$parent}->{pools
}->{$curr} = 1;
1549 $cfg->{pools
}->{$pool}->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1551 foreach my $vmid (split_list
($vmlist)) {
1552 if ($vmid !~ m/^\d+$/) {
1553 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1558 if ($cfg->{vms
}->{$vmid}) {
1559 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1563 $cfg->{pools
}->{$pool}->{vms
}->{$vmid} = 1;
1565 # record vmid ==> pool relation
1566 $cfg->{vms
}->{$vmid} = $pool;
1569 foreach my $storeid (split_list
($storelist)) {
1570 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1571 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1574 $cfg->{pools
}->{$pool}->{storage
}->{$storeid} = 1;
1576 } elsif ($et eq 'token') {
1577 my ($tokenid, $expire, $privsep, $comment) = @data;
1579 my ($user, $token) = split_tokenid
($tokenid, 1);
1580 if (!($user && $token)) {
1581 warn "user config - ignore invalid tokenid '$tokenid'\n";
1585 $privsep = $privsep ?
1 : 0;
1587 $expire = 0 if !$expire;
1589 if ($expire !~ m/^\d+$/) {
1590 warn "user config - ignore token '$tokenid' - (illegal characters in expire '$expire')\n";
1593 $expire = int($expire);
1595 if (my $user_cfg = $cfg->{users
}->{$user}) { # user exists
1596 $user_cfg->{tokens
}->{$token} = {} if !$user_cfg->{tokens
}->{$token};
1597 my $token_cfg = $user_cfg->{tokens
}->{$token};
1598 $token_cfg->{privsep
} = $privsep;
1599 $token_cfg->{expire
} = $expire;
1600 $token_cfg->{comment
} = PVE
::Tools
::decode_text
($comment) if $comment;
1602 warn "user config - ignore token '$tokenid' - user does not exist\n";
1605 warn "user config - ignore config line: $line\n";
1609 userconfig_force_defaults
($cfg);
1614 sub write_user_config
{
1615 my ($filename, $cfg) = @_;
1619 foreach my $user (sort keys %{$cfg->{users
}}) {
1620 my $d = $cfg->{users
}->{$user};
1621 my $firstname = $d->{firstname
} ? PVE
::Tools
::encode_text
($d->{firstname
}) : '';
1622 my $lastname = $d->{lastname
} ? PVE
::Tools
::encode_text
($d->{lastname
}) : '';
1623 my $email = $d->{email
} || '';
1624 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1625 my $expire = int($d->{expire
} || 0);
1626 my $enable = $d->{enable
} ?
1 : 0;
1627 my $keys = $d->{keys} ?
$d->{keys} : '';
1628 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1630 my $user_tokens = $d->{tokens
};
1631 foreach my $token (sort keys %$user_tokens) {
1632 my $td = $user_tokens->{$token};
1633 my $full_tokenid = join_tokenid
($user, $token);
1634 my $comment = $td->{comment
} ? PVE
::Tools
::encode_text
($td->{comment
}) : '';
1635 my $expire = int($td->{expire
} || 0);
1636 my $privsep = $td->{privsep
} ?
1 : 0;
1637 $data .= "token:$full_tokenid:$expire:$privsep:$comment:\n";
1643 foreach my $group (sort keys %{$cfg->{groups
}}) {
1644 my $d = $cfg->{groups
}->{$group};
1645 my $list = join (',', sort keys %{$d->{users
}});
1646 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1647 $data .= "group:$group:$list:$comment:\n";
1652 foreach my $pool (sort keys %{$cfg->{pools
}}) {
1653 my $d = $cfg->{pools
}->{$pool};
1654 my $vmlist = join (',', sort keys %{$d->{vms
}});
1655 my $storelist = join (',', sort keys %{$d->{storage
}});
1656 my $comment = $d->{comment
} ? PVE
::Tools
::encode_text
($d->{comment
}) : '';
1657 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1662 foreach my $role (sort keys %{$cfg->{roles
}}) {
1663 next if $special_roles->{$role};
1665 my $d = $cfg->{roles
}->{$role};
1666 my $list = join (',', sort keys %$d);
1667 $data .= "role:$role:$list:\n";
1672 my $collect_rolelist_members = sub {
1673 my ($acl_members, $result, $prefix, $exclude) = @_;
1675 foreach my $member (keys %$acl_members) {
1676 next if $exclude && $member eq $exclude;
1680 foreach my $role (sort keys %{$acl_members->{$member}}) {
1681 my $propagate = $acl_members->{$member}->{$role};
1690 $result->{0}->{$l0}->{"${prefix}${member}"} = 1 if $l0;
1691 $result->{1}->{$l1}->{"${prefix}${member}"} = 1 if $l1;
1695 iterate_acl_tree
("/", $cfg->{acl_root
}, sub {
1696 my ($path, $d) = @_;
1698 my $rolelist_members = {};
1700 $collect_rolelist_members->($d->{'groups'}, $rolelist_members, '@');
1702 # no need to save 'root@pam', it is always 'Administrator'
1703 $collect_rolelist_members->($d->{'users'}, $rolelist_members, '', 'root@pam');
1705 $collect_rolelist_members->($d->{'tokens'}, $rolelist_members, '');
1707 foreach my $propagate (0,1) {
1708 my $filtered = $rolelist_members->{$propagate};
1709 foreach my $rolelist (sort keys %$filtered) {
1710 my $uglist = join (',', sort keys %{$filtered->{$rolelist}});
1711 $data .= "acl:$propagate:$path:$uglist:$rolelist:\n";
1720 # Creates a `PVE::RS::TFA` instance from the raw config data.
1721 # Its contained hash will also support the legacy functionality.
1722 sub parse_priv_tfa_config
{
1723 my ($filename, $raw) = @_;
1725 $raw = '' if !defined($raw);
1726 my $cfg = PVE
::RS
::TFA-
>new($raw);
1728 # Purge invalid users:
1729 foreach my $user ($cfg->users()->@*) {
1730 my (undef, undef, $realm) = PVE
::Auth
::Plugin
::verify_username
($user, 1);
1732 warn "user tfa config - ignore user '$user' - invalid user name\n";
1733 $cfg->remove_user($user);
1740 sub write_priv_tfa_config
{
1741 my ($filename, $cfg) = @_;
1743 return $cfg->write();
1747 my ($cfg, $user, $path) = @_;
1749 # NOTE: we do not consider pools here.
1750 # NOTE: for privsep tokens, this does not filter roles by those that the
1751 # corresponding user has.
1752 # Use $rpcenv->permission() for any actual permission checks!
1754 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1756 if (!defined($path)) {
1757 # this shouldn't happen!
1758 warn "internal error: ACL check called for undefined ACL path!\n";
1762 if (pve_verify_tokenid
($user, 1)) {
1763 my $tokenid = $user;
1764 my ($username, $token) = split_tokenid
($tokenid);
1766 my $token_info = $cfg->{users
}->{$username}->{tokens
}->{$token};
1767 return () if !$token_info;
1769 my $user_roles = roles
($cfg, $username, $path);
1771 # return full user privileges
1772 return $user_roles if !$token_info->{privsep
};
1777 my $split = [ split("/", $path) ];
1782 my $acl = $cfg->{acl_root
};
1786 my $p = shift @$split;
1787 my $final = !@$split;
1789 $acl = $acl->{children
}->{$p};
1792 #print "CHECKACL $path $p\n";
1793 #print "ACL $path = " . Dumper ($acl);
1794 if (my $ri = $acl->{tokens
}->{$user}) {
1796 foreach my $role (keys %$ri) {
1797 my $propagate = $ri->{$role};
1798 if ($final || $propagate) {
1799 #print "APPLY ROLE $p $user $role\n";
1801 $new->{$role} = $propagate;
1805 $roles = $new; # overwrite previous settings
1810 if (my $ri = $acl->{users
}->{$user}) {
1812 foreach my $role (keys %$ri) {
1813 my $propagate = $ri->{$role};
1814 if ($final || $propagate) {
1815 #print "APPLY ROLE $p $user $role\n";
1817 $new->{$role} = $propagate;
1821 $roles = $new; # overwrite previous settings
1822 next; # user privs always override group privs
1827 foreach my $g (keys %{$acl->{groups
}}) {
1828 next if !$cfg->{groups
}->{$g}->{users
}->{$user};
1829 if (my $ri = $acl->{groups
}->{$g}) {
1830 foreach my $role (keys %$ri) {
1831 my $propagate = $ri->{$role};
1832 if ($final || $propagate) {
1833 #print "APPLY ROLE $p \@$g $role\n";
1835 $new->{$role} = $propagate;
1841 $roles = $new; # overwrite previous settings
1846 return { 'NoAccess' => $roles->{NoAccess
} } if defined ($roles->{NoAccess
});
1847 #return () if defined ($roles->{NoAccess});
1849 #print "permission $user $path = " . Dumper ($roles);
1851 #print "roles $user $path = " . join (',', @ra) . "\n";
1856 sub remove_vm_access
{
1858 my $delVMaccessFn = sub {
1859 my $usercfg = cfs_read_file
("user.cfg");
1862 if (my $acl = $usercfg->{acl_root
}->{children
}->{vms
}->{children
}->{$vmid}) {
1863 delete $usercfg->{acl_root
}->{children
}->{vms
}->{children
}->{$vmid};
1866 if (my $pool = $usercfg->{vms
}->{$vmid}) {
1867 if (my $data = $usercfg->{pools
}->{$pool}) {
1868 delete $data->{vms
}->{$vmid};
1869 delete $usercfg->{vms
}->{$vmid};
1873 cfs_write_file
("user.cfg", $usercfg) if $modified;
1876 lock_user_config
($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1879 sub remove_storage_access
{
1882 my $deleteStorageAccessFn = sub {
1883 my $usercfg = cfs_read_file
("user.cfg");
1886 if (my $acl = $usercfg->{acl_root
}->{children
}->{storage
}->{children
}->{$storeid}) {
1887 delete $usercfg->{acl_root
}->{children
}->{storage
}->{children
}->{$storeid};
1890 foreach my $pool (keys %{$usercfg->{pools
}}) {
1891 delete $usercfg->{pools
}->{$pool}->{storage
}->{$storeid};
1894 cfs_write_file
("user.cfg", $usercfg) if $modified;
1897 lock_user_config
($deleteStorageAccessFn,
1898 "access permissions cleanup for storage $storeid failed");
1901 sub add_vm_to_pool
{
1902 my ($vmid, $pool) = @_;
1904 my $addVMtoPoolFn = sub {
1905 my $usercfg = cfs_read_file
("user.cfg");
1906 if (my $data = $usercfg->{pools
}->{$pool}) {
1907 $data->{vms
}->{$vmid} = 1;
1908 $usercfg->{vms
}->{$vmid} = $pool;
1909 cfs_write_file
("user.cfg", $usercfg);
1913 lock_user_config
($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1916 sub remove_vm_from_pool
{
1919 my $delVMfromPoolFn = sub {
1920 my $usercfg = cfs_read_file
("user.cfg");
1921 if (my $pool = $usercfg->{vms
}->{$vmid}) {
1922 if (my $data = $usercfg->{pools
}->{$pool}) {
1923 delete $data->{vms
}->{$vmid};
1924 delete $usercfg->{vms
}->{$vmid};
1925 cfs_write_file
("user.cfg", $usercfg);
1930 lock_user_config
($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1933 my $USER_CONTROLLED_TFA_TYPES = {
1938 sub user_remove_tfa
: prototype($) {
1941 my $tfa_cfg = cfs_read_file
('priv/tfa.cfg');
1942 $tfa_cfg->remove_user($userid);
1943 cfs_write_file
('priv/tfa.cfg', $tfa_cfg);
1946 my sub add_old_yubico_keys
: prototype($$$) {
1947 my ($userid, $tfa_cfg, $keys) = @_;
1950 foreach my $key (split_list
($keys)) {
1951 my $description = "<old userconfig key $count>";
1953 $tfa_cfg->add_yubico_entry($userid, $description, $key);
1957 my sub normalize_totp_secret
: prototype($) {
1961 # See PVE::OTP::oath_verify_otp:
1962 if ($key =~ /^v2-0x([0-9a-fA-F]+)$/) {
1964 $binkey = pack('H*', $1);
1965 } elsif ($key =~ /^v2-([A-Z2-7=]+)$/) {
1967 $binkey = MIME
::Base32
::decode_rfc3548
($1);
1968 } elsif ($key =~ /^[A-Z2-7=]{16}$/) {
1969 $binkey = MIME
::Base32
::decode_rfc3548
($key);
1970 } elsif ($key =~ /^[A-Fa-f0-9]{40}$/) {
1971 $binkey = pack('H*', $key);
1976 return MIME
::Base32
::encode_rfc3548
($binkey);
1979 my sub add_old_totp_keys
: prototype($$$$) {
1980 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1982 my $issuer = 'Proxmox%20VE';
1983 my $account = uri_escape
("Old key for $userid");
1984 my $digits = $realm_tfa->{digits
} || 6;
1985 my $step = $realm_tfa->{step
} || 30;
1986 my $uri = "otpauth://totp/$issuer:$account?digits=$digits&period=$step&algorithm=SHA1&secret=";
1989 foreach my $key (split_list
($keys)) {
1990 $key = normalize_totp_secret
($key);
1991 # and just skip invalid keys:
1992 next if !defined($key);
1994 my $description = "<old userconfig key $count>";
1996 eval { $tfa_cfg->add_totp_entry($userid, $description, $uri . $key) };
2001 sub add_old_keys_to_realm_tfa
: prototype($$$$) {
2002 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
2004 # if there's no realm tfa configured, we don't know what the keys mean, so we just ignore
2006 return if !$realm_tfa;
2008 my $type = $realm_tfa->{type
};
2009 if ($type eq 'oath') {
2010 add_old_totp_keys
($userid, $tfa_cfg, $realm_tfa, $keys);
2011 } elsif ($type eq 'yubico') {
2012 add_old_yubico_keys
($userid, $tfa_cfg, $keys);
2014 # invalid keys, we'll just drop them now...
2018 sub user_get_tfa
: prototype($$$) {
2019 my ($username, $realm) = @_;
2021 my $user_cfg = cfs_read_file
('user.cfg');
2022 my $user = $user_cfg->{users
}->{$username}
2023 or die "user '$username' not found\n";
2025 my $keys = $user->{keys};
2027 my $domain_cfg = cfs_read_file
('domains.cfg');
2028 my $realm_cfg = $domain_cfg->{ids
}->{$realm};
2029 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
2031 my $realm_tfa = $realm_cfg->{tfa
};
2032 $realm_tfa = PVE
::Auth
::Plugin
::parse_tfa_config
($realm_tfa)
2035 my $tfa_cfg = cfs_read_file
('priv/tfa.cfg');
2036 if (defined($keys) && $keys !~ /^x(?:!.*)$/) {
2037 add_old_keys_to_realm_tfa
($username, $tfa_cfg, $realm_tfa, $keys);
2040 return ($tfa_cfg, $realm_tfa);
2043 # bash completion helpers
2045 register_standard_option
('userid-completed',
2046 get_standard_option
('userid', { completion
=> \
&complete_username
}),
2049 sub complete_username
{
2051 my $user_cfg = cfs_read_file
('user.cfg');
2053 return [ keys %{$user_cfg->{users
}} ];
2056 sub complete_group
{
2058 my $user_cfg = cfs_read_file
('user.cfg');
2060 return [ keys %{$user_cfg->{groups
}} ];
2063 sub complete_realm
{
2065 my $domain_cfg = cfs_read_file
('domains.cfg');
2067 return [ keys %{$domain_cfg->{ids
}} ];