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