]> git.proxmox.com Git - pve-access-control.git/blob - PVE/AccessControl.pm
2a4fe142743886c2df7fb28444529b927a6d30c4
[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 $propagate = $propagate ? 1 : 0;
969
970 if (my $path = normalize_path($pathtxt)) {
971 foreach my $role (split_list($rolelist)) {
972
973 if (!verify_rolename($role, 1)) {
974 warn "user config - ignore invalid role name '$role' in acl\n";
975 next;
976 }
977
978 foreach my $ug (split_list($uglist)) {
979 my ($group) = $ug =~ m/^@(\S+)$/;
980
981 if ($group && verify_groupname($group, 1)) {
982 if ($cfg->{groups}->{$group}) { # group exists
983 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
984 } else {
985 warn "user config - ignore invalid acl group '$group'\n";
986 }
987 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
988 if ($cfg->{users}->{$ug}) { # user exists
989 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
990 } else {
991 warn "user config - ignore invalid acl member '$ug'\n";
992 }
993 } else {
994 warn "user config - invalid user/group '$ug' in acl\n";
995 }
996 }
997 }
998 } else {
999 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1000 }
1001 } elsif ($et eq 'pool') {
1002 my ($pool, $comment, $vmlist, $storelist) = @data;
1003
1004 if (!verify_poolname($pool, 1)) {
1005 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1006 next;
1007 }
1008
1009 # make sure to add the pool (even if there are no members)
1010 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
1011
1012 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1013
1014 foreach my $vmid (split_list($vmlist)) {
1015 if ($vmid !~ m/^\d+$/) {
1016 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1017 next;
1018 }
1019 $vmid = int($vmid);
1020
1021 if ($cfg->{vms}->{$vmid}) {
1022 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1023 next;
1024 }
1025
1026 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
1027
1028 # record vmid ==> pool relation
1029 $cfg->{vms}->{$vmid} = $pool;
1030 }
1031
1032 foreach my $storeid (split_list($storelist)) {
1033 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1034 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1035 next;
1036 }
1037 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
1038 }
1039 } else {
1040 warn "user config - ignore config line: $line\n";
1041 }
1042 }
1043
1044 userconfig_force_defaults($cfg);
1045
1046 return $cfg;
1047 }
1048
1049 sub write_user_config {
1050 my ($filename, $cfg) = @_;
1051
1052 my $data = '';
1053
1054 foreach my $user (sort keys %{$cfg->{users}}) {
1055 my $d = $cfg->{users}->{$user};
1056 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1057 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1058 my $email = $d->{email} || '';
1059 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1060 my $expire = int($d->{expire} || 0);
1061 my $enable = $d->{enable} ? 1 : 0;
1062 my $keys = $d->{keys} ? $d->{keys} : '';
1063 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1064 }
1065
1066 $data .= "\n";
1067
1068 foreach my $group (sort keys %{$cfg->{groups}}) {
1069 my $d = $cfg->{groups}->{$group};
1070 my $list = join (',', keys %{$d->{users}});
1071 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1072 $data .= "group:$group:$list:$comment:\n";
1073 }
1074
1075 $data .= "\n";
1076
1077 foreach my $pool (sort keys %{$cfg->{pools}}) {
1078 my $d = $cfg->{pools}->{$pool};
1079 my $vmlist = join (',', keys %{$d->{vms}});
1080 my $storelist = join (',', keys %{$d->{storage}});
1081 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1082 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1083 }
1084
1085 $data .= "\n";
1086
1087 foreach my $role (sort keys %{$cfg->{roles}}) {
1088 next if $special_roles->{$role};
1089
1090 my $d = $cfg->{roles}->{$role};
1091 my $list = join (',', keys %$d);
1092 $data .= "role:$role:$list:\n";
1093 }
1094
1095 $data .= "\n";
1096
1097 foreach my $path (sort keys %{$cfg->{acl}}) {
1098 my $d = $cfg->{acl}->{$path};
1099
1100 my $ra = {};
1101
1102 foreach my $group (keys %{$d->{groups}}) {
1103 my $l0 = '';
1104 my $l1 = '';
1105 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
1106 my $propagate = $d->{groups}->{$group}->{$role};
1107 if ($propagate) {
1108 $l1 .= ',' if $l1;
1109 $l1 .= $role;
1110 } else {
1111 $l0 .= ',' if $l0;
1112 $l0 .= $role;
1113 }
1114 }
1115 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
1116 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
1117 }
1118
1119 foreach my $user (keys %{$d->{users}}) {
1120 # no need to save, because root is always 'Administrator'
1121 next if $user eq 'root@pam';
1122
1123 my $l0 = '';
1124 my $l1 = '';
1125 foreach my $role (sort keys %{$d->{users}->{$user}}) {
1126 my $propagate = $d->{users}->{$user}->{$role};
1127 if ($propagate) {
1128 $l1 .= ',' if $l1;
1129 $l1 .= $role;
1130 } else {
1131 $l0 .= ',' if $l0;
1132 $l0 .= $role;
1133 }
1134 }
1135 $ra->{0}->{$l0}->{$user} = 1 if $l0;
1136 $ra->{1}->{$l1}->{$user} = 1 if $l1;
1137 }
1138
1139 foreach my $rolelist (sort keys %{$ra->{0}}) {
1140 my $uglist = join (',', sort keys %{$ra->{0}->{$rolelist}});
1141 $data .= "acl:0:$path:$uglist:$rolelist:\n";
1142 }
1143 foreach my $rolelist (sort keys %{$ra->{1}}) {
1144 my $uglist = join (',', sort keys %{$ra->{1}->{$rolelist}});
1145 $data .= "acl:1:$path:$uglist:$rolelist:\n";
1146 }
1147 }
1148
1149 return $data;
1150 }
1151
1152 # The TFA configuration in priv/tfa.cfg format contains one line per user of
1153 # the form:
1154 # USER:TYPE:DATA
1155 # DATA is a base64 encoded json string and its format depends on the type.
1156 sub parse_priv_tfa_config {
1157 my ($filename, $raw) = @_;
1158
1159 my $users = {};
1160 my $cfg = { users => $users };
1161
1162 $raw = '' if !defined($raw);
1163 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1164 my $line = $1;
1165 my ($user, $type, $data) = split(/:/, $line, 3);
1166
1167 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1168 if (!$realm) {
1169 warn "user tfa config - ignore user '$user' - invalid user name\n";
1170 next;
1171 }
1172
1173 $data = decode_json(decode_base64($data));
1174
1175 $users->{$user} = {
1176 type => $type,
1177 data => $data,
1178 };
1179 }
1180
1181 return $cfg;
1182 }
1183
1184 sub write_priv_tfa_config {
1185 my ($filename, $cfg) = @_;
1186
1187 my $output = '';
1188
1189 my $users = $cfg->{users};
1190 foreach my $user (sort keys %$users) {
1191 my $info = $users->{$user};
1192 next if !%$info; # skip empty entries
1193
1194 $info = {%$info}; # copy to verify contents:
1195
1196 my $type = delete $info->{type};
1197 my $data = delete $info->{data};
1198
1199 if (my @keys = keys %$info) {
1200 die "invalid keys in TFA config for user $user: " . join(', ', @keys) . "\n";
1201 }
1202
1203 $data = encode_base64(encode_json($data), '');
1204 $output .= "${user}:${type}:${data}\n";
1205 }
1206
1207 return $output;
1208 }
1209
1210 sub roles {
1211 my ($cfg, $user, $path) = @_;
1212
1213 # NOTE: we do not consider pools here.
1214 # You need to use $rpcenv->roles() instead if you want that.
1215
1216 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1217
1218 my $perm = {};
1219
1220 foreach my $p (sort keys %{$cfg->{acl}}) {
1221 my $final = ($path eq $p);
1222
1223 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1224
1225 my $acl = $cfg->{acl}->{$p};
1226
1227 #print "CHECKACL $path $p\n";
1228 #print "ACL $path = " . Dumper ($acl);
1229
1230 if (my $ri = $acl->{users}->{$user}) {
1231 my $new;
1232 foreach my $role (keys %$ri) {
1233 my $propagate = $ri->{$role};
1234 if ($final || $propagate) {
1235 #print "APPLY ROLE $p $user $role\n";
1236 $new = {} if !$new;
1237 $new->{$role} = 1;
1238 }
1239 }
1240 if ($new) {
1241 $perm = $new; # overwrite previous settings
1242 next; # user privs always override group privs
1243 }
1244 }
1245
1246 my $new;
1247 foreach my $g (keys %{$acl->{groups}}) {
1248 next if !$cfg->{groups}->{$g}->{users}->{$user};
1249 if (my $ri = $acl->{groups}->{$g}) {
1250 foreach my $role (keys %$ri) {
1251 my $propagate = $ri->{$role};
1252 if ($final || $propagate) {
1253 #print "APPLY ROLE $p \@$g $role\n";
1254 $new = {} if !$new;
1255 $new->{$role} = 1;
1256 }
1257 }
1258 }
1259 }
1260 if ($new) {
1261 $perm = $new; # overwrite previous settings
1262 next;
1263 }
1264 }
1265
1266 return ('NoAccess') if defined ($perm->{NoAccess});
1267 #return () if defined ($perm->{NoAccess});
1268
1269 #print "permission $user $path = " . Dumper ($perm);
1270
1271 my @ra = keys %$perm;
1272
1273 #print "roles $user $path = " . join (',', @ra) . "\n";
1274
1275 return @ra;
1276 }
1277
1278 sub permission {
1279 my ($cfg, $user, $path) = @_;
1280
1281 $user = PVE::Auth::Plugin::verify_username($user, 1);
1282 return {} if !$user;
1283
1284 my @ra = roles($cfg, $user, $path);
1285
1286 my $privs = {};
1287
1288 foreach my $role (@ra) {
1289 if (my $privset = $cfg->{roles}->{$role}) {
1290 foreach my $p (keys %$privset) {
1291 $privs->{$p} = 1;
1292 }
1293 }
1294 }
1295
1296 #print "priviledges $user $path = " . Dumper ($privs);
1297
1298 return $privs;
1299 }
1300
1301 sub check_permissions {
1302 my ($username, $path, $privlist) = @_;
1303
1304 $path = normalize_path($path);
1305 my $usercfg = cfs_read_file('user.cfg');
1306 my $perm = permission($usercfg, $username, $path);
1307
1308 foreach my $priv (split_list($privlist)) {
1309 return undef if !$perm->{$priv};
1310 };
1311
1312 return 1;
1313 }
1314
1315 sub remove_vm_access {
1316 my ($vmid) = @_;
1317 my $delVMaccessFn = sub {
1318 my $usercfg = cfs_read_file("user.cfg");
1319 my $modified;
1320
1321 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1322 delete $usercfg->{acl}->{"/vms/$vmid"};
1323 $modified = 1;
1324 }
1325 if (my $pool = $usercfg->{vms}->{$vmid}) {
1326 if (my $data = $usercfg->{pools}->{$pool}) {
1327 delete $data->{vms}->{$vmid};
1328 delete $usercfg->{vms}->{$vmid};
1329 $modified = 1;
1330 }
1331 }
1332 cfs_write_file("user.cfg", $usercfg) if $modified;
1333 };
1334
1335 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1336 }
1337
1338 sub remove_storage_access {
1339 my ($storeid) = @_;
1340
1341 my $deleteStorageAccessFn = sub {
1342 my $usercfg = cfs_read_file("user.cfg");
1343 my $modified;
1344
1345 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1346 delete $usercfg->{acl}->{"/storage/$storeid"};
1347 $modified = 1;
1348 }
1349 foreach my $pool (keys %{$usercfg->{pools}}) {
1350 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1351 $modified = 1;
1352 }
1353 cfs_write_file("user.cfg", $usercfg) if $modified;
1354 };
1355
1356 lock_user_config($deleteStorageAccessFn,
1357 "access permissions cleanup for storage $storeid failed");
1358 }
1359
1360 sub add_vm_to_pool {
1361 my ($vmid, $pool) = @_;
1362
1363 my $addVMtoPoolFn = sub {
1364 my $usercfg = cfs_read_file("user.cfg");
1365 if (my $data = $usercfg->{pools}->{$pool}) {
1366 $data->{vms}->{$vmid} = 1;
1367 $usercfg->{vms}->{$vmid} = $pool;
1368 cfs_write_file("user.cfg", $usercfg);
1369 }
1370 };
1371
1372 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1373 }
1374
1375 sub remove_vm_from_pool {
1376 my ($vmid) = @_;
1377
1378 my $delVMfromPoolFn = sub {
1379 my $usercfg = cfs_read_file("user.cfg");
1380 if (my $pool = $usercfg->{vms}->{$vmid}) {
1381 if (my $data = $usercfg->{pools}->{$pool}) {
1382 delete $data->{vms}->{$vmid};
1383 delete $usercfg->{vms}->{$vmid};
1384 cfs_write_file("user.cfg", $usercfg);
1385 }
1386 }
1387 };
1388
1389 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1390 }
1391
1392 my $USER_CONTROLLED_TFA_TYPES = {
1393 u2f => 1,
1394 oath => 1,
1395 };
1396
1397 # Delete an entry by setting $data=undef in which case $type is ignored.
1398 # Otherwise both must be valid.
1399 sub user_set_tfa {
1400 my ($userid, $realm, $type, $data, $cached_usercfg, $cached_domaincfg) = @_;
1401
1402 if (defined($data) && !defined($type)) {
1403 # This is an internal usage error and should not happen
1404 die "cannot set tfa data without a type\n";
1405 }
1406
1407 my $user_cfg = $cached_usercfg || cfs_read_file('user.cfg');
1408 my $user = $user_cfg->{users}->{$userid}
1409 or die "user '$userid' not found\n";
1410
1411 my $domain_cfg = $cached_domaincfg || cfs_read_file('domains.cfg');
1412 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1413 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1414
1415 my $realm_tfa = $realm_cfg->{tfa};
1416 if (defined($realm_tfa)) {
1417 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa);
1418 # If the realm has a TFA setting, we're only allowed to use that.
1419 if (defined($data)) {
1420 my $required_type = $realm_tfa->{type};
1421 if ($required_type ne $type) {
1422 die "realm '$realm' only allows TFA of type '$required_type\n";
1423 }
1424
1425 if (defined($data->{config})) {
1426 # XXX: Is it enough if the type matches? Or should the configuration also match?
1427 }
1428
1429 # realm-configured tfa always uses a simple key list, so use the user.cfg
1430 $user->{keys} = $data->{keys};
1431 } else {
1432 die "realm '$realm' does not allow removing the 2nd factor\n";
1433 }
1434 } else {
1435 # Without a realm-enforced TFA setting the user can add a u2f or totp entry by themselves.
1436 # The 'yubico' type requires yubico server settings, which have to be configured on the
1437 # realm, so this is not supported here:
1438 die "domain '$realm' does not support TFA type '$type'\n"
1439 if defined($data) && !$USER_CONTROLLED_TFA_TYPES->{$type};
1440 }
1441
1442 # Custom TFA entries are stored in priv/tfa.cfg as they can be more complet: u2f uses a
1443 # public key and a key handle, TOTP requires the usual totp settings...
1444
1445 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1446 my $tfa = ($tfa_cfg->{users}->{$userid} //= {});
1447
1448 if (defined($data)) {
1449 $tfa->{type} = $type;
1450 $tfa->{data} = $data;
1451 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1452
1453 $user->{keys} = "x!$type";
1454 } else {
1455 delete $tfa_cfg->{users}->{$userid};
1456 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1457
1458 delete $user->{keys};
1459 }
1460
1461 cfs_write_file('user.cfg', $user_cfg);
1462 }
1463
1464 sub user_get_tfa {
1465 my ($username, $realm) = @_;
1466
1467 my $user_cfg = cfs_read_file('user.cfg');
1468 my $user = $user_cfg->{users}->{$username}
1469 or die "user '$username' not found\n";
1470
1471 my $keys = $user->{keys};
1472
1473 my $domain_cfg = cfs_read_file('domains.cfg');
1474 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1475 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1476
1477 my $realm_tfa = $realm_cfg->{tfa};
1478 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
1479 if $realm_tfa;
1480
1481 if (!$keys) {
1482 return if !$realm_tfa;
1483 die "missing required 2nd keys\n";
1484 }
1485
1486 # new style config starts with an 'x' and optionally contains a !<type> suffix
1487 if ($keys !~ /^x(?:!.*)?$/) {
1488 # old style config, find the type via the realm
1489 return if !$realm_tfa;
1490 return ($realm_tfa->{type}, {
1491 keys => $keys,
1492 config => $realm_tfa,
1493 });
1494 } else {
1495 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1496 my $tfa = $tfa_cfg->{users}->{$username};
1497 return if !$tfa; # should not happen (user.cfg wasn't cleaned up?)
1498
1499 if ($realm_tfa) {
1500 # if the realm has a tfa setting we need to verify the type:
1501 die "auth domain '$realm' and user have mismatching TFA settings\n"
1502 if $realm_tfa && $realm_tfa->{type} ne $tfa->{type};
1503 }
1504
1505 return ($tfa->{type}, $tfa->{data});
1506 }
1507 }
1508
1509 # bash completion helpers
1510
1511 register_standard_option('userid-completed',
1512 get_standard_option('userid', { completion => \&complete_username}),
1513 );
1514
1515 sub complete_username {
1516
1517 my $user_cfg = cfs_read_file('user.cfg');
1518
1519 return [ keys %{$user_cfg->{users}} ];
1520 }
1521
1522 sub complete_group {
1523
1524 my $user_cfg = cfs_read_file('user.cfg');
1525
1526 return [ keys %{$user_cfg->{groups}} ];
1527 }
1528
1529 sub complete_realm {
1530
1531 my $domain_cfg = cfs_read_file('domains.cfg');
1532
1533 return [ keys %{$domain_cfg->{ids}} ];
1534 }
1535
1536 1;