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