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