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