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