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