]> git.proxmox.com Git - pve-access-control.git/blame - src/PVE/AccessControl.pm
update read_user_tfa_type call
[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 21
57098eb8
WB
22use PVE::RS::TFA;
23
5bb4e06a
DM
24use PVE::Auth::Plugin;
25use PVE::Auth::AD;
26use PVE::Auth::LDAP;
27use PVE::Auth::PVE;
28use PVE::Auth::PAM;
52d1c1b9 29use PVE::Auth::OpenId;
2c3a6c0a 30
5bb4e06a
DM
31# load and initialize all plugins
32
33PVE::Auth::AD->register();
34PVE::Auth::LDAP->register();
35PVE::Auth::PVE->register();
36PVE::Auth::PAM->register();
52d1c1b9 37PVE::Auth::OpenId->register();
5bb4e06a
DM
38PVE::Auth::Plugin->init();
39
2c3a6c0a
DM
40# $authdir must be writable by root only!
41my $confdir = "/etc/pve";
42my $authdir = "$confdir/priv";
21800a71 43
2c3a6c0a
DM
44my $pve_www_key_fn = "$confdir/pve-www.key";
45
21800a71
FG
46my $pve_auth_key_files = {
47 priv => "$authdir/authkey.key",
48 pub => "$confdir/authkey.pub",
49 pubold => "$confdir/authkey.pub.old",
50};
51
52my $pve_auth_key_cache = {};
53
243262f1 54my $ticket_lifetime = 3600 * 2; # 2 hours
8304b226 55my $auth_graceperiod = 60 * 5; # 5 minutes
243262f1 56my $authkey_lifetime = 3600 * 24; # rotate every 24 hours
2c3a6c0a
DM
57
58Crypt::OpenSSL::RSA->import_random_seed();
59
d7e8d24e
TL
60cfs_register_file('user.cfg', \&parse_user_config, \&write_user_config);
61cfs_register_file('priv/tfa.cfg', \&parse_priv_tfa_config, \&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
35c3ca0f 435 my $user = $usercfg->{users}->{$username};
35c3ca0f 436 my $token_info = $user->{tokens}->{$token};
8a724f7b
DM
437
438 my $ctime = time();
35c3ca0f
FG
439 die "token expired\n" if $token_info->{expire} && ($token_info->{expire} < $ctime);
440
441 die "invalid token value!\n" if !PVE::Cluster::verify_token($tokenid, $value);
442
443 return wantarray ? ($tokenid) : $tokenid;
444}
445
446
adf8d771
DM
447# VNC tickets
448# - they do not contain the username in plain text
449# - they are restricted to a specific resource path (example: '/vms/100')
450sub assemble_vnc_ticket {
451 my ($username, $path) = @_;
452
453 my $rsa_priv = get_privkey();
454
adf8d771
DM
455 $path = normalize_path($path);
456
a1f8aaae 457 my $secret_data = "$username:$path";
adf8d771 458
a1f8aaae
DM
459 return PVE::Ticket::assemble_rsa_ticket(
460 $rsa_priv, 'PVEVNC', undef, $secret_data);
adf8d771
DM
461}
462
463sub verify_vnc_ticket {
464 my ($ticket, $username, $path, $noerr) = @_;
465
a1f8aaae 466 my $secret_data = "$username:$path";
adf8d771 467
21800a71 468 my ($rsa_pub, $rsa_mtime) = get_pubkey();
5efff6c1 469 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime && $authkey_lifetime > 0)) {
21800a71
FG
470 if ($noerr) {
471 return undef;
472 } else {
473 # raise error via undef ticket
474 PVE::Ticket::verify_rsa_ticket($rsa_pub, 'PVEVNC');
475 }
476 }
477
a1f8aaae
DM
478 return PVE::Ticket::verify_rsa_ticket(
479 $rsa_pub, 'PVEVNC', $ticket, $secret_data, -20, 40, $noerr);
adf8d771
DM
480}
481
23b35225 482sub assemble_spice_ticket {
bf3e6d31 483 my ($username, $vmid, $node) = @_;
23b35225 484
3f62bdbe 485 my $secret = &$get_csrfr_secret();
23b35225 486
a1f8aaae
DM
487 return PVE::Ticket::assemble_spice_ticket(
488 $secret, $username, $vmid, $node);
bf3e6d31
DM
489}
490
491sub verify_spice_connect_url {
492 my ($connect_str) = @_;
493
a1f8aaae 494 my $secret = &$get_csrfr_secret();
bf3e6d31 495
a1f8aaae 496 return PVE::Ticket::verify_spice_connect_url($secret, $connect_str);
23b35225
AD
497}
498
cee5583b
DM
499sub read_x509_subject_spice {
500 my ($filename) = @_;
501
502 # read x509 subject
503 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
44903703
FG
504 die "Could not open $filename using OpenSSL\n"
505 if !$bio;
506
cee5583b
DM
507 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
508 Net::SSLeay::BIO_free($bio);
44903703
FG
509
510 die "Could not parse X509 certificate in $filename\n"
511 if !$x509;
512
cee5583b
DM
513 my $nameobj = Net::SSLeay::X509_get_subject_name($x509);
514 my $subject = Net::SSLeay::X509_NAME_oneline($nameobj);
515 Net::SSLeay::X509_free($x509);
66931b11 516
cee5583b
DM
517 # remote-viewer wants comma as seperator (not '/')
518 $subject =~ s!^/!!;
519 $subject =~ s!/(\w+=)!,$1!g;
520
521 return $subject;
522}
523
524# helper to generate SPICE remote-viewer configuration
525sub remote_viewer_config {
526 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
527
528 if (!$proxy) {
529 my $host = `hostname -f` || PVE::INotify::nodename();
530 chomp $host;
531 $proxy = $host;
532 }
533
534 my ($ticket, $proxyticket) = assemble_spice_ticket($authuser, $vmid, $node);
535
536 my $filename = "/etc/pve/local/pve-ssl.pem";
537 my $subject = read_x509_subject_spice($filename);
538
539 my $cacert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192);
540 $cacert =~ s/\n/\\n/g;
63691fc6 541
25167526 542 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
cee5583b 543 my $config = {
63691fc6
DM
544 'secure-attention' => "Ctrl+Alt+Ins",
545 'toggle-fullscreen' => "Shift+F11",
546 'release-cursor' => "Ctrl+Alt+R",
cee5583b
DM
547 type => 'spice',
548 title => $title,
1075c589 549 host => $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
cee5583b
DM
550 proxy => "http://$proxy:3128",
551 'tls-port' => $port,
552 'host-subject' => $subject,
553 ca => $cacert,
554 password => $ticket,
555 'delete-this-file' => 1,
556 };
557
558 return ($ticket, $proxyticket, $config);
559}
560
37d45deb 561sub check_user_exist {
7070c1ae 562 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 563
5bb4e06a 564 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 565 return undef if !$username;
66931b11 566
37d45deb
DM
567 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
568
569 die "no such user ('$username')\n" if !$noerr;
66931b11 570
37d45deb
DM
571 return undef;
572}
573
574sub check_user_enabled {
575 my ($usercfg, $username, $noerr) = @_;
576
577 my $data = check_user_exist($usercfg, $username, $noerr);
578 return undef if !$data;
579
580 return 1 if $data->{enable};
2c3a6c0a 581
37d45deb 582 die "user '$username' is disabled\n" if !$noerr;
66931b11 583
8a724f7b
DM
584 my $ctime = time();
585 my $expire = $usercfg->{users}->{$username}->{expire};
586
587 die "account expired\n" if $expire && ($expire < $ctime);
588
7070c1ae 589 return undef;
2c3a6c0a
DM
590}
591
571e9d06
FG
592sub check_token_exist {
593 my ($usercfg, $username, $tokenid, $noerr) = @_;
594
595 my $user = check_user_exist($usercfg, $username, $noerr);
596 return undef if !$user;
597
598 return $user->{tokens}->{$tokenid}
599 if defined($user->{tokens}) && $user->{tokens}->{$tokenid};
600
601 die "no such token '$tokenid' for user '$username'\n" if !$noerr;
602
603 return undef;
604}
605
96f8ebd6 606sub verify_one_time_pw {
fda8ca85 607 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
96f8ebd6 608
1075c589 609 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
96f8ebd6
DM
610
611 # fixme: proxy support?
612 my $proxy;
613
614 if ($type eq 'yubico') {
972859d1
DM
615 PVE::OTP::yubico_verify_otp($otp, $keys, $tfa_cfg->{url},
616 $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
1abc2c0a 617 } elsif ($type eq 'oath') {
972859d1 618 PVE::OTP::oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
96f8ebd6
DM
619 } else {
620 die "unknown tfa type '$type'\n";
621 }
96f8ebd6
DM
622}
623
2c3a6c0a 624# password should be utf8 encoded
1075c589 625# Note: some plugins delay/sleep if auth fails
2c3a6c0a 626sub authenticate_user {
96f8ebd6 627 my ($username, $password, $otp) = @_;
2c3a6c0a
DM
628
629 die "no username specified\n" if !$username;
66931b11 630
5bb4e06a 631 my ($ruid, $realm);
2c3a6c0a 632
5bb4e06a 633 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
2c3a6c0a
DM
634
635 my $usercfg = cfs_read_file('user.cfg');
636
6126ab75 637 check_user_enabled($usercfg, $username);
2c3a6c0a 638
5bb4e06a 639 my $domain_cfg = cfs_read_file('domains.cfg');
2c3a6c0a 640
6126ab75 641 my $cfg = $domain_cfg->{ids}->{$realm};
3443faca 642 die "auth domain '$realm' does not exist\n" if !$cfg;
6126ab75
DM
643 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
644 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
2c3a6c0a 645
fda8ca85
WB
646 my ($type, $tfa_data) = user_get_tfa($username, $realm);
647 if ($type) {
648 if ($type eq 'u2f') {
649 # Note that if the user did not manage to complete the initial u2f registration
650 # challenge we have a hash containing a 'challenge' entry in the user's tfa.cfg entry:
f25628d3
WB
651 $tfa_data = undef if exists $tfa_data->{challenge};
652 } elsif (!defined($otp)) {
653 # The user requires a 2nd factor but has not provided one. Return success but
654 # don't clear $tfa_data.
fda8ca85
WB
655 } else {
656 my $keys = $tfa_data->{keys};
657 my $tfa_cfg = $tfa_data->{config};
658 verify_one_time_pw($type, $username, $keys, $tfa_cfg, $otp);
f25628d3
WB
659 $tfa_data = undef;
660 }
661
662 # Return the type along with the rest:
663 if ($tfa_data) {
664 $tfa_data = {
665 type => $type,
666 data => $tfa_data,
667 };
fda8ca85 668 }
96f8ebd6
DM
669 }
670
f25628d3 671 return wantarray ? ($username, $tfa_data) : $username;
2c3a6c0a
DM
672}
673
674sub domain_set_password {
5bb4e06a 675 my ($realm, $username, $password) = @_;
2c3a6c0a
DM
676
677 die "no auth domain specified" if !$realm;
678
5bb4e06a
DM
679 my $domain_cfg = cfs_read_file('domains.cfg');
680
681 my $cfg = $domain_cfg->{ids}->{$realm};
1075c589 682 die "auth domain '$realm' does not exist\n" if !$cfg;
5bb4e06a
DM
683 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
684 $plugin->store_password($cfg, $realm, $username, $password);
2c3a6c0a
DM
685}
686
687sub add_user_group {
2c3a6c0a 688 my ($username, $usercfg, $group) = @_;
66931b11 689
2c3a6c0a
DM
690 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
691 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
692}
693
694sub delete_user_group {
2c3a6c0a 695 my ($username, $usercfg) = @_;
66931b11 696
2c3a6c0a
DM
697 foreach my $group (keys %{$usercfg->{groups}}) {
698
66931b11 699 delete ($usercfg->{groups}->{$group}->{users}->{$username})
2c3a6c0a
DM
700 if $usercfg->{groups}->{$group}->{users}->{$username};
701 }
702}
703
704sub delete_user_acl {
2c3a6c0a
DM
705 my ($username, $usercfg) = @_;
706
707 foreach my $acl (keys %{$usercfg->{acl}}) {
708
66931b11 709 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
2c3a6c0a
DM
710 if $usercfg->{acl}->{$acl}->{users}->{$username};
711 }
2c3a6c0a 712}
39c85db8 713
2c3a6c0a 714sub delete_group_acl {
2c3a6c0a
DM
715 my ($group, $usercfg) = @_;
716
717 foreach my $acl (keys %{$usercfg->{acl}}) {
718
66931b11 719 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
2c3a6c0a
DM
720 if $usercfg->{acl}->{$acl}->{groups}->{$group};
721 }
39c85db8
DM
722}
723
724sub delete_pool_acl {
39c85db8 725 my ($pool, $usercfg) = @_;
2c3a6c0a 726
39c85db8
DM
727 my $path = "/pool/$pool";
728
3b4a3f94 729 delete ($usercfg->{acl}->{$path})
2c3a6c0a
DM
730}
731
732# we automatically create some predefined roles by splitting privs
733# into 3 groups (per category)
734# root: only root is allowed to do that
735# admin: an administrator can to that
1075c589 736# user: a normal user/customer can to that
2c3a6c0a
DM
737my $privgroups = {
738 VM => {
739 root => [],
66931b11
DM
740 admin => [
741 'VM.Config.Disk',
742 'VM.Config.CPU',
743 'VM.Config.Memory',
744 'VM.Config.Network',
c0fead8c 745 'VM.Config.HWType',
66931b11
DM
746 'VM.Config.Options', # covers all other things
747 'VM.Allocate',
748 'VM.Clone',
2c3a6c0a 749 'VM.Migrate',
66931b11
DM
750 'VM.Monitor',
751 'VM.Snapshot',
aad513f6 752 'VM.Snapshot.Rollback',
2c3a6c0a
DM
753 ],
754 user => [
cc7bdf33 755 'VM.Config.CDROM', # change CDROM media
cb381abc 756 'VM.Config.Cloudinit',
66931b11 757 'VM.Console',
68d5a86d 758 'VM.Backup',
2c3a6c0a
DM
759 'VM.PowerMgmt',
760 ],
66931b11 761 audit => [
82b63965 762 'VM.Audit',
2c3a6c0a
DM
763 ],
764 },
765 Sys => {
766 root => [
66931b11 767 'Sys.PowerMgmt',
37d45deb 768 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
769 ],
770 admin => [
2e376c58 771 'Permissions.Modify',
66931b11 772 'Sys.Console',
2c3a6c0a
DM
773 'Sys.Syslog',
774 ],
775 user => [],
776 audit => [
777 'Sys.Audit',
778 ],
779 },
780 Datastore => {
2e376c58 781 root => [],
19f60b5e
DM
782 admin => [
783 'Datastore.Allocate',
373cb383 784 'Datastore.AllocateTemplate',
19f60b5e 785 ],
2c3a6c0a
DM
786 user => [
787 'Datastore.AllocateSpace',
788 ],
789 audit => [
790 'Datastore.Audit',
791 ],
792 },
40672671
AD
793 SDN => {
794 root => [],
795 admin => [
796 'SDN.Allocate',
797 'SDN.Audit',
798 ],
799 audit => [
800 'SDN.Audit',
801 ],
802 },
12683df7 803 User => {
82b63965
DM
804 root => [
805 'Realm.Allocate',
806 ],
12683df7
DM
807 admin => [
808 'User.Modify',
82b63965 809 'Group.Allocate', # edit/change group settings
66931b11 810 'Realm.AllocateUser',
19f60b5e 811 ],
12683df7
DM
812 user => [],
813 audit => [],
814 },
dee1c882
DM
815 Pool => {
816 root => [],
817 admin => [
818 'Pool.Allocate', # create/delete pools
819 ],
6d048ad6
LS
820 user => [
821 'Pool.Audit',
822 ],
823 audit => [
824 'Pool.Audit',
825 ],
dee1c882 826 },
2c3a6c0a
DM
827};
828
829my $valid_privs = {};
830
831my $special_roles = {
1075c589
FG
832 'NoAccess' => {}, # no privileges
833 'Administrator' => $valid_privs, # all privileges
2c3a6c0a
DM
834};
835
836sub create_roles {
837
838 foreach my $cat (keys %$privgroups) {
839 my $cd = $privgroups->{$cat};
66931b11 840 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
2c3a6c0a
DM
841 @{$cd->{user}}, @{$cd->{audit}}) {
842 $valid_privs->{$p} = 1;
843 }
844 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
845
846 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
847 $special_roles->{"PVEAdmin"}->{$p} = 1;
848 }
849 if (scalar(@{$cd->{user}})) {
850 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
851 $special_roles->{"PVE${cat}User"}->{$p} = 1;
852 }
853 }
854 foreach my $p (@{$cd->{audit}}) {
855 $special_roles->{"PVEAuditor"}->{$p} = 1;
856 }
857 }
ff4b2235 858
7b395f99 859 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
860};
861
862create_roles();
863
0fea3f16
DC
864sub create_priv_properties {
865 my $properties = {};
866 foreach my $priv (keys %$valid_privs) {
867 $properties->{$priv} = {
868 type => 'boolean',
869 optional => 1,
870 };
871 }
872 return $properties;
873}
874
894e6f0c
PA
875sub role_is_special {
876 my ($role) = @_;
b7ba86d4 877 return (exists $special_roles->{$role}) ? 1 : 0;
894e6f0c
PA
878}
879
2c3a6c0a
DM
880sub add_role_privs {
881 my ($role, $usercfg, $privs) = @_;
882
883 return if !$privs;
884
885 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
886
887 foreach my $priv (split_list($privs)) {
888 if (defined ($valid_privs->{$priv})) {
889 $usercfg->{roles}->{$role}->{$priv} = 1;
890 } else {
1075c589 891 die "invalid privilege '$priv'\n";
66931b11
DM
892 }
893 }
2c3a6c0a
DM
894}
895
eb41d200 896sub lookup_username {
f335d265 897 my ($username, $noerr) = @_;
eb41d200
WL
898
899 $username =~ m!^(${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex})$!;
900
901 my $realm = $2;
902 my $domain_cfg = cfs_read_file("domains.cfg");
903 my $casesensitive = $domain_cfg->{ids}->{$realm}->{'case-sensitive'} // 1;
904 my $usercfg = cfs_read_file('user.cfg');
905
906 if (!$casesensitive) {
907 my @matches = grep { lc $username eq lc $_ } (keys %{$usercfg->{users}});
908
909 die "ambiguous case insensitive match of username '$username', cannot safely grant access!\n"
f335d265 910 if scalar @matches > 1 && !$noerr;
eb41d200
WL
911
912 return $matches[0]
913 }
914
915 return $username;
916}
917
2c3a6c0a
DM
918sub normalize_path {
919 my $path = shift;
920
4bc17477 921 $path =~ s|/+|/|g;
2c3a6c0a
DM
922
923 $path =~ s|/$||;
924
925 $path = '/' if !$path;
926
4bc17477
DM
927 $path = "/$path" if $path !~ m|^/|;
928
e4f8fc2e 929 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
2c3a6c0a
DM
930
931 return $path;
66931b11 932}
2c3a6c0a 933
20c60513 934sub check_path {
91c30089
TL
935 my ($path) = @_;
936 return $path =~ m!^(
20c60513
LS
937 /
938 |/access
939 |/access/groups
8737ff37 940 |/access/groups/[[:alnum:]\.\-\_]+
20c60513 941 |/access/realm
8737ff37 942 |/access/realm/[[:alnum:]\.\-\_]+
20c60513
LS
943 |/nodes
944 |/nodes/[[:alnum:]\.\-\_]+
945 |/pool
946 |/pool/[[:alnum:]\.\-\_]+
947 |/sdn
0a06acb1 948 |/sdn/zones/[[:alnum:]\.\-\_]+
4100ba8d 949 |/sdn/vnets/[[:alnum:]\.\-\_]+
20c60513
LS
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
57098eb8
WB
1358# Creates a `PVE::RS::TFA` instance from the raw config data.
1359# Its contained hash will also support the legacy functionality.
fda8ca85
WB
1360sub parse_priv_tfa_config {
1361 my ($filename, $raw) = @_;
1362
fda8ca85 1363 $raw = '' if !defined($raw);
57098eb8 1364 my $cfg = PVE::RS::TFA->new($raw);
fda8ca85 1365
57098eb8
WB
1366 # Purge invalid users:
1367 foreach my $user ($cfg->users()->@*) {
fda8ca85
WB
1368 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1369 if (!$realm) {
1370 warn "user tfa config - ignore user '$user' - invalid user name\n";
57098eb8 1371 $cfg->remove_user($user);
fda8ca85 1372 }
fda8ca85
WB
1373 }
1374
1375 return $cfg;
1376}
1377
1378sub write_priv_tfa_config {
1379 my ($filename, $cfg) = @_;
1380
57098eb8
WB
1381 # FIXME: Only allow this if the complete cluster has been upgraded to understand the json
1382 # config format.
1383 return $cfg->write();
fda8ca85
WB
1384}
1385
2c3a6c0a
DM
1386sub roles {
1387 my ($cfg, $user, $path) = @_;
1388
66931b11 1389 # NOTE: we do not consider pools here.
e915e9e4
FG
1390 # NOTE: for privsep tokens, this does not filter roles by those that the
1391 # corresponding user has.
a31f1d85 1392 # Use $rpcenv->permission() for any actual permission checks!
4bc17477 1393
2c3a6c0a
DM
1394 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1395
e915e9e4
FG
1396 if (pve_verify_tokenid($user, 1)) {
1397 my $tokenid = $user;
1398 my ($username, $token) = split_tokenid($tokenid);
1399
1400 my $token_info = $cfg->{users}->{$username}->{tokens}->{$token};
1401 return () if !$token_info;
1402
7e8bcaa7 1403 my $user_roles = roles($cfg, $username, $path);
e915e9e4
FG
1404
1405 # return full user privileges
7e8bcaa7 1406 return $user_roles if !$token_info->{privsep};
e915e9e4
FG
1407 }
1408
7e8bcaa7 1409 my $roles = {};
2c3a6c0a
DM
1410
1411 foreach my $p (sort keys %{$cfg->{acl}}) {
1412 my $final = ($path eq $p);
1413
1414 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1415
1416 my $acl = $cfg->{acl}->{$p};
1417
1418 #print "CHECKACL $path $p\n";
1419 #print "ACL $path = " . Dumper ($acl);
e915e9e4
FG
1420 if (my $ri = $acl->{tokens}->{$user}) {
1421 my $new;
1422 foreach my $role (keys %$ri) {
1423 my $propagate = $ri->{$role};
1424 if ($final || $propagate) {
1425 #print "APPLY ROLE $p $user $role\n";
1426 $new = {} if !$new;
7e8bcaa7 1427 $new->{$role} = $propagate;
e915e9e4
FG
1428 }
1429 }
1430 if ($new) {
7e8bcaa7 1431 $roles = $new; # overwrite previous settings
e915e9e4
FG
1432 next;
1433 }
1434 }
2c3a6c0a
DM
1435
1436 if (my $ri = $acl->{users}->{$user}) {
1437 my $new;
1438 foreach my $role (keys %$ri) {
1439 my $propagate = $ri->{$role};
1440 if ($final || $propagate) {
1441 #print "APPLY ROLE $p $user $role\n";
1442 $new = {} if !$new;
7e8bcaa7 1443 $new->{$role} = $propagate;
2c3a6c0a
DM
1444 }
1445 }
1446 if ($new) {
7e8bcaa7 1447 $roles = $new; # overwrite previous settings
2c3a6c0a
DM
1448 next; # user privs always override group privs
1449 }
1450 }
1451
1452 my $new;
1453 foreach my $g (keys %{$acl->{groups}}) {
1454 next if !$cfg->{groups}->{$g}->{users}->{$user};
1455 if (my $ri = $acl->{groups}->{$g}) {
1456 foreach my $role (keys %$ri) {
1457 my $propagate = $ri->{$role};
1458 if ($final || $propagate) {
1459 #print "APPLY ROLE $p \@$g $role\n";
1460 $new = {} if !$new;
7e8bcaa7 1461 $new->{$role} = $propagate;
2c3a6c0a
DM
1462 }
1463 }
1464 }
1465 }
1466 if ($new) {
7e8bcaa7 1467 $roles = $new; # overwrite previous settings
2c3a6c0a
DM
1468 next;
1469 }
2c3a6c0a
DM
1470 }
1471
7e8bcaa7
FG
1472 return { 'NoAccess' => $roles->{NoAccess} } if defined ($roles->{NoAccess});
1473 #return () if defined ($roles->{NoAccess});
66931b11 1474
7e8bcaa7 1475 #print "permission $user $path = " . Dumper ($roles);
2c3a6c0a
DM
1476
1477 #print "roles $user $path = " . join (',', @ra) . "\n";
1478
7e8bcaa7 1479 return $roles;
2c3a6c0a 1480}
66931b11 1481
3b4a3f94
AG
1482sub remove_vm_access {
1483 my ($vmid) = @_;
1484 my $delVMaccessFn = sub {
1485 my $usercfg = cfs_read_file("user.cfg");
57a70473 1486 my $modified;
3b4a3f94 1487
57a70473
DM
1488 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1489 delete $usercfg->{acl}->{"/vms/$vmid"};
1490 $modified = 1;
3b4a3f94
AG
1491 }
1492 if (my $pool = $usercfg->{vms}->{$vmid}) {
1493 if (my $data = $usercfg->{pools}->{$pool}) {
1494 delete $data->{vms}->{$vmid};
1495 delete $usercfg->{vms}->{$vmid};
57a70473 1496 $modified = 1;
3b4a3f94
AG
1497 }
1498 }
57a70473 1499 cfs_write_file("user.cfg", $usercfg) if $modified;
3b4a3f94
AG
1500 };
1501
1502 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1503}
1504
60844761
AG
1505sub remove_storage_access {
1506 my ($storeid) = @_;
1507
1508 my $deleteStorageAccessFn = sub {
1509 my $usercfg = cfs_read_file("user.cfg");
1510 my $modified;
1511
1512 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1513 delete $usercfg->{acl}->{"/storage/$storeid"};
1514 $modified = 1;
1515 }
1516 foreach my $pool (keys %{$usercfg->{pools}}) {
1517 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1518 $modified = 1;
1519 }
1520 cfs_write_file("user.cfg", $usercfg) if $modified;
1521 };
1522
1523 lock_user_config($deleteStorageAccessFn,
1524 "access permissions cleanup for storage $storeid failed");
1525}
1526
018ae3a9
DM
1527sub add_vm_to_pool {
1528 my ($vmid, $pool) = @_;
1529
1530 my $addVMtoPoolFn = sub {
1531 my $usercfg = cfs_read_file("user.cfg");
1532 if (my $data = $usercfg->{pools}->{$pool}) {
1533 $data->{vms}->{$vmid} = 1;
1534 $usercfg->{vms}->{$vmid} = $pool;
1535 cfs_write_file("user.cfg", $usercfg);
1536 }
1537 };
1538
1539 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1540}
1541
1542sub remove_vm_from_pool {
1543 my ($vmid) = @_;
66931b11 1544
018ae3a9
DM
1545 my $delVMfromPoolFn = sub {
1546 my $usercfg = cfs_read_file("user.cfg");
1547 if (my $pool = $usercfg->{vms}->{$vmid}) {
1548 if (my $data = $usercfg->{pools}->{$pool}) {
1549 delete $data->{vms}->{$vmid};
1550 delete $usercfg->{vms}->{$vmid};
1551 cfs_write_file("user.cfg", $usercfg);
1552 }
1553 }
1554 };
1555
1556 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1557}
1558
49b15310 1559my $USER_CONTROLLED_TFA_TYPES = {
fda8ca85
WB
1560 u2f => 1,
1561 oath => 1,
1562};
1563
1564# Delete an entry by setting $data=undef in which case $type is ignored.
1565# Otherwise both must be valid.
1566sub user_set_tfa {
1567 my ($userid, $realm, $type, $data, $cached_usercfg, $cached_domaincfg) = @_;
1568
1569 if (defined($data) && !defined($type)) {
1570 # This is an internal usage error and should not happen
1571 die "cannot set tfa data without a type\n";
1572 }
1573
1574 my $user_cfg = $cached_usercfg || cfs_read_file('user.cfg');
8ecf1a49 1575 my $user = $user_cfg->{users}->{$userid};
fda8ca85
WB
1576
1577 my $domain_cfg = $cached_domaincfg || cfs_read_file('domains.cfg');
1578 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1579 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1580
1581 my $realm_tfa = $realm_cfg->{tfa};
1582 if (defined($realm_tfa)) {
1583 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa);
1584 # If the realm has a TFA setting, we're only allowed to use that.
1585 if (defined($data)) {
8ecf1a49 1586 die "user '$userid' not found\n" if !defined($user);
fda8ca85
WB
1587 my $required_type = $realm_tfa->{type};
1588 if ($required_type ne $type) {
1589 die "realm '$realm' only allows TFA of type '$required_type\n";
1590 }
1591
1592 if (defined($data->{config})) {
1593 # XXX: Is it enough if the type matches? Or should the configuration also match?
1594 }
1595
1596 # realm-configured tfa always uses a simple key list, so use the user.cfg
1597 $user->{keys} = $data->{keys};
1598 } else {
8ecf1a49
TL
1599 # TFA is enforce by realm, only allow deletion if the whole user gets delete
1600 die "realm '$realm' does not allow removing the 2nd factor\n" if defined($user);
fda8ca85
WB
1601 }
1602 } else {
4aa4f0b3 1603 die "user '$userid' not found\n" if !defined($user) && defined($data);
fda8ca85
WB
1604 # Without a realm-enforced TFA setting the user can add a u2f or totp entry by themselves.
1605 # The 'yubico' type requires yubico server settings, which have to be configured on the
1606 # realm, so this is not supported here:
1607 die "domain '$realm' does not support TFA type '$type'\n"
49b15310 1608 if defined($data) && !$USER_CONTROLLED_TFA_TYPES->{$type};
fda8ca85
WB
1609 }
1610
1611 # Custom TFA entries are stored in priv/tfa.cfg as they can be more complet: u2f uses a
1612 # public key and a key handle, TOTP requires the usual totp settings...
1613
1614 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1615 my $tfa = ($tfa_cfg->{users}->{$userid} //= {});
1616
1617 if (defined($data)) {
1618 $tfa->{type} = $type;
1619 $tfa->{data} = $data;
1620 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1621
7e58c66d 1622 $user->{keys} = "x!$type";
fda8ca85
WB
1623 } else {
1624 delete $tfa_cfg->{users}->{$userid};
1625 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1626
8ecf1a49 1627 delete $user->{keys} if defined($user);
fda8ca85
WB
1628 }
1629
8ecf1a49 1630 cfs_write_file('user.cfg', $user_cfg) if defined($user);
fda8ca85
WB
1631}
1632
1633sub user_get_tfa {
1634 my ($username, $realm) = @_;
1635
1636 my $user_cfg = cfs_read_file('user.cfg');
1637 my $user = $user_cfg->{users}->{$username}
1638 or die "user '$username' not found\n";
1639
1640 my $keys = $user->{keys};
fda8ca85
WB
1641
1642 my $domain_cfg = cfs_read_file('domains.cfg');
1643 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1644 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1645
1646 my $realm_tfa = $realm_cfg->{tfa};
1647 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
1648 if $realm_tfa;
1649
6063b65b
WB
1650 if (!$keys) {
1651 return if !$realm_tfa;
1652 die "missing required 2nd keys\n";
1653 }
1654
7e58c66d 1655 # new style config starts with an 'x' and optionally contains a !<type> suffix
0a956b94 1656 if ($keys !~ /^x(?:!.*)?$/) {
fda8ca85
WB
1657 # old style config, find the type via the realm
1658 return if !$realm_tfa;
1659 return ($realm_tfa->{type}, {
1660 keys => $keys,
1661 config => $realm_tfa,
1662 });
1663 } else {
1664 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1665 my $tfa = $tfa_cfg->{users}->{$username};
1666 return if !$tfa; # should not happen (user.cfg wasn't cleaned up?)
1667
1668 if ($realm_tfa) {
1669 # if the realm has a tfa setting we need to verify the type:
1670 die "auth domain '$realm' and user have mismatching TFA settings\n"
1671 if $realm_tfa && $realm_tfa->{type} ne $tfa->{type};
1672 }
1673
1674 return ($tfa->{type}, $tfa->{data});
1675 }
1676}
1677
3e5bfdf6
DM
1678# bash completion helpers
1679
ab7b19b5
SI
1680register_standard_option('userid-completed',
1681 get_standard_option('userid', { completion => \&complete_username}),
1682);
1683
3e5bfdf6
DM
1684sub complete_username {
1685
1686 my $user_cfg = cfs_read_file('user.cfg');
1687
1688 return [ keys %{$user_cfg->{users}} ];
1689}
1690
1691sub complete_group {
1692
1693 my $user_cfg = cfs_read_file('user.cfg');
1694
1695 return [ keys %{$user_cfg->{groups}} ];
1696}
1697
1698sub complete_realm {
1699
1700 my $domain_cfg = cfs_read_file('domains.cfg');
1701
1702 return [ keys %{$domain_cfg->{ids}} ];
1703}
1704
2c3a6c0a 17051;