]> git.proxmox.com Git - pve-access-control.git/blob - src/PVE/AccessControl.pm
2569a3528232c3f1ba438a293fd0d44010c59874
[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
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 $auth_graceperiod = 60 * 5; # 5 minutes
52 my $authkey_lifetime = 3600 * 24; # rotate every 24 hours
53
54 Crypt::OpenSSL::RSA->import_random_seed();
55
56 cfs_register_file('user.cfg', \&parse_user_config, \&write_user_config);
57 cfs_register_file('priv/tfa.cfg', \&parse_priv_tfa_config, \&write_priv_tfa_config);
58
59 sub verify_username {
60 PVE::Auth::Plugin::verify_username(@_);
61 }
62
63 sub pve_verify_realm {
64 PVE::Auth::Plugin::pve_verify_realm(@_);
65 }
66
67 sub lock_user_config {
68 my ($code, $errmsg) = @_;
69
70 cfs_lock_file("user.cfg", undef, $code);
71 if (my $err = $@) {
72 $errmsg ? die "$errmsg: $err" : die $err;
73 }
74 }
75
76 my $cache_read_key = sub {
77 my ($type) = @_;
78
79 my $path = $pve_auth_key_files->{$type};
80
81 my $read_key_and_mtime = sub {
82 my $fh = IO::File->new($path, "r");
83
84 return undef if !defined($fh);
85
86 my $st = stat($fh);
87 my $pem = PVE::Tools::safe_read_from($fh, 0, 0, $path);
88
89 close $fh;
90
91 my $key;
92 if ($type eq 'pub' || $type eq 'pubold') {
93 $key = eval { Crypt::OpenSSL::RSA->new_public_key($pem); };
94 } elsif ($type eq 'priv') {
95 $key = eval { Crypt::OpenSSL::RSA->new_private_key($pem); };
96 } else {
97 die "Invalid authkey type '$type'\n";
98 }
99
100 return { key => $key, mtime => $st->mtime };
101 };
102
103 if (!defined($pve_auth_key_cache->{$type})) {
104 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
105 } else {
106 my $st = stat($path);
107 if (!$st || $st->mtime != $pve_auth_key_cache->{$type}->{mtime}) {
108 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
109 }
110 }
111
112 return $pve_auth_key_cache->{$type};
113 };
114
115 sub get_pubkey {
116 my ($old) = @_;
117
118 my $type = $old ? 'pubold' : 'pub';
119
120 my $res = $cache_read_key->($type);
121 return undef if !defined($res);
122
123 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
124 }
125
126 sub get_privkey {
127 my $res = $cache_read_key->('priv');
128
129 if (!defined($res) || !check_authkey(1)) {
130 rotate_authkey();
131 $res = $cache_read_key->('priv');
132 }
133
134 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
135 }
136
137 sub check_authkey {
138 my ($quiet) = @_;
139
140 # skip check if non-quorate, as rotation is not possible anyway
141 return 1 if !PVE::Cluster::check_cfs_quorum(1);
142
143 my ($pub_key, $mtime) = get_pubkey();
144 if (!$pub_key) {
145 warn "auth key pair missing, generating new one..\n" if !$quiet;
146 return 0;
147 } else {
148 my $now = time();
149 if ($now - $mtime >= $authkey_lifetime) {
150 warn "auth key pair too old, rotating..\n" if !$quiet;;
151 return 0;
152 } elsif ($mtime > $now + $auth_graceperiod) {
153 # a nodes RTC had a time set in the future during key generation -> ticket
154 # validity is clamped to 0+5 min grace period until now >= mtime again
155 my (undef, $old_mtime) = get_pubkey(1);
156 if ($old_mtime && $mtime >= $old_mtime && $mtime - $old_mtime < $ticket_lifetime) {
157 warn "auth key pair generated in the future (key $mtime > host $now),"
158 ." but old key still exists and in valid grace period so avoid automatic"
159 ." fixup. Cluster time not in sync?\n" if !$quiet;
160 return 1;
161 }
162 warn "auth key pair generated in the future (key $mtime > host $now), rotating..\n" if !$quiet;
163 return 0;
164 } else {
165 warn "auth key new enough, skipping rotation\n" if !$quiet;;
166 return 1;
167 }
168 }
169 }
170
171 sub rotate_authkey {
172 return if $authkey_lifetime == 0;
173
174 PVE::Cluster::cfs_lock_authkey(undef, sub {
175 # re-check with lock to avoid double rotation in clusters
176 return if check_authkey();
177
178 my $old = get_pubkey();
179 my $new = Crypt::OpenSSL::RSA->generate_key(2048);
180
181 if ($old) {
182 eval {
183 my $pem = $old->get_public_key_x509_string();
184 # mtime is used for caching and ticket age range calculation
185 PVE::Tools::file_set_contents($pve_auth_key_files->{pubold}, $pem);
186 };
187 die "Failed to store old auth key: $@\n" if $@;
188 }
189
190 eval {
191 my $pem = $new->get_public_key_x509_string();
192 # mtime is used for caching and ticket age range calculation,
193 # should be close to that of pubold above
194 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
195 };
196 if ($@) {
197 if ($old) {
198 warn "Failed to store new auth key - $@\n";
199 warn "Reverting to previous auth key\n";
200 eval {
201 my $pem = $old->get_public_key_x509_string();
202 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
203 };
204 die "Failed to restore old auth key: $@\n" if $@;
205 } else {
206 die "Failed to store new auth key - $@\n";
207 }
208 }
209
210 eval {
211 my $pem = $new->get_private_key_string();
212 PVE::Tools::file_set_contents($pve_auth_key_files->{priv}, $pem);
213 };
214 if ($@) {
215 warn "Failed to store new auth key - $@\n";
216 warn "Deleting auth key to force regeneration\n";
217 unlink $pve_auth_key_files->{pub};
218 unlink $pve_auth_key_files->{priv};
219 }
220 });
221 die $@ if $@;
222 }
223
224 PVE::JSONSchema::register_standard_option('tokenid', {
225 description => "API token identifier.",
226 type => "string",
227 format => "pve-tokenid",
228 });
229
230 our $token_subid_regex = $PVE::Auth::Plugin::realm_regex;
231
232 # username@realm username realm tokenid
233 our $token_full_regex = qr/((${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex}))!(${token_subid_regex})/;
234
235 our $userid_or_token_regex = qr/^$PVE::Auth::Plugin::user_regex\@$PVE::Auth::Plugin::realm_regex(?:!$token_subid_regex)?$/;
236
237 sub split_tokenid {
238 my ($tokenid, $noerr) = @_;
239
240 if ($tokenid =~ /^${token_full_regex}$/) {
241 return ($1, $4);
242 }
243
244 die "'$tokenid' is not a valid token ID - not able to split into user and token parts\n" if !$noerr;
245
246 return undef;
247 }
248
249 sub join_tokenid {
250 my ($username, $tokensubid) = @_;
251
252 my $joined = "${username}!${tokensubid}";
253
254 return pve_verify_tokenid($joined);
255 }
256
257 PVE::JSONSchema::register_format('pve-tokenid', \&pve_verify_tokenid);
258 sub pve_verify_tokenid {
259 my ($tokenid, $noerr) = @_;
260
261 if ($tokenid =~ /^${token_full_regex}$/) {
262 return wantarray ? ($tokenid, $2, $3, $4) : $tokenid;
263 }
264
265 die "value '$tokenid' does not look like a valid token ID\n" if !$noerr;
266
267 return undef;
268 }
269
270
271 my $csrf_prevention_secret;
272 my $csrf_prevention_secret_legacy;
273 my $get_csrfr_secret = sub {
274 if (!$csrf_prevention_secret) {
275 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
276 $csrf_prevention_secret = Digest::SHA::hmac_sha256_base64($input);
277 $csrf_prevention_secret_legacy = Digest::SHA::sha1_base64($input);
278 }
279 return $csrf_prevention_secret;
280 };
281
282 sub assemble_csrf_prevention_token {
283 my ($username) = @_;
284
285 my $secret = &$get_csrfr_secret();
286
287 return PVE::Ticket::assemble_csrf_prevention_token ($secret, $username);
288 }
289
290 sub verify_csrf_prevention_token {
291 my ($username, $token, $noerr) = @_;
292
293 my $secret = $get_csrfr_secret->();
294
295 # FIXME: remove with PVE 7 and/or refactor all into PVE::Ticket ?
296 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
297 my $sig = $2;
298 if (length($sig) == 27) {
299 # the legacy secret got populated by above get_csrfr_secret call
300 $secret = $csrf_prevention_secret_legacy;
301 }
302 }
303
304 return PVE::Ticket::verify_csrf_prevention_token(
305 $secret, $username, $token, -$auth_graceperiod, $ticket_lifetime, $noerr);
306 }
307
308 my $get_ticket_age_range = sub {
309 my ($now, $mtime, $rotated) = @_;
310
311 my $key_age = $now - $mtime;
312 $key_age = 0 if $key_age < 0;
313
314 my $min = -$auth_graceperiod;
315 my $max = $ticket_lifetime;
316
317 if ($rotated) {
318 # ticket creation after rotation is not allowed
319 $min = $key_age - $auth_graceperiod;
320 } else {
321 if ($key_age > $authkey_lifetime && $authkey_lifetime > 0) {
322 if (PVE::Cluster::check_cfs_quorum(1)) {
323 # key should have been rotated, clamp range accordingly
324 $min = $key_age - $authkey_lifetime;
325 } else {
326 warn "Cluster not quorate - extending auth key lifetime!\n";
327 }
328 }
329
330 $max = $key_age + $auth_graceperiod if $key_age < $ticket_lifetime;
331 }
332
333 return undef if $min > $ticket_lifetime;
334 return ($min, $max);
335 };
336
337 sub assemble_ticket {
338 my ($data) = @_;
339
340 my $rsa_priv = get_privkey();
341
342 return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $data);
343 }
344
345 sub verify_ticket {
346 my ($ticket, $noerr) = @_;
347
348 my $now = time();
349
350 my $check = sub {
351 my ($old) = @_;
352
353 my ($rsa_pub, $rsa_mtime) = get_pubkey($old);
354 return undef if !$rsa_pub;
355
356 my ($min, $max) = $get_ticket_age_range->($now, $rsa_mtime, $old);
357 return undef if !defined($min);
358
359 return PVE::Ticket::verify_rsa_ticket(
360 $rsa_pub, 'PVE', $ticket, undef, $min, $max, 1);
361 };
362
363 my ($data, $age) = $check->();
364
365 # check with old, rotated key if current key failed
366 ($data, $age) = $check->(1) if !defined($data);
367
368 my $auth_failure = sub {
369 if ($noerr) {
370 return undef;
371 } else {
372 # raise error via undef ticket
373 PVE::Ticket::verify_rsa_ticket(undef, 'PVE');
374 }
375 };
376
377 if (!defined($data)) {
378 return $auth_failure->();
379 }
380
381 my ($username, $tfa_info);
382 if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
383 # Ticket for u2f-users:
384 ($username, my $challenge) = ($1, $2);
385 if ($challenge eq 'verified') {
386 # u2f challenge was completed
387 $challenge = undef;
388 } elsif (!wantarray) {
389 # The caller is not aware there could be an ongoing challenge,
390 # so we treat this ticket as invalid:
391 return $auth_failure->();
392 }
393 $tfa_info = {
394 type => 'u2f',
395 challenge => $challenge,
396 };
397 } elsif ($data =~ /^tfa!(.*)$/) {
398 # TOTP and Yubico don't require a challenge so this is the generic
399 # 'missing 2nd factor ticket'
400 $username = $1;
401 $tfa_info = { type => 'tfa' };
402 } else {
403 # Regular ticket (full access)
404 $username = $data;
405 }
406
407 return undef if !PVE::Auth::Plugin::verify_username($username, $noerr);
408
409 return wantarray ? ($username, $age, $tfa_info) : $username;
410 }
411
412 sub verify_token {
413 my ($api_token) = @_;
414
415 die "no API token specified\n" if !$api_token;
416
417 my ($tokenid, $value);
418 if ($api_token =~ /^(.*)=(.*)$/) {
419 $tokenid = $1;
420 $value = $2;
421 } else {
422 die "no tokenid specified\n";
423 }
424
425 my ($username, $token) = split_tokenid($tokenid);
426
427 my $usercfg = cfs_read_file('user.cfg');
428 check_user_enabled($usercfg, $username);
429 check_token_exist($usercfg, $username, $token);
430
431 my $ctime = time();
432
433 my $user = $usercfg->{users}->{$username};
434 die "account expired\n" if $user->{expire} && ($user->{expire} < $ctime);
435
436 my $token_info = $user->{tokens}->{$token};
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 return undef;
583 }
584
585 sub check_token_exist {
586 my ($usercfg, $username, $tokenid, $noerr) = @_;
587
588 my $user = check_user_exist($usercfg, $username, $noerr);
589 return undef if !$user;
590
591 return $user->{tokens}->{$tokenid}
592 if defined($user->{tokens}) && $user->{tokens}->{$tokenid};
593
594 die "no such token '$tokenid' for user '$username'\n" if !$noerr;
595
596 return undef;
597 }
598
599 sub verify_one_time_pw {
600 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
601
602 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
603
604 # fixme: proxy support?
605 my $proxy;
606
607 if ($type eq 'yubico') {
608 PVE::OTP::yubico_verify_otp($otp, $keys, $tfa_cfg->{url},
609 $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
610 } elsif ($type eq 'oath') {
611 PVE::OTP::oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
612 } else {
613 die "unknown tfa type '$type'\n";
614 }
615 }
616
617 # password should be utf8 encoded
618 # Note: some plugins delay/sleep if auth fails
619 sub authenticate_user {
620 my ($username, $password, $otp) = @_;
621
622 die "no username specified\n" if !$username;
623
624 my ($ruid, $realm);
625
626 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
627
628 my $usercfg = cfs_read_file('user.cfg');
629
630 check_user_enabled($usercfg, $username);
631
632 my $ctime = time();
633 my $expire = $usercfg->{users}->{$username}->{expire};
634
635 die "account expired\n" if $expire && ($expire < $ctime);
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 |/storage
948 |/storage/[[:alnum:]\.\-\_]+
949 |/vms
950 |/vms/[1-9][0-9]{2,}
951 )$!xs;
952 }
953
954 PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
955 sub verify_groupname {
956 my ($groupname, $noerr) = @_;
957
958 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
959
960 die "group name '$groupname' contains invalid characters\n" if !$noerr;
961
962 return undef;
963 }
964
965 return $groupname;
966 }
967
968 PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
969 sub verify_rolename {
970 my ($rolename, $noerr) = @_;
971
972 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
973
974 die "role name '$rolename' contains invalid characters\n" if !$noerr;
975
976 return undef;
977 }
978
979 return $rolename;
980 }
981
982 PVE::JSONSchema::register_format('pve-poolid', \&verify_poolname);
983 sub verify_poolname {
984 my ($poolname, $noerr) = @_;
985
986 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
987
988 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
989
990 return undef;
991 }
992
993 return $poolname;
994 }
995
996 PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
997 sub verify_privname {
998 my ($priv, $noerr) = @_;
999
1000 if (!$valid_privs->{$priv}) {
1001 die "invalid privilege '$priv'\n" if !$noerr;
1002
1003 return undef;
1004 }
1005
1006 return $priv;
1007 }
1008
1009 sub userconfig_force_defaults {
1010 my ($cfg) = @_;
1011
1012 foreach my $r (keys %$special_roles) {
1013 $cfg->{roles}->{$r} = $special_roles->{$r};
1014 }
1015
1016 # add root user if not exists
1017 if (!$cfg->{users}->{'root@pam'}) {
1018 $cfg->{users}->{'root@pam'}->{enable} = 1;
1019 }
1020 }
1021
1022 sub parse_user_config {
1023 my ($filename, $raw) = @_;
1024
1025 my $cfg = {};
1026
1027 userconfig_force_defaults($cfg);
1028
1029 $raw = '' if !defined($raw);
1030 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1031 my $line = $1;
1032 my @data;
1033
1034 foreach my $d (split (/:/, $line)) {
1035 $d =~ s/^\s+//;
1036 $d =~ s/\s+$//;
1037 push @data, $d
1038 }
1039
1040 my $et = shift @data;
1041
1042 if ($et eq 'user') {
1043 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
1044
1045 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1046 if (!$realm) {
1047 warn "user config - ignore user '$user' - invalid user name\n";
1048 next;
1049 }
1050
1051 $enable = $enable ? 1 : 0;
1052
1053 $expire = 0 if !$expire;
1054
1055 if ($expire !~ m/^\d+$/) {
1056 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
1057 next;
1058 }
1059 $expire = int($expire);
1060
1061 #if (!verify_groupname ($group, 1)) {
1062 # warn "user config - ignore user '$user' - invalid characters in group name\n";
1063 # next;
1064 #}
1065
1066 $cfg->{users}->{$user} = {
1067 enable => $enable,
1068 # group => $group,
1069 };
1070 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
1071 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
1072 $cfg->{users}->{$user}->{email} = $email;
1073 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1074 $cfg->{users}->{$user}->{expire} = $expire;
1075 # keys: allowed yubico key ids or oath secrets (base32 encoded)
1076 $cfg->{users}->{$user}->{keys} = $keys if $keys;
1077
1078 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
1079 #$cfg->{groups}->{$group}->{$user} = 1;
1080
1081 } elsif ($et eq 'group') {
1082 my ($group, $userlist, $comment) = @data;
1083
1084 if (!verify_groupname($group, 1)) {
1085 warn "user config - ignore group '$group' - invalid characters in group name\n";
1086 next;
1087 }
1088
1089 # make sure to add the group (even if there are no members)
1090 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
1091
1092 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1093
1094 foreach my $user (split_list($userlist)) {
1095
1096 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
1097 warn "user config - ignore invalid group member '$user'\n";
1098 next;
1099 }
1100
1101 if ($cfg->{users}->{$user}) { # user exists
1102 $cfg->{users}->{$user}->{groups}->{$group} = 1;
1103 } else {
1104 warn "user config - ignore invalid group member '$user'\n";
1105 }
1106 $cfg->{groups}->{$group}->{users}->{$user} = 1;
1107 }
1108
1109 } elsif ($et eq 'role') {
1110 my ($role, $privlist) = @data;
1111
1112 if (!verify_rolename($role, 1)) {
1113 warn "user config - ignore role '$role' - invalid characters in role name\n";
1114 next;
1115 }
1116
1117 # make sure to add the role (even if there are no privileges)
1118 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
1119
1120 foreach my $priv (split_list($privlist)) {
1121 if (defined ($valid_privs->{$priv})) {
1122 $cfg->{roles}->{$role}->{$priv} = 1;
1123 } else {
1124 warn "user config - ignore invalid privilege '$priv'\n";
1125 }
1126 }
1127
1128 } elsif ($et eq 'acl') {
1129 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
1130
1131 $propagate = $propagate ? 1 : 0;
1132
1133 if (my $path = normalize_path($pathtxt)) {
1134 foreach my $role (split_list($rolelist)) {
1135
1136 if (!verify_rolename($role, 1)) {
1137 warn "user config - ignore invalid role name '$role' in acl\n";
1138 next;
1139 }
1140
1141 if (!$cfg->{roles}->{$role}) {
1142 warn "user config - ignore invalid acl role '$role'\n";
1143 next;
1144 }
1145
1146 foreach my $ug (split_list($uglist)) {
1147 my ($group) = $ug =~ m/^@(\S+)$/;
1148
1149 if ($group && verify_groupname($group, 1)) {
1150 if (!$cfg->{groups}->{$group}) { # group does not exist
1151 warn "user config - ignore invalid acl group '$group'\n";
1152 }
1153 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
1154 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
1155 if (!$cfg->{users}->{$ug}) { # user does not exist
1156 warn "user config - ignore invalid acl member '$ug'\n";
1157 }
1158 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
1159 } elsif (my ($user, $token) = split_tokenid($ug, 1)) {
1160 if (check_token_exist($cfg, $user, $token, 1)) {
1161 $cfg->{acl}->{$path}->{tokens}->{$ug}->{$role} = $propagate;
1162 } else {
1163 warn "user config - ignore invalid acl token '$ug'\n";
1164 }
1165 } else {
1166 warn "user config - invalid user/group '$ug' in acl\n";
1167 }
1168 }
1169 }
1170 } else {
1171 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1172 }
1173 } elsif ($et eq 'pool') {
1174 my ($pool, $comment, $vmlist, $storelist) = @data;
1175
1176 if (!verify_poolname($pool, 1)) {
1177 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1178 next;
1179 }
1180
1181 # make sure to add the pool (even if there are no members)
1182 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
1183
1184 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1185
1186 foreach my $vmid (split_list($vmlist)) {
1187 if ($vmid !~ m/^\d+$/) {
1188 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1189 next;
1190 }
1191 $vmid = int($vmid);
1192
1193 if ($cfg->{vms}->{$vmid}) {
1194 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1195 next;
1196 }
1197
1198 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
1199
1200 # record vmid ==> pool relation
1201 $cfg->{vms}->{$vmid} = $pool;
1202 }
1203
1204 foreach my $storeid (split_list($storelist)) {
1205 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1206 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1207 next;
1208 }
1209 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
1210 }
1211 } elsif ($et eq 'token') {
1212 my ($tokenid, $expire, $privsep, $comment) = @data;
1213
1214 my ($user, $token) = split_tokenid($tokenid, 1);
1215 if (!($user && $token)) {
1216 warn "user config - ignore invalid tokenid '$tokenid'\n";
1217 next;
1218 }
1219
1220 $privsep = $privsep ? 1 : 0;
1221
1222 $expire = 0 if !$expire;
1223
1224 if ($expire !~ m/^\d+$/) {
1225 warn "user config - ignore token '$tokenid' - (illegal characters in expire '$expire')\n";
1226 next;
1227 }
1228 $expire = int($expire);
1229
1230 if (my $user_cfg = $cfg->{users}->{$user}) { # user exists
1231 $user_cfg->{tokens}->{$token} = {} if !$user_cfg->{tokens}->{$token};
1232 my $token_cfg = $user_cfg->{tokens}->{$token};
1233 $token_cfg->{privsep} = $privsep;
1234 $token_cfg->{expire} = $expire;
1235 $token_cfg->{comment} = PVE::Tools::decode_text($comment) if $comment;
1236 } else {
1237 warn "user config - ignore token '$tokenid' - user does not exist\n";
1238 }
1239 } else {
1240 warn "user config - ignore config line: $line\n";
1241 }
1242 }
1243
1244 userconfig_force_defaults($cfg);
1245
1246 return $cfg;
1247 }
1248
1249 sub write_user_config {
1250 my ($filename, $cfg) = @_;
1251
1252 my $data = '';
1253
1254 foreach my $user (sort keys %{$cfg->{users}}) {
1255 my $d = $cfg->{users}->{$user};
1256 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1257 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1258 my $email = $d->{email} || '';
1259 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1260 my $expire = int($d->{expire} || 0);
1261 my $enable = $d->{enable} ? 1 : 0;
1262 my $keys = $d->{keys} ? $d->{keys} : '';
1263 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1264
1265 my $user_tokens = $d->{tokens};
1266 foreach my $token (sort keys %$user_tokens) {
1267 my $td = $user_tokens->{$token};
1268 my $full_tokenid = join_tokenid($user, $token);
1269 my $comment = $td->{comment} ? PVE::Tools::encode_text($td->{comment}) : '';
1270 my $expire = int($td->{expire} || 0);
1271 my $privsep = $td->{privsep} ? 1 : 0;
1272 $data .= "token:$full_tokenid:$expire:$privsep:$comment:\n";
1273 }
1274 }
1275
1276 $data .= "\n";
1277
1278 foreach my $group (sort keys %{$cfg->{groups}}) {
1279 my $d = $cfg->{groups}->{$group};
1280 my $list = join (',', sort keys %{$d->{users}});
1281 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1282 $data .= "group:$group:$list:$comment:\n";
1283 }
1284
1285 $data .= "\n";
1286
1287 foreach my $pool (sort keys %{$cfg->{pools}}) {
1288 my $d = $cfg->{pools}->{$pool};
1289 my $vmlist = join (',', sort keys %{$d->{vms}});
1290 my $storelist = join (',', sort keys %{$d->{storage}});
1291 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1292 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1293 }
1294
1295 $data .= "\n";
1296
1297 foreach my $role (sort keys %{$cfg->{roles}}) {
1298 next if $special_roles->{$role};
1299
1300 my $d = $cfg->{roles}->{$role};
1301 my $list = join (',', sort keys %$d);
1302 $data .= "role:$role:$list:\n";
1303 }
1304
1305 $data .= "\n";
1306
1307 my $collect_rolelist_members = sub {
1308 my ($acl_members, $result, $prefix, $exclude) = @_;
1309
1310 foreach my $member (keys %$acl_members) {
1311 next if $exclude && $member eq $exclude;
1312
1313 my $l0 = '';
1314 my $l1 = '';
1315 foreach my $role (sort keys %{$acl_members->{$member}}) {
1316 my $propagate = $acl_members->{$member}->{$role};
1317 if ($propagate) {
1318 $l1 .= ',' if $l1;
1319 $l1 .= $role;
1320 } else {
1321 $l0 .= ',' if $l0;
1322 $l0 .= $role;
1323 }
1324 }
1325 $result->{0}->{$l0}->{"${prefix}${member}"} = 1 if $l0;
1326 $result->{1}->{$l1}->{"${prefix}${member}"} = 1 if $l1;
1327 }
1328 };
1329
1330 foreach my $path (sort keys %{$cfg->{acl}}) {
1331 my $d = $cfg->{acl}->{$path};
1332
1333 my $rolelist_members = {};
1334
1335 $collect_rolelist_members->($d->{'groups'}, $rolelist_members, '@');
1336
1337 # no need to save 'root@pam', it is always 'Administrator'
1338 $collect_rolelist_members->($d->{'users'}, $rolelist_members, '', 'root@pam');
1339
1340 $collect_rolelist_members->($d->{'tokens'}, $rolelist_members, '');
1341
1342 foreach my $propagate (0,1) {
1343 my $filtered = $rolelist_members->{$propagate};
1344 foreach my $rolelist (sort keys %$filtered) {
1345 my $uglist = join (',', sort keys %{$filtered->{$rolelist}});
1346 $data .= "acl:$propagate:$path:$uglist:$rolelist:\n";
1347 }
1348
1349 }
1350 }
1351
1352 return $data;
1353 }
1354
1355 # The TFA configuration in priv/tfa.cfg format contains one line per user of
1356 # the form:
1357 # USER:TYPE:DATA
1358 # DATA is a base64 encoded json string and its format depends on the type.
1359 sub parse_priv_tfa_config {
1360 my ($filename, $raw) = @_;
1361
1362 my $users = {};
1363 my $cfg = { users => $users };
1364
1365 $raw = '' if !defined($raw);
1366 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1367 my $line = $1;
1368 my ($user, $type, $data) = split(/:/, $line, 3);
1369
1370 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1371 if (!$realm) {
1372 warn "user tfa config - ignore user '$user' - invalid user name\n";
1373 next;
1374 }
1375
1376 $data = decode_json(decode_base64($data));
1377
1378 $users->{$user} = {
1379 type => $type,
1380 data => $data,
1381 };
1382 }
1383
1384 return $cfg;
1385 }
1386
1387 sub write_priv_tfa_config {
1388 my ($filename, $cfg) = @_;
1389
1390 my $output = '';
1391
1392 my $users = $cfg->{users};
1393 foreach my $user (sort keys %$users) {
1394 my $info = $users->{$user};
1395 next if !%$info; # skip empty entries
1396
1397 $info = {%$info}; # copy to verify contents:
1398
1399 my $type = delete $info->{type};
1400 my $data = delete $info->{data};
1401
1402 if (my @keys = keys %$info) {
1403 die "invalid keys in TFA config for user $user: " . join(', ', @keys) . "\n";
1404 }
1405
1406 $data = encode_base64(encode_json($data), '');
1407 $output .= "${user}:${type}:${data}\n";
1408 }
1409
1410 return $output;
1411 }
1412
1413 sub roles {
1414 my ($cfg, $user, $path) = @_;
1415
1416 # NOTE: we do not consider pools here.
1417 # NOTE: for privsep tokens, this does not filter roles by those that the
1418 # corresponding user has.
1419 # Use $rpcenv->permission() for any actual permission checks!
1420
1421 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1422
1423 if (pve_verify_tokenid($user, 1)) {
1424 my $tokenid = $user;
1425 my ($username, $token) = split_tokenid($tokenid);
1426
1427 my $token_info = $cfg->{users}->{$username}->{tokens}->{$token};
1428 return () if !$token_info;
1429
1430 my $user_roles = roles($cfg, $username, $path);
1431
1432 # return full user privileges
1433 return $user_roles if !$token_info->{privsep};
1434 }
1435
1436 my $roles = {};
1437
1438 foreach my $p (sort keys %{$cfg->{acl}}) {
1439 my $final = ($path eq $p);
1440
1441 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1442
1443 my $acl = $cfg->{acl}->{$p};
1444
1445 #print "CHECKACL $path $p\n";
1446 #print "ACL $path = " . Dumper ($acl);
1447 if (my $ri = $acl->{tokens}->{$user}) {
1448 my $new;
1449 foreach my $role (keys %$ri) {
1450 my $propagate = $ri->{$role};
1451 if ($final || $propagate) {
1452 #print "APPLY ROLE $p $user $role\n";
1453 $new = {} if !$new;
1454 $new->{$role} = $propagate;
1455 }
1456 }
1457 if ($new) {
1458 $roles = $new; # overwrite previous settings
1459 next;
1460 }
1461 }
1462
1463 if (my $ri = $acl->{users}->{$user}) {
1464 my $new;
1465 foreach my $role (keys %$ri) {
1466 my $propagate = $ri->{$role};
1467 if ($final || $propagate) {
1468 #print "APPLY ROLE $p $user $role\n";
1469 $new = {} if !$new;
1470 $new->{$role} = $propagate;
1471 }
1472 }
1473 if ($new) {
1474 $roles = $new; # overwrite previous settings
1475 next; # user privs always override group privs
1476 }
1477 }
1478
1479 my $new;
1480 foreach my $g (keys %{$acl->{groups}}) {
1481 next if !$cfg->{groups}->{$g}->{users}->{$user};
1482 if (my $ri = $acl->{groups}->{$g}) {
1483 foreach my $role (keys %$ri) {
1484 my $propagate = $ri->{$role};
1485 if ($final || $propagate) {
1486 #print "APPLY ROLE $p \@$g $role\n";
1487 $new = {} if !$new;
1488 $new->{$role} = $propagate;
1489 }
1490 }
1491 }
1492 }
1493 if ($new) {
1494 $roles = $new; # overwrite previous settings
1495 next;
1496 }
1497 }
1498
1499 return { 'NoAccess' => $roles->{NoAccess} } if defined ($roles->{NoAccess});
1500 #return () if defined ($roles->{NoAccess});
1501
1502 #print "permission $user $path = " . Dumper ($roles);
1503
1504 #print "roles $user $path = " . join (',', @ra) . "\n";
1505
1506 return $roles;
1507 }
1508
1509 sub remove_vm_access {
1510 my ($vmid) = @_;
1511 my $delVMaccessFn = sub {
1512 my $usercfg = cfs_read_file("user.cfg");
1513 my $modified;
1514
1515 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1516 delete $usercfg->{acl}->{"/vms/$vmid"};
1517 $modified = 1;
1518 }
1519 if (my $pool = $usercfg->{vms}->{$vmid}) {
1520 if (my $data = $usercfg->{pools}->{$pool}) {
1521 delete $data->{vms}->{$vmid};
1522 delete $usercfg->{vms}->{$vmid};
1523 $modified = 1;
1524 }
1525 }
1526 cfs_write_file("user.cfg", $usercfg) if $modified;
1527 };
1528
1529 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1530 }
1531
1532 sub remove_storage_access {
1533 my ($storeid) = @_;
1534
1535 my $deleteStorageAccessFn = sub {
1536 my $usercfg = cfs_read_file("user.cfg");
1537 my $modified;
1538
1539 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1540 delete $usercfg->{acl}->{"/storage/$storeid"};
1541 $modified = 1;
1542 }
1543 foreach my $pool (keys %{$usercfg->{pools}}) {
1544 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1545 $modified = 1;
1546 }
1547 cfs_write_file("user.cfg", $usercfg) if $modified;
1548 };
1549
1550 lock_user_config($deleteStorageAccessFn,
1551 "access permissions cleanup for storage $storeid failed");
1552 }
1553
1554 sub add_vm_to_pool {
1555 my ($vmid, $pool) = @_;
1556
1557 my $addVMtoPoolFn = sub {
1558 my $usercfg = cfs_read_file("user.cfg");
1559 if (my $data = $usercfg->{pools}->{$pool}) {
1560 $data->{vms}->{$vmid} = 1;
1561 $usercfg->{vms}->{$vmid} = $pool;
1562 cfs_write_file("user.cfg", $usercfg);
1563 }
1564 };
1565
1566 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1567 }
1568
1569 sub remove_vm_from_pool {
1570 my ($vmid) = @_;
1571
1572 my $delVMfromPoolFn = sub {
1573 my $usercfg = cfs_read_file("user.cfg");
1574 if (my $pool = $usercfg->{vms}->{$vmid}) {
1575 if (my $data = $usercfg->{pools}->{$pool}) {
1576 delete $data->{vms}->{$vmid};
1577 delete $usercfg->{vms}->{$vmid};
1578 cfs_write_file("user.cfg", $usercfg);
1579 }
1580 }
1581 };
1582
1583 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1584 }
1585
1586 my $USER_CONTROLLED_TFA_TYPES = {
1587 u2f => 1,
1588 oath => 1,
1589 };
1590
1591 # Delete an entry by setting $data=undef in which case $type is ignored.
1592 # Otherwise both must be valid.
1593 sub user_set_tfa {
1594 my ($userid, $realm, $type, $data, $cached_usercfg, $cached_domaincfg) = @_;
1595
1596 if (defined($data) && !defined($type)) {
1597 # This is an internal usage error and should not happen
1598 die "cannot set tfa data without a type\n";
1599 }
1600
1601 my $user_cfg = $cached_usercfg || cfs_read_file('user.cfg');
1602 my $user = $user_cfg->{users}->{$userid}
1603 or die "user '$userid' not found\n";
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 my $required_type = $realm_tfa->{type};
1615 if ($required_type ne $type) {
1616 die "realm '$realm' only allows TFA of type '$required_type\n";
1617 }
1618
1619 if (defined($data->{config})) {
1620 # XXX: Is it enough if the type matches? Or should the configuration also match?
1621 }
1622
1623 # realm-configured tfa always uses a simple key list, so use the user.cfg
1624 $user->{keys} = $data->{keys};
1625 } else {
1626 die "realm '$realm' does not allow removing the 2nd factor\n";
1627 }
1628 } else {
1629 # Without a realm-enforced TFA setting the user can add a u2f or totp entry by themselves.
1630 # The 'yubico' type requires yubico server settings, which have to be configured on the
1631 # realm, so this is not supported here:
1632 die "domain '$realm' does not support TFA type '$type'\n"
1633 if defined($data) && !$USER_CONTROLLED_TFA_TYPES->{$type};
1634 }
1635
1636 # Custom TFA entries are stored in priv/tfa.cfg as they can be more complet: u2f uses a
1637 # public key and a key handle, TOTP requires the usual totp settings...
1638
1639 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1640 my $tfa = ($tfa_cfg->{users}->{$userid} //= {});
1641
1642 if (defined($data)) {
1643 $tfa->{type} = $type;
1644 $tfa->{data} = $data;
1645 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1646
1647 $user->{keys} = "x!$type";
1648 } else {
1649 delete $tfa_cfg->{users}->{$userid};
1650 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1651
1652 delete $user->{keys};
1653 }
1654
1655 cfs_write_file('user.cfg', $user_cfg);
1656 }
1657
1658 sub user_get_tfa {
1659 my ($username, $realm) = @_;
1660
1661 my $user_cfg = cfs_read_file('user.cfg');
1662 my $user = $user_cfg->{users}->{$username}
1663 or die "user '$username' not found\n";
1664
1665 my $keys = $user->{keys};
1666
1667 my $domain_cfg = cfs_read_file('domains.cfg');
1668 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1669 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1670
1671 my $realm_tfa = $realm_cfg->{tfa};
1672 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
1673 if $realm_tfa;
1674
1675 if (!$keys) {
1676 return if !$realm_tfa;
1677 die "missing required 2nd keys\n";
1678 }
1679
1680 # new style config starts with an 'x' and optionally contains a !<type> suffix
1681 if ($keys !~ /^x(?:!.*)?$/) {
1682 # old style config, find the type via the realm
1683 return if !$realm_tfa;
1684 return ($realm_tfa->{type}, {
1685 keys => $keys,
1686 config => $realm_tfa,
1687 });
1688 } else {
1689 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1690 my $tfa = $tfa_cfg->{users}->{$username};
1691 return if !$tfa; # should not happen (user.cfg wasn't cleaned up?)
1692
1693 if ($realm_tfa) {
1694 # if the realm has a tfa setting we need to verify the type:
1695 die "auth domain '$realm' and user have mismatching TFA settings\n"
1696 if $realm_tfa && $realm_tfa->{type} ne $tfa->{type};
1697 }
1698
1699 return ($tfa->{type}, $tfa->{data});
1700 }
1701 }
1702
1703 # bash completion helpers
1704
1705 register_standard_option('userid-completed',
1706 get_standard_option('userid', { completion => \&complete_username}),
1707 );
1708
1709 sub complete_username {
1710
1711 my $user_cfg = cfs_read_file('user.cfg');
1712
1713 return [ keys %{$user_cfg->{users}} ];
1714 }
1715
1716 sub complete_group {
1717
1718 my $user_cfg = cfs_read_file('user.cfg');
1719
1720 return [ keys %{$user_cfg->{groups}} ];
1721 }
1722
1723 sub complete_realm {
1724
1725 my $domain_cfg = cfs_read_file('domains.cfg');
1726
1727 return [ keys %{$domain_cfg->{ids}} ];
1728 }
1729
1730 1;