user.cfg: sort entries alphabetically in each section
[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 User => {
687 root => [
688 'Realm.Allocate',
689 ],
690 admin => [
691 'User.Modify',
692 'Group.Allocate', # edit/change group settings
693 'Realm.AllocateUser',
694 ],
695 user => [],
696 audit => [],
697 },
698 Pool => {
699 root => [],
700 admin => [
701 'Pool.Allocate', # create/delete pools
702 ],
703 user => [],
704 audit => [],
705 },
706 };
707
708 my $valid_privs = {};
709
710 my $special_roles = {
711 'NoAccess' => {}, # no privileges
712 'Administrator' => $valid_privs, # all privileges
713 };
714
715 sub create_roles {
716
717 foreach my $cat (keys %$privgroups) {
718 my $cd = $privgroups->{$cat};
719 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
720 @{$cd->{user}}, @{$cd->{audit}}) {
721 $valid_privs->{$p} = 1;
722 }
723 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
724
725 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
726 $special_roles->{"PVEAdmin"}->{$p} = 1;
727 }
728 if (scalar(@{$cd->{user}})) {
729 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
730 $special_roles->{"PVE${cat}User"}->{$p} = 1;
731 }
732 }
733 foreach my $p (@{$cd->{audit}}) {
734 $special_roles->{"PVEAuditor"}->{$p} = 1;
735 }
736 }
737
738 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
739 };
740
741 create_roles();
742
743 sub create_priv_properties {
744 my $properties = {};
745 foreach my $priv (keys %$valid_privs) {
746 $properties->{$priv} = {
747 type => 'boolean',
748 optional => 1,
749 };
750 }
751 return $properties;
752 }
753
754 sub role_is_special {
755 my ($role) = @_;
756 return (exists $special_roles->{$role}) ? 1 : 0;
757 }
758
759 sub add_role_privs {
760 my ($role, $usercfg, $privs) = @_;
761
762 return if !$privs;
763
764 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
765
766 foreach my $priv (split_list($privs)) {
767 if (defined ($valid_privs->{$priv})) {
768 $usercfg->{roles}->{$role}->{$priv} = 1;
769 } else {
770 die "invalid privilege '$priv'\n";
771 }
772 }
773 }
774
775 sub normalize_path {
776 my $path = shift;
777
778 $path =~ s|/+|/|g;
779
780 $path =~ s|/$||;
781
782 $path = '/' if !$path;
783
784 $path = "/$path" if $path !~ m|^/|;
785
786 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
787
788 return $path;
789 }
790
791 PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
792 sub verify_groupname {
793 my ($groupname, $noerr) = @_;
794
795 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
796
797 die "group name '$groupname' contains invalid characters\n" if !$noerr;
798
799 return undef;
800 }
801
802 return $groupname;
803 }
804
805 PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
806 sub verify_rolename {
807 my ($rolename, $noerr) = @_;
808
809 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
810
811 die "role name '$rolename' contains invalid characters\n" if !$noerr;
812
813 return undef;
814 }
815
816 return $rolename;
817 }
818
819 PVE::JSONSchema::register_format('pve-poolid', \&verify_poolname);
820 sub verify_poolname {
821 my ($poolname, $noerr) = @_;
822
823 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
824
825 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
826
827 return undef;
828 }
829
830 return $poolname;
831 }
832
833 PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
834 sub verify_privname {
835 my ($priv, $noerr) = @_;
836
837 if (!$valid_privs->{$priv}) {
838 die "invalid privilege '$priv'\n" if !$noerr;
839
840 return undef;
841 }
842
843 return $priv;
844 }
845
846 sub userconfig_force_defaults {
847 my ($cfg) = @_;
848
849 foreach my $r (keys %$special_roles) {
850 $cfg->{roles}->{$r} = $special_roles->{$r};
851 }
852
853 # add root user if not exists
854 if (!$cfg->{users}->{'root@pam'}) {
855 $cfg->{users}->{'root@pam'}->{enable} = 1;
856 }
857 }
858
859 sub parse_user_config {
860 my ($filename, $raw) = @_;
861
862 my $cfg = {};
863
864 userconfig_force_defaults($cfg);
865
866 $raw = '' if !defined($raw);
867 while ($raw =~ /^\s*(.+?)\s*$/gm) {
868 my $line = $1;
869 my @data;
870
871 foreach my $d (split (/:/, $line)) {
872 $d =~ s/^\s+//;
873 $d =~ s/\s+$//;
874 push @data, $d
875 }
876
877 my $et = shift @data;
878
879 if ($et eq 'user') {
880 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
881
882 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
883 if (!$realm) {
884 warn "user config - ignore user '$user' - invalid user name\n";
885 next;
886 }
887
888 $enable = $enable ? 1 : 0;
889
890 $expire = 0 if !$expire;
891
892 if ($expire !~ m/^\d+$/) {
893 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
894 next;
895 }
896 $expire = int($expire);
897
898 #if (!verify_groupname ($group, 1)) {
899 # warn "user config - ignore user '$user' - invalid characters in group name\n";
900 # next;
901 #}
902
903 $cfg->{users}->{$user} = {
904 enable => $enable,
905 # group => $group,
906 };
907 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
908 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
909 $cfg->{users}->{$user}->{email} = $email;
910 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
911 $cfg->{users}->{$user}->{expire} = $expire;
912 # keys: allowed yubico key ids or oath secrets (base32 encoded)
913 $cfg->{users}->{$user}->{keys} = $keys if $keys;
914
915 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
916 #$cfg->{groups}->{$group}->{$user} = 1;
917
918 } elsif ($et eq 'group') {
919 my ($group, $userlist, $comment) = @data;
920
921 if (!verify_groupname($group, 1)) {
922 warn "user config - ignore group '$group' - invalid characters in group name\n";
923 next;
924 }
925
926 # make sure to add the group (even if there are no members)
927 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
928
929 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
930
931 foreach my $user (split_list($userlist)) {
932
933 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
934 warn "user config - ignore invalid group member '$user'\n";
935 next;
936 }
937
938 if ($cfg->{users}->{$user}) { # user exists
939 $cfg->{users}->{$user}->{groups}->{$group} = 1;
940 $cfg->{groups}->{$group}->{users}->{$user} = 1;
941 } else {
942 warn "user config - ignore invalid group member '$user'\n";
943 }
944 }
945
946 } elsif ($et eq 'role') {
947 my ($role, $privlist) = @data;
948
949 if (!verify_rolename($role, 1)) {
950 warn "user config - ignore role '$role' - invalid characters in role name\n";
951 next;
952 }
953
954 # make sure to add the role (even if there are no privileges)
955 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
956
957 foreach my $priv (split_list($privlist)) {
958 if (defined ($valid_privs->{$priv})) {
959 $cfg->{roles}->{$role}->{$priv} = 1;
960 } else {
961 warn "user config - ignore invalid priviledge '$priv'\n";
962 }
963 }
964
965 } elsif ($et eq 'acl') {
966 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
967
968 if (my $path = normalize_path($pathtxt)) {
969 foreach my $role (split_list($rolelist)) {
970
971 if (!verify_rolename($role, 1)) {
972 warn "user config - ignore invalid role name '$role' in acl\n";
973 next;
974 }
975
976 foreach my $ug (split_list($uglist)) {
977 my ($group) = $ug =~ m/^@(\S+)$/;
978
979 if ($group && verify_groupname($group, 1)) {
980 if ($cfg->{groups}->{$group}) { # group exists
981 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
982 } else {
983 warn "user config - ignore invalid acl group '$group'\n";
984 }
985 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
986 if ($cfg->{users}->{$ug}) { # user exists
987 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
988 } else {
989 warn "user config - ignore invalid acl member '$ug'\n";
990 }
991 } else {
992 warn "user config - invalid user/group '$ug' in acl\n";
993 }
994 }
995 }
996 } else {
997 warn "user config - ignore invalid path in acl '$pathtxt'\n";
998 }
999 } elsif ($et eq 'pool') {
1000 my ($pool, $comment, $vmlist, $storelist) = @data;
1001
1002 if (!verify_poolname($pool, 1)) {
1003 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1004 next;
1005 }
1006
1007 # make sure to add the pool (even if there are no members)
1008 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
1009
1010 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1011
1012 foreach my $vmid (split_list($vmlist)) {
1013 if ($vmid !~ m/^\d+$/) {
1014 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1015 next;
1016 }
1017 $vmid = int($vmid);
1018
1019 if ($cfg->{vms}->{$vmid}) {
1020 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1021 next;
1022 }
1023
1024 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
1025
1026 # record vmid ==> pool relation
1027 $cfg->{vms}->{$vmid} = $pool;
1028 }
1029
1030 foreach my $storeid (split_list($storelist)) {
1031 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1032 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1033 next;
1034 }
1035 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
1036 }
1037 } else {
1038 warn "user config - ignore config line: $line\n";
1039 }
1040 }
1041
1042 userconfig_force_defaults($cfg);
1043
1044 return $cfg;
1045 }
1046
1047 sub write_user_config {
1048 my ($filename, $cfg) = @_;
1049
1050 my $data = '';
1051
1052 foreach my $user (sort keys %{$cfg->{users}}) {
1053 my $d = $cfg->{users}->{$user};
1054 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1055 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1056 my $email = $d->{email} || '';
1057 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1058 my $expire = int($d->{expire} || 0);
1059 my $enable = $d->{enable} ? 1 : 0;
1060 my $keys = $d->{keys} ? $d->{keys} : '';
1061 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1062 }
1063
1064 $data .= "\n";
1065
1066 foreach my $group (sort keys %{$cfg->{groups}}) {
1067 my $d = $cfg->{groups}->{$group};
1068 my $list = join (',', keys %{$d->{users}});
1069 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1070 $data .= "group:$group:$list:$comment:\n";
1071 }
1072
1073 $data .= "\n";
1074
1075 foreach my $pool (sort keys %{$cfg->{pools}}) {
1076 my $d = $cfg->{pools}->{$pool};
1077 my $vmlist = join (',', keys %{$d->{vms}});
1078 my $storelist = join (',', keys %{$d->{storage}});
1079 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1080 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1081 }
1082
1083 $data .= "\n";
1084
1085 foreach my $role (sort keys %{$cfg->{roles}}) {
1086 next if $special_roles->{$role};
1087
1088 my $d = $cfg->{roles}->{$role};
1089 my $list = join (',', keys %$d);
1090 $data .= "role:$role:$list:\n";
1091 }
1092
1093 $data .= "\n";
1094
1095 foreach my $path (sort keys %{$cfg->{acl}}) {
1096 my $d = $cfg->{acl}->{$path};
1097
1098 my $ra = {};
1099
1100 foreach my $group (keys %{$d->{groups}}) {
1101 my $l0 = '';
1102 my $l1 = '';
1103 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
1104 my $propagate = $d->{groups}->{$group}->{$role};
1105 if ($propagate) {
1106 $l1 .= ',' if $l1;
1107 $l1 .= $role;
1108 } else {
1109 $l0 .= ',' if $l0;
1110 $l0 .= $role;
1111 }
1112 }
1113 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
1114 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
1115 }
1116
1117 foreach my $user (keys %{$d->{users}}) {
1118 # no need to save, because root is always 'Administrator'
1119 next if $user eq 'root@pam';
1120
1121 my $l0 = '';
1122 my $l1 = '';
1123 foreach my $role (sort keys %{$d->{users}->{$user}}) {
1124 my $propagate = $d->{users}->{$user}->{$role};
1125 if ($propagate) {
1126 $l1 .= ',' if $l1;
1127 $l1 .= $role;
1128 } else {
1129 $l0 .= ',' if $l0;
1130 $l0 .= $role;
1131 }
1132 }
1133 $ra->{0}->{$l0}->{$user} = 1 if $l0;
1134 $ra->{1}->{$l1}->{$user} = 1 if $l1;
1135 }
1136
1137 foreach my $rolelist (sort keys %{$ra->{0}}) {
1138 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
1139 $data .= "acl:0:$path:$uglist:$rolelist:\n";
1140 }
1141 foreach my $rolelist (sort keys %{$ra->{1}}) {
1142 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
1143 $data .= "acl:1:$path:$uglist:$rolelist:\n";
1144 }
1145 }
1146
1147 return $data;
1148 }
1149
1150 # The TFA configuration in priv/tfa.cfg format contains one line per user of
1151 # the form:
1152 # USER:TYPE:DATA
1153 # DATA is a base64 encoded json string and its format depends on the type.
1154 sub parse_priv_tfa_config {
1155 my ($filename, $raw) = @_;
1156
1157 my $users = {};
1158 my $cfg = { users => $users };
1159
1160 $raw = '' if !defined($raw);
1161 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1162 my $line = $1;
1163 my ($user, $type, $data) = split(/:/, $line, 3);
1164
1165 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1166 if (!$realm) {
1167 warn "user tfa config - ignore user '$user' - invalid user name\n";
1168 next;
1169 }
1170
1171 $data = decode_json(decode_base64($data));
1172
1173 $users->{$user} = {
1174 type => $type,
1175 data => $data,
1176 };
1177 }
1178
1179 return $cfg;
1180 }
1181
1182 sub write_priv_tfa_config {
1183 my ($filename, $cfg) = @_;
1184
1185 my $output = '';
1186
1187 my $users = $cfg->{users};
1188 foreach my $user (sort keys %$users) {
1189 my $info = $users->{$user};
1190 next if !%$info; # skip empty entries
1191
1192 $info = {%$info}; # copy to verify contents:
1193
1194 my $type = delete $info->{type};
1195 my $data = delete $info->{data};
1196
1197 if (my @keys = keys %$info) {
1198 die "invalid keys in TFA config for user $user: " . join(', ', @keys) . "\n";
1199 }
1200
1201 $data = encode_base64(encode_json($data), '');
1202 $output .= "${user}:${type}:${data}\n";
1203 }
1204
1205 return $output;
1206 }
1207
1208 sub roles {
1209 my ($cfg, $user, $path) = @_;
1210
1211 # NOTE: we do not consider pools here.
1212 # You need to use $rpcenv->roles() instead if you want that.
1213
1214 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1215
1216 my $perm = {};
1217
1218 foreach my $p (sort keys %{$cfg->{acl}}) {
1219 my $final = ($path eq $p);
1220
1221 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1222
1223 my $acl = $cfg->{acl}->{$p};
1224
1225 #print "CHECKACL $path $p\n";
1226 #print "ACL $path = " . Dumper ($acl);
1227
1228 if (my $ri = $acl->{users}->{$user}) {
1229 my $new;
1230 foreach my $role (keys %$ri) {
1231 my $propagate = $ri->{$role};
1232 if ($final || $propagate) {
1233 #print "APPLY ROLE $p $user $role\n";
1234 $new = {} if !$new;
1235 $new->{$role} = 1;
1236 }
1237 }
1238 if ($new) {
1239 $perm = $new; # overwrite previous settings
1240 next; # user privs always override group privs
1241 }
1242 }
1243
1244 my $new;
1245 foreach my $g (keys %{$acl->{groups}}) {
1246 next if !$cfg->{groups}->{$g}->{users}->{$user};
1247 if (my $ri = $acl->{groups}->{$g}) {
1248 foreach my $role (keys %$ri) {
1249 my $propagate = $ri->{$role};
1250 if ($final || $propagate) {
1251 #print "APPLY ROLE $p \@$g $role\n";
1252 $new = {} if !$new;
1253 $new->{$role} = 1;
1254 }
1255 }
1256 }
1257 }
1258 if ($new) {
1259 $perm = $new; # overwrite previous settings
1260 next;
1261 }
1262 }
1263
1264 return ('NoAccess') if defined ($perm->{NoAccess});
1265 #return () if defined ($perm->{NoAccess});
1266
1267 #print "permission $user $path = " . Dumper ($perm);
1268
1269 my @ra = keys %$perm;
1270
1271 #print "roles $user $path = " . join (',', @ra) . "\n";
1272
1273 return @ra;
1274 }
1275
1276 sub permission {
1277 my ($cfg, $user, $path) = @_;
1278
1279 $user = PVE::Auth::Plugin::verify_username($user, 1);
1280 return {} if !$user;
1281
1282 my @ra = roles($cfg, $user, $path);
1283
1284 my $privs = {};
1285
1286 foreach my $role (@ra) {
1287 if (my $privset = $cfg->{roles}->{$role}) {
1288 foreach my $p (keys %$privset) {
1289 $privs->{$p} = 1;
1290 }
1291 }
1292 }
1293
1294 #print "priviledges $user $path = " . Dumper ($privs);
1295
1296 return $privs;
1297 }
1298
1299 sub check_permissions {
1300 my ($username, $path, $privlist) = @_;
1301
1302 $path = normalize_path($path);
1303 my $usercfg = cfs_read_file('user.cfg');
1304 my $perm = permission($usercfg, $username, $path);
1305
1306 foreach my $priv (split_list($privlist)) {
1307 return undef if !$perm->{$priv};
1308 };
1309
1310 return 1;
1311 }
1312
1313 sub remove_vm_access {
1314 my ($vmid) = @_;
1315 my $delVMaccessFn = sub {
1316 my $usercfg = cfs_read_file("user.cfg");
1317 my $modified;
1318
1319 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1320 delete $usercfg->{acl}->{"/vms/$vmid"};
1321 $modified = 1;
1322 }
1323 if (my $pool = $usercfg->{vms}->{$vmid}) {
1324 if (my $data = $usercfg->{pools}->{$pool}) {
1325 delete $data->{vms}->{$vmid};
1326 delete $usercfg->{vms}->{$vmid};
1327 $modified = 1;
1328 }
1329 }
1330 cfs_write_file("user.cfg", $usercfg) if $modified;
1331 };
1332
1333 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1334 }
1335
1336 sub remove_storage_access {
1337 my ($storeid) = @_;
1338
1339 my $deleteStorageAccessFn = sub {
1340 my $usercfg = cfs_read_file("user.cfg");
1341 my $modified;
1342
1343 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1344 delete $usercfg->{acl}->{"/storage/$storeid"};
1345 $modified = 1;
1346 }
1347 foreach my $pool (keys %{$usercfg->{pools}}) {
1348 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1349 $modified = 1;
1350 }
1351 cfs_write_file("user.cfg", $usercfg) if $modified;
1352 };
1353
1354 lock_user_config($deleteStorageAccessFn,
1355 "access permissions cleanup for storage $storeid failed");
1356 }
1357
1358 sub add_vm_to_pool {
1359 my ($vmid, $pool) = @_;
1360
1361 my $addVMtoPoolFn = sub {
1362 my $usercfg = cfs_read_file("user.cfg");
1363 if (my $data = $usercfg->{pools}->{$pool}) {
1364 $data->{vms}->{$vmid} = 1;
1365 $usercfg->{vms}->{$vmid} = $pool;
1366 cfs_write_file("user.cfg", $usercfg);
1367 }
1368 };
1369
1370 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1371 }
1372
1373 sub remove_vm_from_pool {
1374 my ($vmid) = @_;
1375
1376 my $delVMfromPoolFn = sub {
1377 my $usercfg = cfs_read_file("user.cfg");
1378 if (my $pool = $usercfg->{vms}->{$vmid}) {
1379 if (my $data = $usercfg->{pools}->{$pool}) {
1380 delete $data->{vms}->{$vmid};
1381 delete $usercfg->{vms}->{$vmid};
1382 cfs_write_file("user.cfg", $usercfg);
1383 }
1384 }
1385 };
1386
1387 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1388 }
1389
1390 my $USER_CONTROLLED_TFA_TYPES = {
1391 u2f => 1,
1392 oath => 1,
1393 };
1394
1395 # Delete an entry by setting $data=undef in which case $type is ignored.
1396 # Otherwise both must be valid.
1397 sub user_set_tfa {
1398 my ($userid, $realm, $type, $data, $cached_usercfg, $cached_domaincfg) = @_;
1399
1400 if (defined($data) && !defined($type)) {
1401 # This is an internal usage error and should not happen
1402 die "cannot set tfa data without a type\n";
1403 }
1404
1405 my $user_cfg = $cached_usercfg || cfs_read_file('user.cfg');
1406 my $user = $user_cfg->{users}->{$userid}
1407 or die "user '$userid' not found\n";
1408
1409 my $domain_cfg = $cached_domaincfg || cfs_read_file('domains.cfg');
1410 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1411 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1412
1413 my $realm_tfa = $realm_cfg->{tfa};
1414 if (defined($realm_tfa)) {
1415 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa);
1416 # If the realm has a TFA setting, we're only allowed to use that.
1417 if (defined($data)) {
1418 my $required_type = $realm_tfa->{type};
1419 if ($required_type ne $type) {
1420 die "realm '$realm' only allows TFA of type '$required_type\n";
1421 }
1422
1423 if (defined($data->{config})) {
1424 # XXX: Is it enough if the type matches? Or should the configuration also match?
1425 }
1426
1427 # realm-configured tfa always uses a simple key list, so use the user.cfg
1428 $user->{keys} = $data->{keys};
1429 } else {
1430 die "realm '$realm' does not allow removing the 2nd factor\n";
1431 }
1432 } else {
1433 # Without a realm-enforced TFA setting the user can add a u2f or totp entry by themselves.
1434 # The 'yubico' type requires yubico server settings, which have to be configured on the
1435 # realm, so this is not supported here:
1436 die "domain '$realm' does not support TFA type '$type'\n"
1437 if defined($data) && !$USER_CONTROLLED_TFA_TYPES->{$type};
1438 }
1439
1440 # Custom TFA entries are stored in priv/tfa.cfg as they can be more complet: u2f uses a
1441 # public key and a key handle, TOTP requires the usual totp settings...
1442
1443 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1444 my $tfa = ($tfa_cfg->{users}->{$userid} //= {});
1445
1446 if (defined($data)) {
1447 $tfa->{type} = $type;
1448 $tfa->{data} = $data;
1449 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1450
1451 $user->{keys} = "x!$type";
1452 } else {
1453 delete $tfa_cfg->{users}->{$userid};
1454 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1455
1456 delete $user->{keys};
1457 }
1458
1459 cfs_write_file('user.cfg', $user_cfg);
1460 }
1461
1462 sub user_get_tfa {
1463 my ($username, $realm) = @_;
1464
1465 my $user_cfg = cfs_read_file('user.cfg');
1466 my $user = $user_cfg->{users}->{$username}
1467 or die "user '$username' not found\n";
1468
1469 my $keys = $user->{keys};
1470
1471 my $domain_cfg = cfs_read_file('domains.cfg');
1472 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1473 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1474
1475 my $realm_tfa = $realm_cfg->{tfa};
1476 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
1477 if $realm_tfa;
1478
1479 if (!$keys) {
1480 return if !$realm_tfa;
1481 die "missing required 2nd keys\n";
1482 }
1483
1484 # new style config starts with an 'x' and optionally contains a !<type> suffix
1485 if ($keys !~ /^x(?:!.*)?$/) {
1486 # old style config, find the type via the realm
1487 return if !$realm_tfa;
1488 return ($realm_tfa->{type}, {
1489 keys => $keys,
1490 config => $realm_tfa,
1491 });
1492 } else {
1493 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1494 my $tfa = $tfa_cfg->{users}->{$username};
1495 return if !$tfa; # should not happen (user.cfg wasn't cleaned up?)
1496
1497 if ($realm_tfa) {
1498 # if the realm has a tfa setting we need to verify the type:
1499 die "auth domain '$realm' and user have mismatching TFA settings\n"
1500 if $realm_tfa && $realm_tfa->{type} ne $tfa->{type};
1501 }
1502
1503 return ($tfa->{type}, $tfa->{data});
1504 }
1505 }
1506
1507 # bash completion helpers
1508
1509 register_standard_option('userid-completed',
1510 get_standard_option('userid', { completion => \&complete_username}),
1511 );
1512
1513 sub complete_username {
1514
1515 my $user_cfg = cfs_read_file('user.cfg');
1516
1517 return [ keys %{$user_cfg->{users}} ];
1518 }
1519
1520 sub complete_group {
1521
1522 my $user_cfg = cfs_read_file('user.cfg');
1523
1524 return [ keys %{$user_cfg->{groups}} ];
1525 }
1526
1527 sub complete_realm {
1528
1529 my $domain_cfg = cfs_read_file('domains.cfg');
1530
1531 return [ keys %{$domain_cfg->{ids}} ];
1532 }
1533
1534 1;