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