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