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