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