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