]> git.proxmox.com Git - pve-access-control.git/blob - src/PVE/AccessControl.pm
drop assert_new_tfa_config_available for Proxmox VE 8
[pve-access-control.git] / src / PVE / AccessControl.pm
1 package PVE::AccessControl;
2
3 use strict;
4 use warnings;
5 use Encode;
6 use Crypt::OpenSSL::Random;
7 use Crypt::OpenSSL::RSA;
8 use Net::SSLeay;
9 use Net::IP;
10 use MIME::Base32;
11 use MIME::Base64;
12 use Digest::SHA;
13 use IO::File;
14 use File::stat;
15 use JSON;
16 use Scalar::Util 'weaken';
17 use URI::Escape;
18
19 use PVE::OTP;
20 use PVE::Ticket;
21 use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
22 use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
23 use PVE::JSONSchema qw(register_standard_option get_standard_option);
24
25 use PVE::RS::TFA;
26
27 use PVE::Auth::Plugin;
28 use PVE::Auth::AD;
29 use PVE::Auth::LDAP;
30 use PVE::Auth::PVE;
31 use PVE::Auth::PAM;
32 use PVE::Auth::OpenId;
33
34 # load and initialize all plugins
35
36 PVE::Auth::AD->register();
37 PVE::Auth::LDAP->register();
38 PVE::Auth::PVE->register();
39 PVE::Auth::PAM->register();
40 PVE::Auth::OpenId->register();
41 PVE::Auth::Plugin->init();
42
43 # $authdir must be writable by root only!
44 my $confdir = "/etc/pve";
45 my $authdir = "$confdir/priv";
46
47 my $pve_www_key_fn = "$confdir/pve-www.key";
48
49 my $pve_auth_key_files = {
50 priv => "$authdir/authkey.key",
51 pub => "$confdir/authkey.pub",
52 pubold => "$confdir/authkey.pub.old",
53 };
54
55 my $pve_auth_key_cache = {};
56
57 my $ticket_lifetime = 3600 * 2; # 2 hours
58 my $auth_graceperiod = 60 * 5; # 5 minutes
59 my $authkey_lifetime = 3600 * 24; # rotate every 24 hours
60
61 Crypt::OpenSSL::RSA->import_random_seed();
62
63 cfs_register_file('user.cfg', \&parse_user_config, \&write_user_config);
64 cfs_register_file('priv/tfa.cfg', \&parse_priv_tfa_config, \&write_priv_tfa_config);
65
66 sub verify_username {
67 PVE::Auth::Plugin::verify_username(@_);
68 }
69
70 sub pve_verify_realm {
71 PVE::Auth::Plugin::pve_verify_realm(@_);
72 }
73
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!
78 my $user_config_locked;
79 sub lock_user_config {
80 my ($code, $errmsg) = @_;
81
82 my $locked = 1;
83 $user_config_locked = \$locked;
84 weaken $user_config_locked; # make this scope guard signal safe...
85
86 cfs_lock_file("user.cfg", undef, $code);
87 $user_config_locked = undef;
88 if (my $err = $@) {
89 $errmsg ? die "$errmsg: $err" : die $err;
90 }
91 }
92
93 sub lock_tfa_config {
94 my ($code, $errmsg) = @_;
95
96 die "tfa config lock cannot be acquired while holding user config lock\n"
97 if ($user_config_locked && $$user_config_locked);
98
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
107 my $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
146 sub get_pubkey {
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
157 sub get_privkey {
158 my $res = $cache_read_key->('priv');
159
160 if (!defined($res) || !check_authkey(1)) {
161 rotate_authkey();
162 $res = $cache_read_key->('priv');
163 }
164
165 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
166 }
167
168 sub 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 {
179 my $now = time();
180 if ($now - $mtime >= $authkey_lifetime) {
181 warn "auth key pair too old, rotating..\n" if !$quiet;;
182 return 0;
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;
195 } else {
196 warn "auth key new enough, skipping rotation\n" if !$quiet;;
197 return 1;
198 }
199 }
200 }
201
202 sub rotate_authkey {
203 return if $authkey_lifetime == 0;
204
205 PVE::Cluster::cfs_lock_authkey(undef, sub {
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.
216 return if check_authkey();
217
218 my $old = get_pubkey();
219 my $new = Crypt::OpenSSL::RSA->generate_key(2048);
220
221 if ($old) {
222 eval {
223 my $pem = $old->get_public_key_x509_string();
224 # mtime is used for caching and ticket age range calculation
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
230 eval {
231 my $pem = $new->get_public_key_x509_string();
232 # mtime is used for caching and ticket age range calculation,
233 # should be close to that of pubold above
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 $@;
262 }
263
264 PVE::JSONSchema::register_standard_option('tokenid', {
265 description => "API token identifier.",
266 type => "string",
267 format => "pve-tokenid",
268 });
269
270 our $token_subid_regex = $PVE::Auth::Plugin::realm_regex;
271
272 # username@realm username realm tokenid
273 our $token_full_regex = qr/((${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex}))!(${token_subid_regex})/;
274
275 our $userid_or_token_regex = qr/^$PVE::Auth::Plugin::user_regex\@$PVE::Auth::Plugin::realm_regex(?:!$token_subid_regex)?$/;
276
277 sub 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
289 sub join_tokenid {
290 my ($username, $tokensubid) = @_;
291
292 my $joined = "${username}!${tokensubid}";
293
294 return pve_verify_tokenid($joined);
295 }
296
297 PVE::JSONSchema::register_format('pve-tokenid', \&pve_verify_tokenid);
298 sub 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
311 my $csrf_prevention_secret;
312 my $csrf_prevention_secret_legacy;
313 my $get_csrfr_secret = sub {
314 if (!$csrf_prevention_secret) {
315 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
316 $csrf_prevention_secret = Digest::SHA::hmac_sha256_base64($input);
317 $csrf_prevention_secret_legacy = Digest::SHA::sha1_base64($input);
318 }
319 return $csrf_prevention_secret;
320 };
321
322 sub assemble_csrf_prevention_token {
323 my ($username) = @_;
324
325 my $secret = &$get_csrfr_secret();
326
327 return PVE::Ticket::assemble_csrf_prevention_token ($secret, $username);
328 }
329
330 sub verify_csrf_prevention_token {
331 my ($username, $token, $noerr) = @_;
332
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 }
343
344 return PVE::Ticket::verify_csrf_prevention_token(
345 $secret, $username, $token, -$auth_graceperiod, $ticket_lifetime, $noerr);
346 }
347
348 my $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
354 my $min = -$auth_graceperiod;
355 my $max = $ticket_lifetime;
356
357 if ($rotated) {
358 # ticket creation after rotation is not allowed
359 $min = $key_age - $auth_graceperiod;
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
370 $max = $key_age + $auth_graceperiod if $key_age < $ticket_lifetime;
371 }
372
373 return undef if $min > $ticket_lifetime;
374 return ($min, $max);
375 };
376
377 sub assemble_ticket : prototype($;$) {
378 my ($data, $aad) = @_;
379
380 my $rsa_priv = get_privkey();
381
382 return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $data, $aad);
383 }
384
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.
392 sub verify_ticket : prototype($;$$) {
393 my ($ticket, $noerr, $tfa_ticket_aad) = @_;
394
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);
404 return undef if !defined($min);
405
406 return PVE::Ticket::verify_rsa_ticket(
407 $rsa_pub, 'PVE', $ticket, $tfa_ticket_aad, $min, $max, 1);
408 };
409
410 my ($data, $age) = $check->();
411
412 # check with old, rotated key if current key failed
413 ($data, $age) = $check->(1) if !defined($data);
414
415 my $auth_failure = sub {
416 if ($noerr) {
417 return undef;
418 } else {
419 # raise error via undef ticket
420 PVE::Ticket::verify_rsa_ticket(undef, 'PVE');
421 }
422 };
423
424 if (!defined($data)) {
425 return $auth_failure->();
426 }
427
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
436 my ($username, $tfa_info);
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 }
443 if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
444 # Ticket for u2f-users:
445 ($username, my $challenge) = ($1, $2);
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 }
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' };
463 } else {
464 # Regular ticket (full access)
465 $username = $data;
466 }
467
468 return undef if !PVE::Auth::Plugin::verify_username($username, $noerr);
469
470 return wantarray ? ($username, $age, $tfa_info) : $username;
471 }
472
473 sub 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
492 my $user = $usercfg->{users}->{$username};
493 my $token_info = $user->{tokens}->{$token};
494
495 my $ctime = time();
496 die "token '$token' access expired\n" if $token_info->{expire} && ($token_info->{expire} < $ctime);
497
498 die "invalid token value!\n" if !PVE::Cluster::verify_token($tokenid, $value);
499
500 return wantarray ? ($tokenid) : $tokenid;
501 }
502
503 my $assemble_short_lived_ticket = sub {
504 my ($prefix, $username, $path) = @_;
505
506 my $rsa_priv = get_privkey();
507
508 $path = normalize_path($path);
509
510 die "invalid ticket path\n" if !defined($path);
511
512 my $secret_data = "$username:$path";
513
514 return PVE::Ticket::assemble_rsa_ticket(
515 $rsa_priv, $prefix, undef, $secret_data);
516 };
517
518 my $verify_short_lived_ticket = sub {
519 my ($ticket, $prefix, $username, $path, $noerr) = @_;
520
521 $path = normalize_path($path);
522
523 die "invalid ticket path\n" if !defined($path);
524
525 my $secret_data = "$username:$path";
526
527 my ($rsa_pub, $rsa_mtime) = get_pubkey();
528 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime && $authkey_lifetime > 0)) {
529 if ($noerr) {
530 return undef;
531 } else {
532 # raise error via undef ticket
533 PVE::Ticket::verify_rsa_ticket($rsa_pub, $prefix);
534 }
535 }
536
537 return PVE::Ticket::verify_rsa_ticket(
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')
544 sub assemble_vnc_ticket {
545 my ($username, $path) = @_;
546
547 return $assemble_short_lived_ticket->('PVEVNC', $username, $path);
548 }
549
550 sub 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')
559 sub assemble_tunnel_ticket {
560 my ($username, $path) = @_;
561
562 return $assemble_short_lived_ticket->('PVETUNNEL', $username, $path);
563 }
564
565 sub verify_tunnel_ticket {
566 my ($ticket, $username, $path, $noerr) = @_;
567
568 return $verify_short_lived_ticket->($ticket, 'PVETUNNEL', $username, $path, $noerr);
569 }
570
571 sub assemble_spice_ticket {
572 my ($username, $vmid, $node) = @_;
573
574 my $secret = &$get_csrfr_secret();
575
576 return PVE::Ticket::assemble_spice_ticket(
577 $secret, $username, $vmid, $node);
578 }
579
580 sub verify_spice_connect_url {
581 my ($connect_str) = @_;
582
583 my $secret = &$get_csrfr_secret();
584
585 return PVE::Ticket::verify_spice_connect_url($secret, $connect_str);
586 }
587
588 sub read_x509_subject_spice {
589 my ($filename) = @_;
590
591 # read x509 subject
592 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
593 die "Could not open $filename using OpenSSL\n"
594 if !$bio;
595
596 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
597 Net::SSLeay::BIO_free($bio);
598
599 die "Could not parse X509 certificate in $filename\n"
600 if !$x509;
601
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);
605
606 # remote-viewer wants comma as separator (not '/')
607 $subject =~ s!^/!!;
608 $subject =~ s!/(\w+=)!,$1!g;
609
610 return $subject;
611 }
612
613 # helper to generate SPICE remote-viewer configuration
614 sub 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;
630
631 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
632 my $config = {
633 'secure-attention' => "Ctrl+Alt+Ins",
634 'toggle-fullscreen' => "Shift+F11",
635 'release-cursor' => "Ctrl+Alt+R",
636 type => 'spice',
637 title => $title,
638 host => $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
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
650 sub check_user_exist {
651 my ($usercfg, $username, $noerr) = @_;
652
653 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
654 return undef if !$username;
655
656 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
657
658 die "no such user ('$username')\n" if !$noerr;
659
660 return undef;
661 }
662
663 sub check_user_enabled {
664 my ($usercfg, $username, $noerr) = @_;
665
666 my $data = check_user_exist($usercfg, $username, $noerr);
667 return undef if !$data;
668
669 if (!$data->{enable}) {
670 die "user '$username' is disabled\n" if !$noerr;
671 return undef;
672 }
673
674 my $ctime = time();
675 my $expire = $usercfg->{users}->{$username}->{expire};
676
677 if ($expire && $expire < $ctime) {
678 die "user '$username' access expired\n" if !$noerr;
679 return undef;
680 }
681
682 return 1; # enabled and not expired
683 }
684
685 sub 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
699 # deprecated
700 sub verify_one_time_pw {
701 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
702
703 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
704
705 # fixme: proxy support?
706 my $proxy;
707
708 if ($type eq 'yubico') {
709 PVE::OTP::yubico_verify_otp($otp, $keys, $tfa_cfg->{url},
710 $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
711 } elsif ($type eq 'oath') {
712 PVE::OTP::oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
713 } else {
714 die "unknown tfa type '$type'\n";
715 }
716 }
717
718 # password should be utf8 encoded
719 # Note: some plugins delay/sleep if auth fails
720 sub authenticate_user : prototype($$$;$) {
721 my ($username, $password, $otp, $tfa_challenge) = @_;
722
723 die "no username specified\n" if !$username;
724
725 my ($ruid, $realm);
726
727 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
728
729 my $usercfg = cfs_read_file('user.cfg');
730
731 check_user_enabled($usercfg, $username);
732
733 my $domain_cfg = cfs_read_file('domains.cfg');
734
735 my $cfg = $domain_cfg->{ids}->{$realm};
736 die "auth domain '$realm' does not exist\n" if !$cfg;
737 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
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
745 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
746
747 # This is the first factor with an optional immediate 2nd factor for TOTP:
748 $tfa_challenge = authenticate_2nd_new($username, $realm, $otp, undef);
749 return wantarray ? ($username, $tfa_challenge) : $username;
750 }
751
752 sub authenticate_2nd_new_do : prototype($$$$) {
753 my ($username, $realm, $tfa_response, $tfa_challenge) = @_;
754 my ($tfa_cfg, $realm_tfa) = user_get_tfa($username, $realm);
755
756 if (!defined($tfa_cfg)) {
757 return undef;
758 }
759
760 my $realm_type = $realm_tfa && $realm_tfa->{type};
761 # verify realm type unless using recovery keys:
762 if (defined($realm_type)) {
763 $realm_type = 'totp' if $realm_type eq 'oath'; # we used to call it that
764 if ($realm_type eq 'yubico') {
765 # Yubico auth will not be supported in rust for now...
766 if (!defined($tfa_challenge)) {
767 my $challenge = { yubico => JSON::true };
768 # Even with yubico auth we do allow recovery keys to be used:
769 if (my $recovery = $tfa_cfg->recovery_state($username)) {
770 $challenge->{recovery} = $recovery;
771 }
772 return to_json($challenge);
773 }
774
775 if ($tfa_response =~ /^yubico:(.*)$/) {
776 $tfa_response = $1;
777 # Defer to after unlocking the TFA config:
778 return sub {
779 authenticate_yubico_new(
780 $tfa_cfg, $username, $realm_tfa, $tfa_challenge, $tfa_response,
781 );
782 };
783 }
784 }
785
786 my $response_type;
787 if (defined($tfa_response)) {
788 if ($tfa_response !~ /^([^:]+):/) {
789 die "bad otp response\n";
790 }
791 $response_type = $1;
792 }
793
794 die "realm requires $realm_type authentication\n"
795 if $response_type && $response_type ne 'recovery' && $response_type ne $realm_type;
796 }
797
798 configure_u2f_and_wa($tfa_cfg);
799
800 my ($result, $tfa_done);
801 if (defined($tfa_challenge)) {
802 $tfa_done = 1;
803 $tfa_challenge = verify_ticket($tfa_challenge, 0, $username);
804 $result = $tfa_cfg->authentication_verify2($username, $tfa_challenge, $tfa_response);
805 $tfa_challenge = undef;
806 } else {
807 $tfa_challenge = $tfa_cfg->authentication_challenge($username);
808 if (defined($tfa_response)) {
809 if (defined($tfa_challenge)) {
810 $tfa_done = 1;
811 $result = $tfa_cfg->authentication_verify2($username, $tfa_challenge, $tfa_response);
812 } else {
813 die "no such challenge\n";
814 }
815 }
816 }
817
818 if ($tfa_done) {
819 if (!$result) {
820 # authentication_verify2 somehow returned undef - should be unreachable
821 die "2nd factor failed\n";
822 }
823
824 if ($result->{'needs-saving'}) {
825 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
826 }
827 if ($result->{'totp-limit-reached'}) {
828 # FIXME: send mail to the user (or admin/root if no email configured)
829 die "failed 2nd factor: TOTP limit reached, locked\n";
830 }
831 if ($result->{'tfa-limit-reached'}) {
832 # FIXME: send mail to the user (or admin/root if no email configured)
833 die "failed 1nd factor: TFA limit reached, user locked out\n";
834 }
835 if (!$result->{result}) {
836 die "failed 2nd factor\n";
837 }
838 }
839
840 return $tfa_challenge;
841 }
842
843 # Returns a tfa challenge or undef.
844 sub authenticate_2nd_new : prototype($$$$) {
845 my ($username, $realm, $tfa_response, $tfa_challenge) = @_;
846
847 my $result;
848
849 if (defined($tfa_response) && $tfa_response =~ m/^recovery:/) {
850 $result = lock_tfa_config(sub {
851 authenticate_2nd_new_do($username, $realm, $tfa_response, $tfa_challenge);
852 });
853 } else {
854 $result = authenticate_2nd_new_do($username, $realm, $tfa_response, $tfa_challenge);
855 }
856
857 # Yubico auth returns the authentication sub:
858 if (ref($result) eq 'CODE') {
859 $result = $result->();
860 }
861
862 return $result;
863 }
864
865 sub authenticate_yubico_new : prototype($$$) {
866 my ($tfa_cfg, $username, $realm, $tfa_challenge, $otp) = @_;
867
868 $tfa_challenge = verify_ticket($tfa_challenge, 0, $username);
869 $tfa_challenge = from_json($tfa_challenge);
870
871 if (!$tfa_challenge->{yubico}) {
872 die "no such challenge\n";
873 }
874
875 my $keys = $tfa_cfg->get_yubico_keys($username);
876 die "no keys configured\n" if !defined($keys) || !length($keys);
877
878 authenticate_yubico_do($otp, $keys, $realm);
879
880 # return `undef` to clear the tfa challenge.
881 return undef;
882 }
883
884 sub authenticate_yubico_do : prototype($$$) {
885 my ($value, $keys, $realm) = @_;
886
887 # fixme: proxy support?
888 my $proxy = undef;
889
890 PVE::OTP::yubico_verify_otp($value, $keys, $realm->{url}, $realm->{id}, $realm->{key}, $proxy);
891 }
892
893 sub configure_u2f_and_wa : prototype($) {
894 my ($tfa_cfg) = @_;
895
896 my $rpc_origin;
897 my $get_origin = sub {
898 return $rpc_origin if defined($rpc_origin);
899 my $rpcenv = PVE::RPCEnvironment::get();
900 if (my $origin = $rpcenv->get_request_host(1)) {
901 $rpc_origin = "https://$origin";
902 return $rpc_origin;
903 }
904 die "failed to figure out origin\n";
905 };
906
907 my $dc = cfs_read_file('datacenter.cfg');
908 if (my $u2f = $dc->{u2f}) {
909 eval {
910 $tfa_cfg->set_u2f_config({
911 origin => $u2f->{origin} // $get_origin->(),
912 appid => $u2f->{appid},
913 });
914 };
915 warn "u2f unavailable, configuration error: $@\n" if $@;
916 }
917 if (my $wa = $dc->{webauthn}) {
918 $wa->{origin} //= $get_origin->();
919 eval { $tfa_cfg->set_webauthn_config({%$wa}) };
920 warn "webauthn unavailable, configuration error: $@\n" if $@;
921 }
922 }
923
924 sub domain_set_password {
925 my ($realm, $username, $password) = @_;
926
927 die "no auth domain specified" if !$realm;
928
929 my $domain_cfg = cfs_read_file('domains.cfg');
930
931 my $cfg = $domain_cfg->{ids}->{$realm};
932 die "auth domain '$realm' does not exist\n" if !$cfg;
933 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
934 $plugin->store_password($cfg, $realm, $username, $password);
935 }
936
937 sub iterate_acl_tree {
938 my ($path, $node, $code) = @_;
939
940 $code->($path, $node);
941
942 $path = '' if $path eq '/'; # avoid leading '//'
943
944 my $children = $node->{children};
945
946 foreach my $child (keys %$children) {
947 iterate_acl_tree("$path/$child", $children->{$child}, $code);
948 }
949 }
950
951 # find ACL node corresponding to normalized $path under $root
952 sub find_acl_tree_node {
953 my ($root, $path) = @_;
954
955 my $split_path = [ split("/", $path) ];
956
957 if (!$split_path) {
958 return $root;
959 }
960
961 my $node = $root;
962 for my $p (@$split_path) {
963 next if !$p;
964
965 $node->{children} = {} if !$node->{children};
966 $node->{children}->{$p} = {} if !$node->{children}->{$p};
967
968 $node = $node->{children}->{$p};
969 }
970
971 return $node;
972 }
973
974 sub add_user_group {
975 my ($username, $usercfg, $group) = @_;
976
977 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
978 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
979 }
980
981 sub delete_user_group {
982 my ($username, $usercfg) = @_;
983
984 foreach my $group (keys %{$usercfg->{groups}}) {
985
986 delete ($usercfg->{groups}->{$group}->{users}->{$username})
987 if $usercfg->{groups}->{$group}->{users}->{$username};
988 }
989 }
990
991 sub delete_user_acl {
992 my ($username, $usercfg) = @_;
993
994 my $code = sub {
995 my ($path, $acl_node) = @_;
996
997 delete ($acl_node->{users}->{$username})
998 if $acl_node->{users}->{$username};
999 };
1000
1001 iterate_acl_tree("/", $usercfg->{acl_root}, $code);
1002 }
1003
1004 sub delete_group_acl {
1005 my ($group, $usercfg) = @_;
1006
1007 my $code = sub {
1008 my ($path, $acl_node) = @_;
1009
1010 delete ($acl_node->{groups}->{$group})
1011 if $acl_node->{groups}->{$group};
1012 };
1013
1014 iterate_acl_tree("/", $usercfg->{acl_root}, $code);
1015 }
1016
1017 sub delete_pool_acl {
1018 my ($pool, $usercfg) = @_;
1019
1020 delete ($usercfg->{acl_root}->{children}->{pool}->{children}->{$pool});
1021 }
1022
1023 # we automatically create some predefined roles by splitting privs
1024 # into 3 groups (per category)
1025 # root: only root is allowed to do that
1026 # admin: an administrator can to that
1027 # user: a normal user/customer can to that
1028 my $privgroups = {
1029 VM => {
1030 root => [],
1031 admin => [
1032 'VM.Config.Disk',
1033 'VM.Config.CPU',
1034 'VM.Config.Memory',
1035 'VM.Config.Network',
1036 'VM.Config.HWType',
1037 'VM.Config.Options', # covers all other things
1038 'VM.Allocate',
1039 'VM.Clone',
1040 'VM.Migrate',
1041 'VM.Monitor',
1042 'VM.Snapshot',
1043 'VM.Snapshot.Rollback',
1044 ],
1045 user => [
1046 'VM.Config.CDROM', # change CDROM media
1047 'VM.Config.Cloudinit',
1048 'VM.Console',
1049 'VM.Backup',
1050 'VM.PowerMgmt',
1051 ],
1052 audit => [
1053 'VM.Audit',
1054 ],
1055 },
1056 Sys => {
1057 root => [
1058 'Sys.PowerMgmt',
1059 'Sys.Modify', # edit/change node settings
1060 'Sys.Incoming', # incoming storage/guest migrations
1061 ],
1062 admin => [
1063 'Sys.Console',
1064 'Sys.Syslog',
1065 ],
1066 user => [],
1067 audit => [
1068 'Sys.Audit',
1069 ],
1070 },
1071 Datastore => {
1072 root => [],
1073 admin => [
1074 'Datastore.Allocate',
1075 'Datastore.AllocateTemplate',
1076 ],
1077 user => [
1078 'Datastore.AllocateSpace',
1079 ],
1080 audit => [
1081 'Datastore.Audit',
1082 ],
1083 },
1084 SDN => {
1085 root => [],
1086 admin => [
1087 'SDN.Allocate',
1088 'SDN.Audit',
1089 ],
1090 user => [
1091 'SDN.Use',
1092 ],
1093 audit => [
1094 'SDN.Audit',
1095 ],
1096 },
1097 User => {
1098 root => [
1099 'Realm.Allocate',
1100 ],
1101 admin => [
1102 'User.Modify',
1103 'Group.Allocate', # edit/change group settings
1104 'Realm.AllocateUser',
1105 ],
1106 user => [],
1107 audit => [],
1108 },
1109 Pool => {
1110 root => [],
1111 admin => [
1112 'Pool.Allocate', # create/delete pools
1113 ],
1114 user => [
1115 'Pool.Audit',
1116 ],
1117 audit => [
1118 'Pool.Audit',
1119 ],
1120 },
1121 Mapping => {
1122 root => [],
1123 admin => [
1124 'Mapping.Modify',
1125 ],
1126 user => [
1127 'Mapping.Use',
1128 ],
1129 audit => [
1130 'Mapping.Audit',
1131 ],
1132 },
1133 };
1134
1135 my $valid_privs = {
1136 'Permissions.Modify' => 1, # not contained in a group
1137 };
1138
1139 my $special_roles = {
1140 'NoAccess' => {}, # no privileges
1141 'Administrator' => $valid_privs, # all privileges
1142 };
1143
1144 sub create_roles {
1145
1146 foreach my $cat (keys %$privgroups) {
1147 my $cd = $privgroups->{$cat};
1148 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
1149 @{$cd->{user}}, @{$cd->{audit}}) {
1150 $valid_privs->{$p} = 1;
1151 }
1152 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
1153
1154 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
1155 $special_roles->{"PVEAdmin"}->{$p} = 1;
1156 }
1157 if (scalar(@{$cd->{user}})) {
1158 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
1159 $special_roles->{"PVE${cat}User"}->{$p} = 1;
1160 }
1161 }
1162 foreach my $p (@{$cd->{audit}}) {
1163 $special_roles->{"PVEAuditor"}->{$p} = 1;
1164 }
1165 }
1166
1167 # remove Mapping.Modify from PVEAdmin, only Administrator, root@pam and
1168 # PVEMappingAdmin should be able to use that for now
1169 delete $special_roles->{"PVEAdmin"}->{"Mapping.Modify"};
1170
1171 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
1172 };
1173
1174 create_roles();
1175
1176 sub create_priv_properties {
1177 my $properties = {};
1178 foreach my $priv (keys %$valid_privs) {
1179 $properties->{$priv} = {
1180 type => 'boolean',
1181 optional => 1,
1182 };
1183 }
1184 return $properties;
1185 }
1186
1187 sub role_is_special {
1188 my ($role) = @_;
1189 return (exists $special_roles->{$role}) ? 1 : 0;
1190 }
1191
1192 sub add_role_privs {
1193 my ($role, $usercfg, $privs) = @_;
1194
1195 return if !$privs;
1196
1197 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
1198
1199 foreach my $priv (split_list($privs)) {
1200 if (defined ($valid_privs->{$priv})) {
1201 $usercfg->{roles}->{$role}->{$priv} = 1;
1202 } else {
1203 die "invalid privilege '$priv'\n";
1204 }
1205 }
1206 }
1207
1208 sub lookup_username {
1209 my ($username, $noerr) = @_;
1210
1211 $username =~ m!^(${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex})$!;
1212
1213 my $realm = $2;
1214 my $domain_cfg = cfs_read_file("domains.cfg");
1215 my $casesensitive = $domain_cfg->{ids}->{$realm}->{'case-sensitive'} // 1;
1216 my $usercfg = cfs_read_file('user.cfg');
1217
1218 if (!$casesensitive) {
1219 my @matches = grep { lc $username eq lc $_ } (keys %{$usercfg->{users}});
1220
1221 die "ambiguous case insensitive match of username '$username', cannot safely grant access!\n"
1222 if scalar @matches > 1 && !$noerr;
1223
1224 return $matches[0]
1225 }
1226
1227 return $username;
1228 }
1229
1230 sub normalize_path {
1231 my $path = shift;
1232
1233 return undef if !$path;
1234
1235 $path =~ s|/+|/|g;
1236
1237 $path =~ s|/$||;
1238
1239 $path = '/' if !$path;
1240
1241 $path = "/$path" if $path !~ m|^/|;
1242
1243 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
1244
1245 return $path;
1246 }
1247
1248 sub check_path {
1249 my ($path) = @_;
1250 return $path =~ m!^(
1251 /
1252 |/access
1253 |/access/groups
1254 |/access/groups/[[:alnum:]\.\-\_]+
1255 |/access/realm
1256 |/access/realm/[[:alnum:]\.\-\_]+
1257 |/nodes
1258 |/nodes/[[:alnum:]\.\-\_]+
1259 |/pool
1260 |/pool/[[:alnum:]\.\-\_]+
1261 |/sdn
1262 |/sdn/zones
1263 |/sdn/zones/[[:alnum:]\.\-\_]+
1264 |/sdn/zones/[[:alnum:]\.\-\_]+/[[:alnum:]\.\-\_]+
1265 |/sdn/zones/[[:alnum:]\.\-\_]+/[[:alnum:]\.\-\_]+/[1-9][0-9]{0,3}
1266 |/storage
1267 |/storage/[[:alnum:]\.\-\_]+
1268 |/vms
1269 |/vms/[1-9][0-9]{2,}
1270 |/mapping
1271 |/mapping/[[:alnum:]\.\-\_]+
1272 |/mapping/[[:alnum:]\.\-\_]+/[[:alnum:]\.\-\_]+
1273 )$!xs;
1274 }
1275
1276 PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
1277 sub verify_groupname {
1278 my ($groupname, $noerr) = @_;
1279
1280 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1281
1282 die "group name '$groupname' contains invalid characters\n" if !$noerr;
1283
1284 return undef;
1285 }
1286
1287 return $groupname;
1288 }
1289
1290 PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
1291 sub verify_rolename {
1292 my ($rolename, $noerr) = @_;
1293
1294 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
1295
1296 die "role name '$rolename' contains invalid characters\n" if !$noerr;
1297
1298 return undef;
1299 }
1300
1301 return $rolename;
1302 }
1303
1304 PVE::JSONSchema::register_format('pve-poolid', \&verify_poolname);
1305 sub verify_poolname {
1306 my ($poolname, $noerr) = @_;
1307
1308 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1309
1310 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
1311
1312 return undef;
1313 }
1314
1315 return $poolname;
1316 }
1317
1318 PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
1319 sub verify_privname {
1320 my ($priv, $noerr) = @_;
1321
1322 if (!$valid_privs->{$priv}) {
1323 die "invalid privilege '$priv'\n" if !$noerr;
1324
1325 return undef;
1326 }
1327
1328 return $priv;
1329 }
1330
1331 sub userconfig_force_defaults {
1332 my ($cfg) = @_;
1333
1334 foreach my $r (keys %$special_roles) {
1335 $cfg->{roles}->{$r} = $special_roles->{$r};
1336 }
1337
1338 # add root user if not exists
1339 if (!$cfg->{users}->{'root@pam'}) {
1340 $cfg->{users}->{'root@pam'}->{enable} = 1;
1341 }
1342
1343 # add (empty) ACL tree root node
1344 if (!$cfg->{acl_root}) {
1345 $cfg->{acl_root} = {};
1346 }
1347 }
1348
1349 sub parse_user_config {
1350 my ($filename, $raw) = @_;
1351
1352 my $cfg = {};
1353
1354 userconfig_force_defaults($cfg);
1355
1356 $raw = '' if !defined($raw);
1357 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1358 my $line = $1;
1359 my @data;
1360
1361 foreach my $d (split (/:/, $line)) {
1362 $d =~ s/^\s+//;
1363 $d =~ s/\s+$//;
1364 push @data, $d
1365 }
1366
1367 my $et = shift @data;
1368
1369 if ($et eq 'user') {
1370 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
1371
1372 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1373 if (!$realm) {
1374 warn "user config - ignore user '$user' - invalid user name\n";
1375 next;
1376 }
1377
1378 $enable = $enable ? 1 : 0;
1379
1380 $expire = 0 if !$expire;
1381
1382 if ($expire !~ m/^\d+$/) {
1383 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
1384 next;
1385 }
1386 $expire = int($expire);
1387
1388 #if (!verify_groupname ($group, 1)) {
1389 # warn "user config - ignore user '$user' - invalid characters in group name\n";
1390 # next;
1391 #}
1392
1393 $cfg->{users}->{$user} = {
1394 enable => $enable,
1395 # group => $group,
1396 };
1397 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
1398 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
1399 $cfg->{users}->{$user}->{email} = $email;
1400 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1401 $cfg->{users}->{$user}->{expire} = $expire;
1402 # keys: allowed yubico key ids or oath secrets (base32 encoded)
1403 $cfg->{users}->{$user}->{keys} = $keys if $keys;
1404
1405 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
1406 #$cfg->{groups}->{$group}->{$user} = 1;
1407
1408 } elsif ($et eq 'group') {
1409 my ($group, $userlist, $comment) = @data;
1410
1411 if (!verify_groupname($group, 1)) {
1412 warn "user config - ignore group '$group' - invalid characters in group name\n";
1413 next;
1414 }
1415
1416 # make sure to add the group (even if there are no members)
1417 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
1418
1419 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1420
1421 foreach my $user (split_list($userlist)) {
1422
1423 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
1424 warn "user config - ignore invalid group member '$user'\n";
1425 next;
1426 }
1427
1428 if ($cfg->{users}->{$user}) { # user exists
1429 $cfg->{users}->{$user}->{groups}->{$group} = 1;
1430 } else {
1431 warn "user config - ignore invalid group member '$user'\n";
1432 }
1433 $cfg->{groups}->{$group}->{users}->{$user} = 1;
1434 }
1435
1436 } elsif ($et eq 'role') {
1437 my ($role, $privlist) = @data;
1438
1439 if (!verify_rolename($role, 1)) {
1440 warn "user config - ignore role '$role' - invalid characters in role name\n";
1441 next;
1442 }
1443
1444 # make sure to add the role (even if there are no privileges)
1445 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
1446
1447 foreach my $priv (split_list($privlist)) {
1448 if (defined ($valid_privs->{$priv})) {
1449 $cfg->{roles}->{$role}->{$priv} = 1;
1450 } else {
1451 warn "user config - ignore invalid privilege '$priv'\n";
1452 }
1453 }
1454
1455 } elsif ($et eq 'acl') {
1456 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
1457
1458 $propagate = $propagate ? 1 : 0;
1459
1460 if (my $path = normalize_path($pathtxt)) {
1461 my $acl_node;
1462 foreach my $role (split_list($rolelist)) {
1463
1464 if (!verify_rolename($role, 1)) {
1465 warn "user config - ignore invalid role name '$role' in acl\n";
1466 next;
1467 }
1468
1469 if (!$cfg->{roles}->{$role}) {
1470 warn "user config - ignore invalid acl role '$role'\n";
1471 next;
1472 }
1473
1474 foreach my $ug (split_list($uglist)) {
1475 my ($group) = $ug =~ m/^@(\S+)$/;
1476
1477 if ($group && verify_groupname($group, 1)) {
1478 if (!$cfg->{groups}->{$group}) { # group does not exist
1479 warn "user config - ignore invalid acl group '$group'\n";
1480 }
1481 $acl_node = find_acl_tree_node($cfg->{acl_root}, $path) if !$acl_node;
1482 $acl_node->{groups}->{$group}->{$role} = $propagate;
1483 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
1484 if (!$cfg->{users}->{$ug}) { # user does not exist
1485 warn "user config - ignore invalid acl member '$ug'\n";
1486 }
1487 $acl_node = find_acl_tree_node($cfg->{acl_root}, $path) if !$acl_node;
1488 $acl_node->{users}->{$ug}->{$role} = $propagate;
1489 } elsif (my ($user, $token) = split_tokenid($ug, 1)) {
1490 if (check_token_exist($cfg, $user, $token, 1)) {
1491 $acl_node = find_acl_tree_node($cfg->{acl_root}, $path) if !$acl_node;
1492 $acl_node->{tokens}->{$ug}->{$role} = $propagate;
1493 } else {
1494 warn "user config - ignore invalid acl token '$ug'\n";
1495 }
1496 } else {
1497 warn "user config - invalid user/group '$ug' in acl\n";
1498 }
1499 }
1500 }
1501 } else {
1502 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1503 }
1504 } elsif ($et eq 'pool') {
1505 my ($pool, $comment, $vmlist, $storelist) = @data;
1506
1507 if (!verify_poolname($pool, 1)) {
1508 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1509 next;
1510 }
1511
1512 # make sure to add the pool (even if there are no members)
1513 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
1514
1515 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1516
1517 foreach my $vmid (split_list($vmlist)) {
1518 if ($vmid !~ m/^\d+$/) {
1519 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1520 next;
1521 }
1522 $vmid = int($vmid);
1523
1524 if ($cfg->{vms}->{$vmid}) {
1525 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1526 next;
1527 }
1528
1529 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
1530
1531 # record vmid ==> pool relation
1532 $cfg->{vms}->{$vmid} = $pool;
1533 }
1534
1535 foreach my $storeid (split_list($storelist)) {
1536 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1537 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1538 next;
1539 }
1540 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
1541 }
1542 } elsif ($et eq 'token') {
1543 my ($tokenid, $expire, $privsep, $comment) = @data;
1544
1545 my ($user, $token) = split_tokenid($tokenid, 1);
1546 if (!($user && $token)) {
1547 warn "user config - ignore invalid tokenid '$tokenid'\n";
1548 next;
1549 }
1550
1551 $privsep = $privsep ? 1 : 0;
1552
1553 $expire = 0 if !$expire;
1554
1555 if ($expire !~ m/^\d+$/) {
1556 warn "user config - ignore token '$tokenid' - (illegal characters in expire '$expire')\n";
1557 next;
1558 }
1559 $expire = int($expire);
1560
1561 if (my $user_cfg = $cfg->{users}->{$user}) { # user exists
1562 $user_cfg->{tokens}->{$token} = {} if !$user_cfg->{tokens}->{$token};
1563 my $token_cfg = $user_cfg->{tokens}->{$token};
1564 $token_cfg->{privsep} = $privsep;
1565 $token_cfg->{expire} = $expire;
1566 $token_cfg->{comment} = PVE::Tools::decode_text($comment) if $comment;
1567 } else {
1568 warn "user config - ignore token '$tokenid' - user does not exist\n";
1569 }
1570 } else {
1571 warn "user config - ignore config line: $line\n";
1572 }
1573 }
1574
1575 userconfig_force_defaults($cfg);
1576
1577 return $cfg;
1578 }
1579
1580 sub write_user_config {
1581 my ($filename, $cfg) = @_;
1582
1583 my $data = '';
1584
1585 foreach my $user (sort keys %{$cfg->{users}}) {
1586 my $d = $cfg->{users}->{$user};
1587 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1588 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1589 my $email = $d->{email} || '';
1590 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1591 my $expire = int($d->{expire} || 0);
1592 my $enable = $d->{enable} ? 1 : 0;
1593 my $keys = $d->{keys} ? $d->{keys} : '';
1594 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1595
1596 my $user_tokens = $d->{tokens};
1597 foreach my $token (sort keys %$user_tokens) {
1598 my $td = $user_tokens->{$token};
1599 my $full_tokenid = join_tokenid($user, $token);
1600 my $comment = $td->{comment} ? PVE::Tools::encode_text($td->{comment}) : '';
1601 my $expire = int($td->{expire} || 0);
1602 my $privsep = $td->{privsep} ? 1 : 0;
1603 $data .= "token:$full_tokenid:$expire:$privsep:$comment:\n";
1604 }
1605 }
1606
1607 $data .= "\n";
1608
1609 foreach my $group (sort keys %{$cfg->{groups}}) {
1610 my $d = $cfg->{groups}->{$group};
1611 my $list = join (',', sort keys %{$d->{users}});
1612 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1613 $data .= "group:$group:$list:$comment:\n";
1614 }
1615
1616 $data .= "\n";
1617
1618 foreach my $pool (sort keys %{$cfg->{pools}}) {
1619 my $d = $cfg->{pools}->{$pool};
1620 my $vmlist = join (',', sort keys %{$d->{vms}});
1621 my $storelist = join (',', sort keys %{$d->{storage}});
1622 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1623 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1624 }
1625
1626 $data .= "\n";
1627
1628 foreach my $role (sort keys %{$cfg->{roles}}) {
1629 next if $special_roles->{$role};
1630
1631 my $d = $cfg->{roles}->{$role};
1632 my $list = join (',', sort keys %$d);
1633 $data .= "role:$role:$list:\n";
1634 }
1635
1636 $data .= "\n";
1637
1638 my $collect_rolelist_members = sub {
1639 my ($acl_members, $result, $prefix, $exclude) = @_;
1640
1641 foreach my $member (keys %$acl_members) {
1642 next if $exclude && $member eq $exclude;
1643
1644 my $l0 = '';
1645 my $l1 = '';
1646 foreach my $role (sort keys %{$acl_members->{$member}}) {
1647 my $propagate = $acl_members->{$member}->{$role};
1648 if ($propagate) {
1649 $l1 .= ',' if $l1;
1650 $l1 .= $role;
1651 } else {
1652 $l0 .= ',' if $l0;
1653 $l0 .= $role;
1654 }
1655 }
1656 $result->{0}->{$l0}->{"${prefix}${member}"} = 1 if $l0;
1657 $result->{1}->{$l1}->{"${prefix}${member}"} = 1 if $l1;
1658 }
1659 };
1660
1661 iterate_acl_tree("/", $cfg->{acl_root}, sub {
1662 my ($path, $d) = @_;
1663
1664 my $rolelist_members = {};
1665
1666 $collect_rolelist_members->($d->{'groups'}, $rolelist_members, '@');
1667
1668 # no need to save 'root@pam', it is always 'Administrator'
1669 $collect_rolelist_members->($d->{'users'}, $rolelist_members, '', 'root@pam');
1670
1671 $collect_rolelist_members->($d->{'tokens'}, $rolelist_members, '');
1672
1673 foreach my $propagate (0,1) {
1674 my $filtered = $rolelist_members->{$propagate};
1675 foreach my $rolelist (sort keys %$filtered) {
1676 my $uglist = join (',', sort keys %{$filtered->{$rolelist}});
1677 $data .= "acl:$propagate:$path:$uglist:$rolelist:\n";
1678 }
1679
1680 }
1681 });
1682
1683 return $data;
1684 }
1685
1686 # Creates a `PVE::RS::TFA` instance from the raw config data.
1687 # Its contained hash will also support the legacy functionality.
1688 sub parse_priv_tfa_config {
1689 my ($filename, $raw) = @_;
1690
1691 $raw = '' if !defined($raw);
1692 my $cfg = PVE::RS::TFA->new($raw);
1693
1694 # Purge invalid users:
1695 foreach my $user ($cfg->users()->@*) {
1696 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1697 if (!$realm) {
1698 warn "user tfa config - ignore user '$user' - invalid user name\n";
1699 $cfg->remove_user($user);
1700 }
1701 }
1702
1703 return $cfg;
1704 }
1705
1706 sub write_priv_tfa_config {
1707 my ($filename, $cfg) = @_;
1708
1709 return $cfg->write();
1710 }
1711
1712 sub roles {
1713 my ($cfg, $user, $path) = @_;
1714
1715 # NOTE: we do not consider pools here.
1716 # NOTE: for privsep tokens, this does not filter roles by those that the
1717 # corresponding user has.
1718 # Use $rpcenv->permission() for any actual permission checks!
1719
1720 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1721
1722 if (!defined($path)) {
1723 # this shouldn't happen!
1724 warn "internal error: ACL check called for undefined ACL path!\n";
1725 return {};
1726 }
1727
1728 if (pve_verify_tokenid($user, 1)) {
1729 my $tokenid = $user;
1730 my ($username, $token) = split_tokenid($tokenid);
1731
1732 my $token_info = $cfg->{users}->{$username}->{tokens}->{$token};
1733 return () if !$token_info;
1734
1735 my $user_roles = roles($cfg, $username, $path);
1736
1737 # return full user privileges
1738 return $user_roles if !$token_info->{privsep};
1739 }
1740
1741 my $roles = {};
1742
1743 my $split = [ split("/", $path) ];
1744 if ($path eq '/') {
1745 $split = [ '' ];
1746 }
1747
1748 my $acl = $cfg->{acl_root};
1749 my $i = 0;
1750
1751 while (@$split) {
1752 my $p = shift @$split;
1753 my $final = !@$split;
1754 if ($p ne '') {
1755 $acl = $acl->{children}->{$p};
1756 }
1757
1758 #print "CHECKACL $path $p\n";
1759 #print "ACL $path = " . Dumper ($acl);
1760 if (my $ri = $acl->{tokens}->{$user}) {
1761 my $new;
1762 foreach my $role (keys %$ri) {
1763 my $propagate = $ri->{$role};
1764 if ($final || $propagate) {
1765 #print "APPLY ROLE $p $user $role\n";
1766 $new = {} if !$new;
1767 $new->{$role} = $propagate;
1768 }
1769 }
1770 if ($new) {
1771 $roles = $new; # overwrite previous settings
1772 next;
1773 }
1774 }
1775
1776 if (my $ri = $acl->{users}->{$user}) {
1777 my $new;
1778 foreach my $role (keys %$ri) {
1779 my $propagate = $ri->{$role};
1780 if ($final || $propagate) {
1781 #print "APPLY ROLE $p $user $role\n";
1782 $new = {} if !$new;
1783 $new->{$role} = $propagate;
1784 }
1785 }
1786 if ($new) {
1787 $roles = $new; # overwrite previous settings
1788 next; # user privs always override group privs
1789 }
1790 }
1791
1792 my $new;
1793 foreach my $g (keys %{$acl->{groups}}) {
1794 next if !$cfg->{groups}->{$g}->{users}->{$user};
1795 if (my $ri = $acl->{groups}->{$g}) {
1796 foreach my $role (keys %$ri) {
1797 my $propagate = $ri->{$role};
1798 if ($final || $propagate) {
1799 #print "APPLY ROLE $p \@$g $role\n";
1800 $new = {} if !$new;
1801 $new->{$role} = $propagate;
1802 }
1803 }
1804 }
1805 }
1806 if ($new) {
1807 $roles = $new; # overwrite previous settings
1808 next;
1809 }
1810 }
1811
1812 return { 'NoAccess' => $roles->{NoAccess} } if defined ($roles->{NoAccess});
1813 #return () if defined ($roles->{NoAccess});
1814
1815 #print "permission $user $path = " . Dumper ($roles);
1816
1817 #print "roles $user $path = " . join (',', @ra) . "\n";
1818
1819 return $roles;
1820 }
1821
1822 sub remove_vm_access {
1823 my ($vmid) = @_;
1824 my $delVMaccessFn = sub {
1825 my $usercfg = cfs_read_file("user.cfg");
1826 my $modified;
1827
1828 if (my $acl = $usercfg->{acl_root}->{children}->{vms}->{children}->{$vmid}) {
1829 delete $usercfg->{acl_root}->{children}->{vms}->{children}->{$vmid};
1830 $modified = 1;
1831 }
1832 if (my $pool = $usercfg->{vms}->{$vmid}) {
1833 if (my $data = $usercfg->{pools}->{$pool}) {
1834 delete $data->{vms}->{$vmid};
1835 delete $usercfg->{vms}->{$vmid};
1836 $modified = 1;
1837 }
1838 }
1839 cfs_write_file("user.cfg", $usercfg) if $modified;
1840 };
1841
1842 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1843 }
1844
1845 sub remove_storage_access {
1846 my ($storeid) = @_;
1847
1848 my $deleteStorageAccessFn = sub {
1849 my $usercfg = cfs_read_file("user.cfg");
1850 my $modified;
1851
1852 if (my $acl = $usercfg->{acl_root}->{children}->{storage}->{children}->{$storeid}) {
1853 delete $usercfg->{acl_root}->{children}->{storage}->{children}->{$storeid};
1854 $modified = 1;
1855 }
1856 foreach my $pool (keys %{$usercfg->{pools}}) {
1857 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1858 $modified = 1;
1859 }
1860 cfs_write_file("user.cfg", $usercfg) if $modified;
1861 };
1862
1863 lock_user_config($deleteStorageAccessFn,
1864 "access permissions cleanup for storage $storeid failed");
1865 }
1866
1867 sub add_vm_to_pool {
1868 my ($vmid, $pool) = @_;
1869
1870 my $addVMtoPoolFn = sub {
1871 my $usercfg = cfs_read_file("user.cfg");
1872 if (my $data = $usercfg->{pools}->{$pool}) {
1873 $data->{vms}->{$vmid} = 1;
1874 $usercfg->{vms}->{$vmid} = $pool;
1875 cfs_write_file("user.cfg", $usercfg);
1876 }
1877 };
1878
1879 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1880 }
1881
1882 sub remove_vm_from_pool {
1883 my ($vmid) = @_;
1884
1885 my $delVMfromPoolFn = sub {
1886 my $usercfg = cfs_read_file("user.cfg");
1887 if (my $pool = $usercfg->{vms}->{$vmid}) {
1888 if (my $data = $usercfg->{pools}->{$pool}) {
1889 delete $data->{vms}->{$vmid};
1890 delete $usercfg->{vms}->{$vmid};
1891 cfs_write_file("user.cfg", $usercfg);
1892 }
1893 }
1894 };
1895
1896 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1897 }
1898
1899 my $USER_CONTROLLED_TFA_TYPES = {
1900 u2f => 1,
1901 oath => 1,
1902 };
1903
1904 sub user_remove_tfa : prototype($) {
1905 my ($userid) = @_;
1906
1907 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1908 $tfa_cfg->remove_user($userid);
1909 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1910 }
1911
1912 my sub add_old_yubico_keys : prototype($$$) {
1913 my ($userid, $tfa_cfg, $keys) = @_;
1914
1915 my $count = 0;
1916 foreach my $key (split_list($keys)) {
1917 my $description = "<old userconfig key $count>";
1918 ++$count;
1919 $tfa_cfg->add_yubico_entry($userid, $description, $key);
1920 }
1921 }
1922
1923 my sub normalize_totp_secret : prototype($) {
1924 my ($key) = @_;
1925
1926 my $binkey;
1927 # See PVE::OTP::oath_verify_otp:
1928 if ($key =~ /^v2-0x([0-9a-fA-F]+)$/) {
1929 # v2, hex
1930 $binkey = pack('H*', $1);
1931 } elsif ($key =~ /^v2-([A-Z2-7=]+)$/) {
1932 # v2, base32
1933 $binkey = MIME::Base32::decode_rfc3548($1);
1934 } elsif ($key =~ /^[A-Z2-7=]{16}$/) {
1935 $binkey = MIME::Base32::decode_rfc3548($key);
1936 } elsif ($key =~ /^[A-Fa-f0-9]{40}$/) {
1937 $binkey = pack('H*', $key);
1938 } else {
1939 return undef;
1940 }
1941
1942 return MIME::Base32::encode_rfc3548($binkey);
1943 }
1944
1945 my sub add_old_totp_keys : prototype($$$$) {
1946 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1947
1948 my $issuer = 'Proxmox%20VE';
1949 my $account = uri_escape("Old key for $userid");
1950 my $digits = $realm_tfa->{digits} || 6;
1951 my $step = $realm_tfa->{step} || 30;
1952 my $uri = "otpauth://totp/$issuer:$account?digits=$digits&period=$step&algorithm=SHA1&secret=";
1953
1954 my $count = 0;
1955 foreach my $key (split_list($keys)) {
1956 $key = normalize_totp_secret($key);
1957 # and just skip invalid keys:
1958 next if !defined($key);
1959
1960 my $description = "<old userconfig key $count>";
1961 ++$count;
1962 eval { $tfa_cfg->add_totp_entry($userid, $description, $uri . $key) };
1963 warn $@ if $@;
1964 }
1965 }
1966
1967 sub add_old_keys_to_realm_tfa : prototype($$$$) {
1968 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1969
1970 # if there's no realm tfa configured, we don't know what the keys mean, so we just ignore
1971 # them...
1972 return if !$realm_tfa;
1973
1974 my $type = $realm_tfa->{type};
1975 if ($type eq 'oath') {
1976 add_old_totp_keys($userid, $tfa_cfg, $realm_tfa, $keys);
1977 } elsif ($type eq 'yubico') {
1978 add_old_yubico_keys($userid, $tfa_cfg, $keys);
1979 } else {
1980 # invalid keys, we'll just drop them now...
1981 }
1982 }
1983
1984 sub user_get_tfa : prototype($$$) {
1985 my ($username, $realm) = @_;
1986
1987 my $user_cfg = cfs_read_file('user.cfg');
1988 my $user = $user_cfg->{users}->{$username}
1989 or die "user '$username' not found\n";
1990
1991 my $keys = $user->{keys};
1992
1993 my $domain_cfg = cfs_read_file('domains.cfg');
1994 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1995 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1996
1997 my $realm_tfa = $realm_cfg->{tfa};
1998 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
1999 if $realm_tfa;
2000
2001 if (!$keys) {
2002 return if !$realm_tfa;
2003 die "missing required 2nd keys\n";
2004 }
2005
2006 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
2007 if (defined($keys) && $keys !~ /^x(?:!.*)$/) {
2008 add_old_keys_to_realm_tfa($username, $tfa_cfg, $realm_tfa, $keys);
2009 }
2010 return ($tfa_cfg, $realm_tfa);
2011 }
2012
2013 # bash completion helpers
2014
2015 register_standard_option('userid-completed',
2016 get_standard_option('userid', { completion => \&complete_username}),
2017 );
2018
2019 sub complete_username {
2020
2021 my $user_cfg = cfs_read_file('user.cfg');
2022
2023 return [ keys %{$user_cfg->{users}} ];
2024 }
2025
2026 sub complete_group {
2027
2028 my $user_cfg = cfs_read_file('user.cfg');
2029
2030 return [ keys %{$user_cfg->{groups}} ];
2031 }
2032
2033 sub complete_realm {
2034
2035 my $domain_cfg = cfs_read_file('domains.cfg');
2036
2037 return [ keys %{$domain_cfg->{ids}} ];
2038 }
2039
2040 1;