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