]> git.proxmox.com Git - pve-access-control.git/blob - PVE/AccessControl.pm
4e9deea87ae6be7802fc0c6b00953f3fb2b0f4ea
[pve-access-control.git] / PVE / AccessControl.pm
1 package PVE::AccessControl;
2
3 use strict;
4 use warnings;
5 use Encode;
6 use Crypt::OpenSSL::Random;
7 use Crypt::OpenSSL::RSA;
8 use Net::SSLeay;
9 use Net::IP;
10 use MIME::Base64;
11 use Digest::SHA;
12 use IO::File;
13 use File::stat;
14 use JSON;
15
16 use PVE::OTP;
17 use PVE::Ticket;
18 use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
19 use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
20 use PVE::JSONSchema qw(register_standard_option get_standard_option);
21
22 use PVE::Auth::Plugin;
23 use PVE::Auth::AD;
24 use PVE::Auth::LDAP;
25 use PVE::Auth::PVE;
26 use PVE::Auth::PAM;
27
28 # load and initialize all plugins
29
30 PVE::Auth::AD->register();
31 PVE::Auth::LDAP->register();
32 PVE::Auth::PVE->register();
33 PVE::Auth::PAM->register();
34 PVE::Auth::Plugin->init();
35
36 # $authdir must be writable by root only!
37 my $confdir = "/etc/pve";
38 my $authdir = "$confdir/priv";
39
40 my $pve_www_key_fn = "$confdir/pve-www.key";
41
42 my $pve_auth_key_files = {
43 priv => "$authdir/authkey.key",
44 pub => "$confdir/authkey.pub",
45 pubold => "$confdir/authkey.pub.old",
46 };
47
48 my $pve_auth_key_cache = {};
49
50 my $ticket_lifetime = 3600 * 2; # 2 hours
51 my $authkey_lifetime = 3600 * 24; # rotate every 24 hours
52
53 Crypt::OpenSSL::RSA->import_random_seed();
54
55 cfs_register_file('user.cfg',
56 \&parse_user_config,
57 \&write_user_config);
58 cfs_register_file('priv/tfa.cfg',
59 \&parse_priv_tfa_config,
60 \&write_priv_tfa_config);
61
62 sub verify_username {
63 PVE::Auth::Plugin::verify_username(@_);
64 }
65
66 sub pve_verify_realm {
67 PVE::Auth::Plugin::pve_verify_realm(@_);
68 }
69
70 sub lock_user_config {
71 my ($code, $errmsg) = @_;
72
73 cfs_lock_file("user.cfg", undef, $code);
74 if (my $err = $@) {
75 $errmsg ? die "$errmsg: $err" : die $err;
76 }
77 }
78
79 my $cache_read_key = sub {
80 my ($type) = @_;
81
82 my $path = $pve_auth_key_files->{$type};
83
84 my $read_key_and_mtime = sub {
85 my $fh = IO::File->new($path, "r");
86
87 return undef if !defined($fh);
88
89 my $st = stat($fh);
90 my $pem = PVE::Tools::safe_read_from($fh, 0, 0, $path);
91
92 close $fh;
93
94 my $key;
95 if ($type eq 'pub' || $type eq 'pubold') {
96 $key = eval { Crypt::OpenSSL::RSA->new_public_key($pem); };
97 } elsif ($type eq 'priv') {
98 $key = eval { Crypt::OpenSSL::RSA->new_private_key($pem); };
99 } else {
100 die "Invalid authkey type '$type'\n";
101 }
102
103 return { key => $key, mtime => $st->mtime };
104 };
105
106 if (!defined($pve_auth_key_cache->{$type})) {
107 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
108 } else {
109 my $st = stat($path);
110 if (!$st || $st->mtime != $pve_auth_key_cache->{$type}->{mtime}) {
111 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
112 }
113 }
114
115 return $pve_auth_key_cache->{$type};
116 };
117
118 sub get_pubkey {
119 my ($old) = @_;
120
121 my $type = $old ? 'pubold' : 'pub';
122
123 my $res = $cache_read_key->($type);
124 return undef if !defined($res);
125
126 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
127 }
128
129 sub get_privkey {
130 my $res = $cache_read_key->('priv');
131
132 if (!defined($res) || !check_authkey(1)) {
133 rotate_authkey();
134 $res = $cache_read_key->('priv');
135 }
136
137 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
138 }
139
140 sub check_authkey {
141 my ($quiet) = @_;
142
143 # skip check if non-quorate, as rotation is not possible anyway
144 return 1 if !PVE::Cluster::check_cfs_quorum(1);
145
146 my ($pub_key, $mtime) = get_pubkey();
147 if (!$pub_key) {
148 warn "auth key pair missing, generating new one..\n" if !$quiet;
149 return 0;
150 } else {
151 if (time() - $mtime >= $authkey_lifetime) {
152 warn "auth key pair too old, rotating..\n" if !$quiet;;
153 return 0;
154 } else {
155 warn "auth key new enough, skipping rotation\n" if !$quiet;;
156 return 1;
157 }
158 }
159 }
160
161 sub rotate_authkey {
162 return if $authkey_lifetime == 0;
163
164 PVE::Cluster::cfs_lock_authkey(undef, sub {
165 # re-check with lock to avoid double rotation in clusters
166 return if check_authkey();
167
168 my $old = get_pubkey();
169 my $new = Crypt::OpenSSL::RSA->generate_key(2048);
170
171 if ($old) {
172 eval {
173 my $pem = $old->get_public_key_x509_string();
174 # mtime is used for caching and ticket age range calculation
175 PVE::Tools::file_set_contents($pve_auth_key_files->{pubold}, $pem);
176 };
177 die "Failed to store old auth key: $@\n" if $@;
178 }
179
180 eval {
181 my $pem = $new->get_public_key_x509_string();
182 # mtime is used for caching and ticket age range calculation,
183 # should be close to that of pubold above
184 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
185 };
186 if ($@) {
187 if ($old) {
188 warn "Failed to store new auth key - $@\n";
189 warn "Reverting to previous auth key\n";
190 eval {
191 my $pem = $old->get_public_key_x509_string();
192 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
193 };
194 die "Failed to restore old auth key: $@\n" if $@;
195 } else {
196 die "Failed to store new auth key - $@\n";
197 }
198 }
199
200 eval {
201 my $pem = $new->get_private_key_string();
202 PVE::Tools::file_set_contents($pve_auth_key_files->{priv}, $pem);
203 };
204 if ($@) {
205 warn "Failed to store new auth key - $@\n";
206 warn "Deleting auth key to force regeneration\n";
207 unlink $pve_auth_key_files->{pub};
208 unlink $pve_auth_key_files->{priv};
209 }
210 });
211 die $@ if $@;
212 }
213
214 my $csrf_prevention_secret;
215 my $csrf_prevention_secret_legacy;
216 my $get_csrfr_secret = sub {
217 if (!$csrf_prevention_secret) {
218 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
219 $csrf_prevention_secret = Digest::SHA::hmac_sha256_base64($input);
220 $csrf_prevention_secret_legacy = Digest::SHA::sha1_base64($input);
221 }
222 return $csrf_prevention_secret;
223 };
224
225 sub assemble_csrf_prevention_token {
226 my ($username) = @_;
227
228 my $secret = &$get_csrfr_secret();
229
230 return PVE::Ticket::assemble_csrf_prevention_token ($secret, $username);
231 }
232
233 sub verify_csrf_prevention_token {
234 my ($username, $token, $noerr) = @_;
235
236 my $secret = $get_csrfr_secret->();
237
238 # FIXME: remove with PVE 7 and/or refactor all into PVE::Ticket ?
239 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
240 my $sig = $2;
241 if (length($sig) == 27) {
242 # the legacy secret got populated by above get_csrfr_secret call
243 $secret = $csrf_prevention_secret_legacy;
244 }
245 }
246
247 return PVE::Ticket::verify_csrf_prevention_token(
248 $secret, $username, $token, -300, $ticket_lifetime, $noerr);
249 }
250
251 my $get_ticket_age_range = sub {
252 my ($now, $mtime, $rotated) = @_;
253
254 my $key_age = $now - $mtime;
255 $key_age = 0 if $key_age < 0;
256
257 my $min = -300;
258 my $max = $ticket_lifetime;
259
260 if ($rotated) {
261 # ticket creation after rotation is not allowed
262 $min = $key_age - 300;
263 } else {
264 if ($key_age > $authkey_lifetime && $authkey_lifetime > 0) {
265 if (PVE::Cluster::check_cfs_quorum(1)) {
266 # key should have been rotated, clamp range accordingly
267 $min = $key_age - $authkey_lifetime;
268 } else {
269 warn "Cluster not quorate - extending auth key lifetime!\n";
270 }
271 }
272
273 $max = $key_age + 300 if $key_age < $ticket_lifetime;
274 }
275
276 return undef if $min > $ticket_lifetime;
277 return ($min, $max);
278 };
279
280 sub assemble_ticket {
281 my ($data) = @_;
282
283 my $rsa_priv = get_privkey();
284
285 return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $data);
286 }
287
288 sub verify_ticket {
289 my ($ticket, $noerr) = @_;
290
291 my $now = time();
292
293 my $check = sub {
294 my ($old) = @_;
295
296 my ($rsa_pub, $rsa_mtime) = get_pubkey($old);
297 return undef if !$rsa_pub;
298
299 my ($min, $max) = $get_ticket_age_range->($now, $rsa_mtime, $old);
300 return undef if !defined($min);
301
302 return PVE::Ticket::verify_rsa_ticket(
303 $rsa_pub, 'PVE', $ticket, undef, $min, $max, 1);
304 };
305
306 my ($data, $age) = $check->();
307
308 # check with old, rotated key if current key failed
309 ($data, $age) = $check->(1) if !defined($data);
310
311 my $auth_failure = sub {
312 if ($noerr) {
313 return undef;
314 } else {
315 # raise error via undef ticket
316 PVE::Ticket::verify_rsa_ticket(undef, 'PVE');
317 }
318 };
319
320 if (!defined($data)) {
321 return $auth_failure->();
322 }
323
324 my ($username, $tfa_info);
325 if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
326 # Ticket for u2f-users:
327 ($username, my $challenge) = ($1, $2);
328 if ($challenge eq 'verified') {
329 # u2f challenge was completed
330 $challenge = undef;
331 } elsif (!wantarray) {
332 # The caller is not aware there could be an ongoing challenge,
333 # so we treat this ticket as invalid:
334 return $auth_failure->();
335 }
336 $tfa_info = {
337 type => 'u2f',
338 challenge => $challenge,
339 };
340 } elsif ($data =~ /^tfa!(.*)$/) {
341 # TOTP and Yubico don't require a challenge so this is the generic
342 # 'missing 2nd factor ticket'
343 $username = $1;
344 $tfa_info = { type => 'tfa' };
345 } else {
346 # Regular ticket (full access)
347 $username = $data;
348 }
349
350 return undef if !PVE::Auth::Plugin::verify_username($username, $noerr);
351
352 return wantarray ? ($username, $age, $tfa_info) : $username;
353 }
354
355 # VNC tickets
356 # - they do not contain the username in plain text
357 # - they are restricted to a specific resource path (example: '/vms/100')
358 sub assemble_vnc_ticket {
359 my ($username, $path) = @_;
360
361 my $rsa_priv = get_privkey();
362
363 $path = normalize_path($path);
364
365 my $secret_data = "$username:$path";
366
367 return PVE::Ticket::assemble_rsa_ticket(
368 $rsa_priv, 'PVEVNC', undef, $secret_data);
369 }
370
371 sub verify_vnc_ticket {
372 my ($ticket, $username, $path, $noerr) = @_;
373
374 my $secret_data = "$username:$path";
375
376 my ($rsa_pub, $rsa_mtime) = get_pubkey();
377 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime && $authkey_lifetime > 0)) {
378 if ($noerr) {
379 return undef;
380 } else {
381 # raise error via undef ticket
382 PVE::Ticket::verify_rsa_ticket($rsa_pub, 'PVEVNC');
383 }
384 }
385
386 return PVE::Ticket::verify_rsa_ticket(
387 $rsa_pub, 'PVEVNC', $ticket, $secret_data, -20, 40, $noerr);
388 }
389
390 sub assemble_spice_ticket {
391 my ($username, $vmid, $node) = @_;
392
393 my $secret = &$get_csrfr_secret();
394
395 return PVE::Ticket::assemble_spice_ticket(
396 $secret, $username, $vmid, $node);
397 }
398
399 sub verify_spice_connect_url {
400 my ($connect_str) = @_;
401
402 my $secret = &$get_csrfr_secret();
403
404 return PVE::Ticket::verify_spice_connect_url($secret, $connect_str);
405 }
406
407 sub read_x509_subject_spice {
408 my ($filename) = @_;
409
410 # read x509 subject
411 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
412 die "Could not open $filename using OpenSSL\n"
413 if !$bio;
414
415 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
416 Net::SSLeay::BIO_free($bio);
417
418 die "Could not parse X509 certificate in $filename\n"
419 if !$x509;
420
421 my $nameobj = Net::SSLeay::X509_get_subject_name($x509);
422 my $subject = Net::SSLeay::X509_NAME_oneline($nameobj);
423 Net::SSLeay::X509_free($x509);
424
425 # remote-viewer wants comma as seperator (not '/')
426 $subject =~ s!^/!!;
427 $subject =~ s!/(\w+=)!,$1!g;
428
429 return $subject;
430 }
431
432 # helper to generate SPICE remote-viewer configuration
433 sub remote_viewer_config {
434 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
435
436 if (!$proxy) {
437 my $host = `hostname -f` || PVE::INotify::nodename();
438 chomp $host;
439 $proxy = $host;
440 }
441
442 my ($ticket, $proxyticket) = assemble_spice_ticket($authuser, $vmid, $node);
443
444 my $filename = "/etc/pve/local/pve-ssl.pem";
445 my $subject = read_x509_subject_spice($filename);
446
447 my $cacert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192);
448 $cacert =~ s/\n/\\n/g;
449
450 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
451 my $config = {
452 'secure-attention' => "Ctrl+Alt+Ins",
453 'toggle-fullscreen' => "Shift+F11",
454 'release-cursor' => "Ctrl+Alt+R",
455 type => 'spice',
456 title => $title,
457 host => $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
458 proxy => "http://$proxy:3128",
459 'tls-port' => $port,
460 'host-subject' => $subject,
461 ca => $cacert,
462 password => $ticket,
463 'delete-this-file' => 1,
464 };
465
466 return ($ticket, $proxyticket, $config);
467 }
468
469 sub check_user_exist {
470 my ($usercfg, $username, $noerr) = @_;
471
472 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
473 return undef if !$username;
474
475 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
476
477 die "no such user ('$username')\n" if !$noerr;
478
479 return undef;
480 }
481
482 sub check_user_enabled {
483 my ($usercfg, $username, $noerr) = @_;
484
485 my $data = check_user_exist($usercfg, $username, $noerr);
486 return undef if !$data;
487
488 return 1 if $data->{enable};
489
490 die "user '$username' is disabled\n" if !$noerr;
491
492 return undef;
493 }
494
495 sub verify_one_time_pw {
496 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
497
498 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
499
500 # fixme: proxy support?
501 my $proxy;
502
503 if ($type eq 'yubico') {
504 PVE::OTP::yubico_verify_otp($otp, $keys, $tfa_cfg->{url},
505 $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
506 } elsif ($type eq 'oath') {
507 PVE::OTP::oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
508 } else {
509 die "unknown tfa type '$type'\n";
510 }
511 }
512
513 # password should be utf8 encoded
514 # Note: some plugins delay/sleep if auth fails
515 sub authenticate_user {
516 my ($username, $password, $otp) = @_;
517
518 die "no username specified\n" if !$username;
519
520 my ($ruid, $realm);
521
522 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
523
524 my $usercfg = cfs_read_file('user.cfg');
525
526 check_user_enabled($usercfg, $username);
527
528 my $ctime = time();
529 my $expire = $usercfg->{users}->{$username}->{expire};
530
531 die "account expired\n" if $expire && ($expire < $ctime);
532
533 my $domain_cfg = cfs_read_file('domains.cfg');
534
535 my $cfg = $domain_cfg->{ids}->{$realm};
536 die "auth domain '$realm' does not exists\n" if !$cfg;
537 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
538 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
539
540 my ($type, $tfa_data) = user_get_tfa($username, $realm);
541 if ($type) {
542 if ($type eq 'u2f') {
543 # Note that if the user did not manage to complete the initial u2f registration
544 # challenge we have a hash containing a 'challenge' entry in the user's tfa.cfg entry:
545 $tfa_data = undef if exists $tfa_data->{challenge};
546 } elsif (!defined($otp)) {
547 # The user requires a 2nd factor but has not provided one. Return success but
548 # don't clear $tfa_data.
549 } else {
550 my $keys = $tfa_data->{keys};
551 my $tfa_cfg = $tfa_data->{config};
552 verify_one_time_pw($type, $username, $keys, $tfa_cfg, $otp);
553 $tfa_data = undef;
554 }
555
556 # Return the type along with the rest:
557 if ($tfa_data) {
558 $tfa_data = {
559 type => $type,
560 data => $tfa_data,
561 };
562 }
563 }
564
565 return wantarray ? ($username, $tfa_data) : $username;
566 }
567
568 sub domain_set_password {
569 my ($realm, $username, $password) = @_;
570
571 die "no auth domain specified" if !$realm;
572
573 my $domain_cfg = cfs_read_file('domains.cfg');
574
575 my $cfg = $domain_cfg->{ids}->{$realm};
576 die "auth domain '$realm' does not exist\n" if !$cfg;
577 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
578 $plugin->store_password($cfg, $realm, $username, $password);
579 }
580
581 sub add_user_group {
582 my ($username, $usercfg, $group) = @_;
583
584 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
585 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
586 }
587
588 sub delete_user_group {
589 my ($username, $usercfg) = @_;
590
591 foreach my $group (keys %{$usercfg->{groups}}) {
592
593 delete ($usercfg->{groups}->{$group}->{users}->{$username})
594 if $usercfg->{groups}->{$group}->{users}->{$username};
595 }
596 }
597
598 sub delete_user_acl {
599 my ($username, $usercfg) = @_;
600
601 foreach my $acl (keys %{$usercfg->{acl}}) {
602
603 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
604 if $usercfg->{acl}->{$acl}->{users}->{$username};
605 }
606 }
607
608 sub delete_group_acl {
609 my ($group, $usercfg) = @_;
610
611 foreach my $acl (keys %{$usercfg->{acl}}) {
612
613 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
614 if $usercfg->{acl}->{$acl}->{groups}->{$group};
615 }
616 }
617
618 sub delete_pool_acl {
619 my ($pool, $usercfg) = @_;
620
621 my $path = "/pool/$pool";
622
623 delete ($usercfg->{acl}->{$path})
624 }
625
626 # we automatically create some predefined roles by splitting privs
627 # into 3 groups (per category)
628 # root: only root is allowed to do that
629 # admin: an administrator can to that
630 # user: a normal user/customer can to that
631 my $privgroups = {
632 VM => {
633 root => [],
634 admin => [
635 'VM.Config.Disk',
636 'VM.Config.CPU',
637 'VM.Config.Memory',
638 'VM.Config.Network',
639 'VM.Config.HWType',
640 'VM.Config.Options', # covers all other things
641 'VM.Allocate',
642 'VM.Clone',
643 'VM.Migrate',
644 'VM.Monitor',
645 'VM.Snapshot',
646 'VM.Snapshot.Rollback',
647 ],
648 user => [
649 'VM.Config.CDROM', # change CDROM media
650 'VM.Console',
651 'VM.Backup',
652 'VM.PowerMgmt',
653 ],
654 audit => [
655 'VM.Audit',
656 ],
657 },
658 Sys => {
659 root => [
660 'Sys.PowerMgmt',
661 'Sys.Modify', # edit/change node settings
662 ],
663 admin => [
664 'Permissions.Modify',
665 'Sys.Console',
666 'Sys.Syslog',
667 ],
668 user => [],
669 audit => [
670 'Sys.Audit',
671 ],
672 },
673 Datastore => {
674 root => [],
675 admin => [
676 'Datastore.Allocate',
677 'Datastore.AllocateTemplate',
678 ],
679 user => [
680 'Datastore.AllocateSpace',
681 ],
682 audit => [
683 'Datastore.Audit',
684 ],
685 },
686 SDN => {
687 root => [],
688 admin => [
689 'SDN.Allocate',
690 'SDN.Audit',
691 ],
692 audit => [
693 'SDN.Audit',
694 ],
695 },
696 User => {
697 root => [
698 'Realm.Allocate',
699 ],
700 admin => [
701 'User.Modify',
702 'Group.Allocate', # edit/change group settings
703 'Realm.AllocateUser',
704 ],
705 user => [],
706 audit => [],
707 },
708 Pool => {
709 root => [],
710 admin => [
711 'Pool.Allocate', # create/delete pools
712 ],
713 user => [],
714 audit => [],
715 },
716 };
717
718 my $valid_privs = {};
719
720 my $special_roles = {
721 'NoAccess' => {}, # no privileges
722 'Administrator' => $valid_privs, # all privileges
723 };
724
725 sub create_roles {
726
727 foreach my $cat (keys %$privgroups) {
728 my $cd = $privgroups->{$cat};
729 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
730 @{$cd->{user}}, @{$cd->{audit}}) {
731 $valid_privs->{$p} = 1;
732 }
733 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
734
735 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
736 $special_roles->{"PVEAdmin"}->{$p} = 1;
737 }
738 if (scalar(@{$cd->{user}})) {
739 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
740 $special_roles->{"PVE${cat}User"}->{$p} = 1;
741 }
742 }
743 foreach my $p (@{$cd->{audit}}) {
744 $special_roles->{"PVEAuditor"}->{$p} = 1;
745 }
746 }
747
748 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
749 };
750
751 create_roles();
752
753 sub create_priv_properties {
754 my $properties = {};
755 foreach my $priv (keys %$valid_privs) {
756 $properties->{$priv} = {
757 type => 'boolean',
758 optional => 1,
759 };
760 }
761 return $properties;
762 }
763
764 sub role_is_special {
765 my ($role) = @_;
766 return (exists $special_roles->{$role}) ? 1 : 0;
767 }
768
769 sub add_role_privs {
770 my ($role, $usercfg, $privs) = @_;
771
772 return if !$privs;
773
774 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
775
776 foreach my $priv (split_list($privs)) {
777 if (defined ($valid_privs->{$priv})) {
778 $usercfg->{roles}->{$role}->{$priv} = 1;
779 } else {
780 die "invalid privilege '$priv'\n";
781 }
782 }
783 }
784
785 sub normalize_path {
786 my $path = shift;
787
788 $path =~ s|/+|/|g;
789
790 $path =~ s|/$||;
791
792 $path = '/' if !$path;
793
794 $path = "/$path" if $path !~ m|^/|;
795
796 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
797
798 return $path;
799 }
800
801 PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
802 sub verify_groupname {
803 my ($groupname, $noerr) = @_;
804
805 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
806
807 die "group name '$groupname' contains invalid characters\n" if !$noerr;
808
809 return undef;
810 }
811
812 return $groupname;
813 }
814
815 PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
816 sub verify_rolename {
817 my ($rolename, $noerr) = @_;
818
819 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
820
821 die "role name '$rolename' contains invalid characters\n" if !$noerr;
822
823 return undef;
824 }
825
826 return $rolename;
827 }
828
829 PVE::JSONSchema::register_format('pve-poolid', \&verify_poolname);
830 sub verify_poolname {
831 my ($poolname, $noerr) = @_;
832
833 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
834
835 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
836
837 return undef;
838 }
839
840 return $poolname;
841 }
842
843 PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
844 sub verify_privname {
845 my ($priv, $noerr) = @_;
846
847 if (!$valid_privs->{$priv}) {
848 die "invalid privilege '$priv'\n" if !$noerr;
849
850 return undef;
851 }
852
853 return $priv;
854 }
855
856 sub userconfig_force_defaults {
857 my ($cfg) = @_;
858
859 foreach my $r (keys %$special_roles) {
860 $cfg->{roles}->{$r} = $special_roles->{$r};
861 }
862
863 # add root user if not exists
864 if (!$cfg->{users}->{'root@pam'}) {
865 $cfg->{users}->{'root@pam'}->{enable} = 1;
866 }
867 }
868
869 sub parse_user_config {
870 my ($filename, $raw) = @_;
871
872 my $cfg = {};
873
874 userconfig_force_defaults($cfg);
875
876 $raw = '' if !defined($raw);
877 while ($raw =~ /^\s*(.+?)\s*$/gm) {
878 my $line = $1;
879 my @data;
880
881 foreach my $d (split (/:/, $line)) {
882 $d =~ s/^\s+//;
883 $d =~ s/\s+$//;
884 push @data, $d
885 }
886
887 my $et = shift @data;
888
889 if ($et eq 'user') {
890 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
891
892 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
893 if (!$realm) {
894 warn "user config - ignore user '$user' - invalid user name\n";
895 next;
896 }
897
898 $enable = $enable ? 1 : 0;
899
900 $expire = 0 if !$expire;
901
902 if ($expire !~ m/^\d+$/) {
903 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
904 next;
905 }
906 $expire = int($expire);
907
908 #if (!verify_groupname ($group, 1)) {
909 # warn "user config - ignore user '$user' - invalid characters in group name\n";
910 # next;
911 #}
912
913 $cfg->{users}->{$user} = {
914 enable => $enable,
915 # group => $group,
916 };
917 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
918 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
919 $cfg->{users}->{$user}->{email} = $email;
920 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
921 $cfg->{users}->{$user}->{expire} = $expire;
922 # keys: allowed yubico key ids or oath secrets (base32 encoded)
923 $cfg->{users}->{$user}->{keys} = $keys if $keys;
924
925 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
926 #$cfg->{groups}->{$group}->{$user} = 1;
927
928 } elsif ($et eq 'group') {
929 my ($group, $userlist, $comment) = @data;
930
931 if (!verify_groupname($group, 1)) {
932 warn "user config - ignore group '$group' - invalid characters in group name\n";
933 next;
934 }
935
936 # make sure to add the group (even if there are no members)
937 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
938
939 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
940
941 foreach my $user (split_list($userlist)) {
942
943 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
944 warn "user config - ignore invalid group member '$user'\n";
945 next;
946 }
947
948 if ($cfg->{users}->{$user}) { # user exists
949 $cfg->{users}->{$user}->{groups}->{$group} = 1;
950 $cfg->{groups}->{$group}->{users}->{$user} = 1;
951 } else {
952 warn "user config - ignore invalid group member '$user'\n";
953 }
954 }
955
956 } elsif ($et eq 'role') {
957 my ($role, $privlist) = @data;
958
959 if (!verify_rolename($role, 1)) {
960 warn "user config - ignore role '$role' - invalid characters in role name\n";
961 next;
962 }
963
964 # make sure to add the role (even if there are no privileges)
965 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
966
967 foreach my $priv (split_list($privlist)) {
968 if (defined ($valid_privs->{$priv})) {
969 $cfg->{roles}->{$role}->{$priv} = 1;
970 } else {
971 warn "user config - ignore invalid priviledge '$priv'\n";
972 }
973 }
974
975 } elsif ($et eq 'acl') {
976 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
977
978 $propagate = $propagate ? 1 : 0;
979
980 if (my $path = normalize_path($pathtxt)) {
981 foreach my $role (split_list($rolelist)) {
982
983 if (!verify_rolename($role, 1)) {
984 warn "user config - ignore invalid role name '$role' in acl\n";
985 next;
986 }
987
988 foreach my $ug (split_list($uglist)) {
989 my ($group) = $ug =~ m/^@(\S+)$/;
990
991 if ($group && verify_groupname($group, 1)) {
992 if ($cfg->{groups}->{$group}) { # group exists
993 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
994 } else {
995 warn "user config - ignore invalid acl group '$group'\n";
996 }
997 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
998 if ($cfg->{users}->{$ug}) { # user exists
999 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
1000 } else {
1001 warn "user config - ignore invalid acl member '$ug'\n";
1002 }
1003 } else {
1004 warn "user config - invalid user/group '$ug' in acl\n";
1005 }
1006 }
1007 }
1008 } else {
1009 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1010 }
1011 } elsif ($et eq 'pool') {
1012 my ($pool, $comment, $vmlist, $storelist) = @data;
1013
1014 if (!verify_poolname($pool, 1)) {
1015 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1016 next;
1017 }
1018
1019 # make sure to add the pool (even if there are no members)
1020 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
1021
1022 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1023
1024 foreach my $vmid (split_list($vmlist)) {
1025 if ($vmid !~ m/^\d+$/) {
1026 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1027 next;
1028 }
1029 $vmid = int($vmid);
1030
1031 if ($cfg->{vms}->{$vmid}) {
1032 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1033 next;
1034 }
1035
1036 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
1037
1038 # record vmid ==> pool relation
1039 $cfg->{vms}->{$vmid} = $pool;
1040 }
1041
1042 foreach my $storeid (split_list($storelist)) {
1043 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1044 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1045 next;
1046 }
1047 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
1048 }
1049 } else {
1050 warn "user config - ignore config line: $line\n";
1051 }
1052 }
1053
1054 userconfig_force_defaults($cfg);
1055
1056 return $cfg;
1057 }
1058
1059 sub write_user_config {
1060 my ($filename, $cfg) = @_;
1061
1062 my $data = '';
1063
1064 foreach my $user (sort keys %{$cfg->{users}}) {
1065 my $d = $cfg->{users}->{$user};
1066 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1067 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1068 my $email = $d->{email} || '';
1069 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1070 my $expire = int($d->{expire} || 0);
1071 my $enable = $d->{enable} ? 1 : 0;
1072 my $keys = $d->{keys} ? $d->{keys} : '';
1073 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1074 }
1075
1076 $data .= "\n";
1077
1078 foreach my $group (sort keys %{$cfg->{groups}}) {
1079 my $d = $cfg->{groups}->{$group};
1080 my $list = join (',', sort keys %{$d->{users}});
1081 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1082 $data .= "group:$group:$list:$comment:\n";
1083 }
1084
1085 $data .= "\n";
1086
1087 foreach my $pool (sort keys %{$cfg->{pools}}) {
1088 my $d = $cfg->{pools}->{$pool};
1089 my $vmlist = join (',', sort keys %{$d->{vms}});
1090 my $storelist = join (',', sort keys %{$d->{storage}});
1091 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1092 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1093 }
1094
1095 $data .= "\n";
1096
1097 foreach my $role (sort keys %{$cfg->{roles}}) {
1098 next if $special_roles->{$role};
1099
1100 my $d = $cfg->{roles}->{$role};
1101 my $list = join (',', sort keys %$d);
1102 $data .= "role:$role:$list:\n";
1103 }
1104
1105 $data .= "\n";
1106
1107 foreach my $path (sort keys %{$cfg->{acl}}) {
1108 my $d = $cfg->{acl}->{$path};
1109
1110 my $ra = {};
1111
1112 foreach my $group (keys %{$d->{groups}}) {
1113 my $l0 = '';
1114 my $l1 = '';
1115 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
1116 my $propagate = $d->{groups}->{$group}->{$role};
1117 if ($propagate) {
1118 $l1 .= ',' if $l1;
1119 $l1 .= $role;
1120 } else {
1121 $l0 .= ',' if $l0;
1122 $l0 .= $role;
1123 }
1124 }
1125 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
1126 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
1127 }
1128
1129 foreach my $user (keys %{$d->{users}}) {
1130 # no need to save, because root is always 'Administrator'
1131 next if $user eq 'root@pam';
1132
1133 my $l0 = '';
1134 my $l1 = '';
1135 foreach my $role (sort keys %{$d->{users}->{$user}}) {
1136 my $propagate = $d->{users}->{$user}->{$role};
1137 if ($propagate) {
1138 $l1 .= ',' if $l1;
1139 $l1 .= $role;
1140 } else {
1141 $l0 .= ',' if $l0;
1142 $l0 .= $role;
1143 }
1144 }
1145 $ra->{0}->{$l0}->{$user} = 1 if $l0;
1146 $ra->{1}->{$l1}->{$user} = 1 if $l1;
1147 }
1148
1149 foreach my $rolelist (sort keys %{$ra->{0}}) {
1150 my $uglist = join (',', sort keys %{$ra->{0}->{$rolelist}});
1151 $data .= "acl:0:$path:$uglist:$rolelist:\n";
1152 }
1153 foreach my $rolelist (sort keys %{$ra->{1}}) {
1154 my $uglist = join (',', sort keys %{$ra->{1}->{$rolelist}});
1155 $data .= "acl:1:$path:$uglist:$rolelist:\n";
1156 }
1157 }
1158
1159 return $data;
1160 }
1161
1162 # The TFA configuration in priv/tfa.cfg format contains one line per user of
1163 # the form:
1164 # USER:TYPE:DATA
1165 # DATA is a base64 encoded json string and its format depends on the type.
1166 sub parse_priv_tfa_config {
1167 my ($filename, $raw) = @_;
1168
1169 my $users = {};
1170 my $cfg = { users => $users };
1171
1172 $raw = '' if !defined($raw);
1173 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1174 my $line = $1;
1175 my ($user, $type, $data) = split(/:/, $line, 3);
1176
1177 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1178 if (!$realm) {
1179 warn "user tfa config - ignore user '$user' - invalid user name\n";
1180 next;
1181 }
1182
1183 $data = decode_json(decode_base64($data));
1184
1185 $users->{$user} = {
1186 type => $type,
1187 data => $data,
1188 };
1189 }
1190
1191 return $cfg;
1192 }
1193
1194 sub write_priv_tfa_config {
1195 my ($filename, $cfg) = @_;
1196
1197 my $output = '';
1198
1199 my $users = $cfg->{users};
1200 foreach my $user (sort keys %$users) {
1201 my $info = $users->{$user};
1202 next if !%$info; # skip empty entries
1203
1204 $info = {%$info}; # copy to verify contents:
1205
1206 my $type = delete $info->{type};
1207 my $data = delete $info->{data};
1208
1209 if (my @keys = keys %$info) {
1210 die "invalid keys in TFA config for user $user: " . join(', ', @keys) . "\n";
1211 }
1212
1213 $data = encode_base64(encode_json($data), '');
1214 $output .= "${user}:${type}:${data}\n";
1215 }
1216
1217 return $output;
1218 }
1219
1220 sub roles {
1221 my ($cfg, $user, $path) = @_;
1222
1223 # NOTE: we do not consider pools here.
1224 # You need to use $rpcenv->roles() instead if you want that.
1225
1226 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1227
1228 my $perm = {};
1229
1230 foreach my $p (sort keys %{$cfg->{acl}}) {
1231 my $final = ($path eq $p);
1232
1233 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1234
1235 my $acl = $cfg->{acl}->{$p};
1236
1237 #print "CHECKACL $path $p\n";
1238 #print "ACL $path = " . Dumper ($acl);
1239
1240 if (my $ri = $acl->{users}->{$user}) {
1241 my $new;
1242 foreach my $role (keys %$ri) {
1243 my $propagate = $ri->{$role};
1244 if ($final || $propagate) {
1245 #print "APPLY ROLE $p $user $role\n";
1246 $new = {} if !$new;
1247 $new->{$role} = 1;
1248 }
1249 }
1250 if ($new) {
1251 $perm = $new; # overwrite previous settings
1252 next; # user privs always override group privs
1253 }
1254 }
1255
1256 my $new;
1257 foreach my $g (keys %{$acl->{groups}}) {
1258 next if !$cfg->{groups}->{$g}->{users}->{$user};
1259 if (my $ri = $acl->{groups}->{$g}) {
1260 foreach my $role (keys %$ri) {
1261 my $propagate = $ri->{$role};
1262 if ($final || $propagate) {
1263 #print "APPLY ROLE $p \@$g $role\n";
1264 $new = {} if !$new;
1265 $new->{$role} = 1;
1266 }
1267 }
1268 }
1269 }
1270 if ($new) {
1271 $perm = $new; # overwrite previous settings
1272 next;
1273 }
1274 }
1275
1276 return ('NoAccess') if defined ($perm->{NoAccess});
1277 #return () if defined ($perm->{NoAccess});
1278
1279 #print "permission $user $path = " . Dumper ($perm);
1280
1281 my @ra = keys %$perm;
1282
1283 #print "roles $user $path = " . join (',', @ra) . "\n";
1284
1285 return @ra;
1286 }
1287
1288 sub remove_vm_access {
1289 my ($vmid) = @_;
1290 my $delVMaccessFn = sub {
1291 my $usercfg = cfs_read_file("user.cfg");
1292 my $modified;
1293
1294 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1295 delete $usercfg->{acl}->{"/vms/$vmid"};
1296 $modified = 1;
1297 }
1298 if (my $pool = $usercfg->{vms}->{$vmid}) {
1299 if (my $data = $usercfg->{pools}->{$pool}) {
1300 delete $data->{vms}->{$vmid};
1301 delete $usercfg->{vms}->{$vmid};
1302 $modified = 1;
1303 }
1304 }
1305 cfs_write_file("user.cfg", $usercfg) if $modified;
1306 };
1307
1308 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1309 }
1310
1311 sub remove_storage_access {
1312 my ($storeid) = @_;
1313
1314 my $deleteStorageAccessFn = sub {
1315 my $usercfg = cfs_read_file("user.cfg");
1316 my $modified;
1317
1318 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1319 delete $usercfg->{acl}->{"/storage/$storeid"};
1320 $modified = 1;
1321 }
1322 foreach my $pool (keys %{$usercfg->{pools}}) {
1323 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1324 $modified = 1;
1325 }
1326 cfs_write_file("user.cfg", $usercfg) if $modified;
1327 };
1328
1329 lock_user_config($deleteStorageAccessFn,
1330 "access permissions cleanup for storage $storeid failed");
1331 }
1332
1333 sub add_vm_to_pool {
1334 my ($vmid, $pool) = @_;
1335
1336 my $addVMtoPoolFn = sub {
1337 my $usercfg = cfs_read_file("user.cfg");
1338 if (my $data = $usercfg->{pools}->{$pool}) {
1339 $data->{vms}->{$vmid} = 1;
1340 $usercfg->{vms}->{$vmid} = $pool;
1341 cfs_write_file("user.cfg", $usercfg);
1342 }
1343 };
1344
1345 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1346 }
1347
1348 sub remove_vm_from_pool {
1349 my ($vmid) = @_;
1350
1351 my $delVMfromPoolFn = sub {
1352 my $usercfg = cfs_read_file("user.cfg");
1353 if (my $pool = $usercfg->{vms}->{$vmid}) {
1354 if (my $data = $usercfg->{pools}->{$pool}) {
1355 delete $data->{vms}->{$vmid};
1356 delete $usercfg->{vms}->{$vmid};
1357 cfs_write_file("user.cfg", $usercfg);
1358 }
1359 }
1360 };
1361
1362 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1363 }
1364
1365 my $USER_CONTROLLED_TFA_TYPES = {
1366 u2f => 1,
1367 oath => 1,
1368 };
1369
1370 # Delete an entry by setting $data=undef in which case $type is ignored.
1371 # Otherwise both must be valid.
1372 sub user_set_tfa {
1373 my ($userid, $realm, $type, $data, $cached_usercfg, $cached_domaincfg) = @_;
1374
1375 if (defined($data) && !defined($type)) {
1376 # This is an internal usage error and should not happen
1377 die "cannot set tfa data without a type\n";
1378 }
1379
1380 my $user_cfg = $cached_usercfg || cfs_read_file('user.cfg');
1381 my $user = $user_cfg->{users}->{$userid}
1382 or die "user '$userid' not found\n";
1383
1384 my $domain_cfg = $cached_domaincfg || cfs_read_file('domains.cfg');
1385 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1386 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1387
1388 my $realm_tfa = $realm_cfg->{tfa};
1389 if (defined($realm_tfa)) {
1390 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa);
1391 # If the realm has a TFA setting, we're only allowed to use that.
1392 if (defined($data)) {
1393 my $required_type = $realm_tfa->{type};
1394 if ($required_type ne $type) {
1395 die "realm '$realm' only allows TFA of type '$required_type\n";
1396 }
1397
1398 if (defined($data->{config})) {
1399 # XXX: Is it enough if the type matches? Or should the configuration also match?
1400 }
1401
1402 # realm-configured tfa always uses a simple key list, so use the user.cfg
1403 $user->{keys} = $data->{keys};
1404 } else {
1405 die "realm '$realm' does not allow removing the 2nd factor\n";
1406 }
1407 } else {
1408 # Without a realm-enforced TFA setting the user can add a u2f or totp entry by themselves.
1409 # The 'yubico' type requires yubico server settings, which have to be configured on the
1410 # realm, so this is not supported here:
1411 die "domain '$realm' does not support TFA type '$type'\n"
1412 if defined($data) && !$USER_CONTROLLED_TFA_TYPES->{$type};
1413 }
1414
1415 # Custom TFA entries are stored in priv/tfa.cfg as they can be more complet: u2f uses a
1416 # public key and a key handle, TOTP requires the usual totp settings...
1417
1418 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1419 my $tfa = ($tfa_cfg->{users}->{$userid} //= {});
1420
1421 if (defined($data)) {
1422 $tfa->{type} = $type;
1423 $tfa->{data} = $data;
1424 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1425
1426 $user->{keys} = "x!$type";
1427 } else {
1428 delete $tfa_cfg->{users}->{$userid};
1429 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1430
1431 delete $user->{keys};
1432 }
1433
1434 cfs_write_file('user.cfg', $user_cfg);
1435 }
1436
1437 sub user_get_tfa {
1438 my ($username, $realm) = @_;
1439
1440 my $user_cfg = cfs_read_file('user.cfg');
1441 my $user = $user_cfg->{users}->{$username}
1442 or die "user '$username' not found\n";
1443
1444 my $keys = $user->{keys};
1445
1446 my $domain_cfg = cfs_read_file('domains.cfg');
1447 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1448 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1449
1450 my $realm_tfa = $realm_cfg->{tfa};
1451 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
1452 if $realm_tfa;
1453
1454 if (!$keys) {
1455 return if !$realm_tfa;
1456 die "missing required 2nd keys\n";
1457 }
1458
1459 # new style config starts with an 'x' and optionally contains a !<type> suffix
1460 if ($keys !~ /^x(?:!.*)?$/) {
1461 # old style config, find the type via the realm
1462 return if !$realm_tfa;
1463 return ($realm_tfa->{type}, {
1464 keys => $keys,
1465 config => $realm_tfa,
1466 });
1467 } else {
1468 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1469 my $tfa = $tfa_cfg->{users}->{$username};
1470 return if !$tfa; # should not happen (user.cfg wasn't cleaned up?)
1471
1472 if ($realm_tfa) {
1473 # if the realm has a tfa setting we need to verify the type:
1474 die "auth domain '$realm' and user have mismatching TFA settings\n"
1475 if $realm_tfa && $realm_tfa->{type} ne $tfa->{type};
1476 }
1477
1478 return ($tfa->{type}, $tfa->{data});
1479 }
1480 }
1481
1482 # bash completion helpers
1483
1484 register_standard_option('userid-completed',
1485 get_standard_option('userid', { completion => \&complete_username}),
1486 );
1487
1488 sub complete_username {
1489
1490 my $user_cfg = cfs_read_file('user.cfg');
1491
1492 return [ keys %{$user_cfg->{users}} ];
1493 }
1494
1495 sub complete_group {
1496
1497 my $user_cfg = cfs_read_file('user.cfg');
1498
1499 return [ keys %{$user_cfg->{groups}} ];
1500 }
1501
1502 sub complete_realm {
1503
1504 my $domain_cfg = cfs_read_file('domains.cfg');
1505
1506 return [ keys %{$domain_cfg->{ids}} ];
1507 }
1508
1509 1;