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