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