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