]> git.proxmox.com Git - pve-access-control.git/blob - src/PVE/AccessControl.pm
faea70de345bbef2b1e710e8436f91c93e708dde
[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 # FIXME: `$tfa_cfg` is now usually never undef - use cheap check for
757 # whether the user has *any* entries here instead whe it is available in
758 # pve-rs
759 if (!defined($tfa_cfg)) {
760 return undef;
761 }
762
763 my $realm_type = $realm_tfa && $realm_tfa->{type};
764 # verify realm type unless using recovery keys:
765 if (defined($realm_type)) {
766 $realm_type = 'totp' if $realm_type eq 'oath'; # we used to call it that
767 if ($realm_type eq 'yubico') {
768 # Yubico auth will not be supported in rust for now...
769 if (!defined($tfa_challenge)) {
770 my $challenge = { yubico => JSON::true };
771 # Even with yubico auth we do allow recovery keys to be used:
772 if (my $recovery = $tfa_cfg->recovery_state($username)) {
773 $challenge->{recovery} = $recovery;
774 }
775 return to_json($challenge);
776 }
777
778 if ($tfa_response =~ /^yubico:(.*)$/) {
779 $tfa_response = $1;
780 # Defer to after unlocking the TFA config:
781 return sub {
782 authenticate_yubico_new(
783 $tfa_cfg, $username, $realm_tfa, $tfa_challenge, $tfa_response,
784 );
785 };
786 }
787 }
788
789 my $response_type;
790 if (defined($tfa_response)) {
791 if ($tfa_response !~ /^([^:]+):/) {
792 die "bad otp response\n";
793 }
794 $response_type = $1;
795 }
796
797 die "realm requires $realm_type authentication\n"
798 if $response_type && $response_type ne 'recovery' && $response_type ne $realm_type;
799 }
800
801 configure_u2f_and_wa($tfa_cfg);
802
803 my ($result, $tfa_done);
804 if (defined($tfa_challenge)) {
805 $tfa_done = 1;
806 $tfa_challenge = verify_ticket($tfa_challenge, 0, $username);
807 $result = $tfa_cfg->authentication_verify2($username, $tfa_challenge, $tfa_response);
808 $tfa_challenge = undef;
809 } else {
810 $tfa_challenge = $tfa_cfg->authentication_challenge($username);
811
812 die "missing required 2nd keys\n"
813 if $realm_tfa && !defined($tfa_challenge);
814
815 if (defined($tfa_response)) {
816 if (defined($tfa_challenge)) {
817 $tfa_done = 1;
818 $result = $tfa_cfg->authentication_verify2($username, $tfa_challenge, $tfa_response);
819 } else {
820 die "no such challenge\n";
821 }
822 }
823 }
824
825 if ($tfa_done) {
826 if (!$result) {
827 # authentication_verify2 somehow returned undef - should be unreachable
828 die "2nd factor failed\n";
829 }
830
831 if ($result->{'needs-saving'}) {
832 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
833 }
834 if ($result->{'totp-limit-reached'}) {
835 # FIXME: send mail to the user (or admin/root if no email configured)
836 die "failed 2nd factor: TOTP limit reached, locked\n";
837 }
838 if ($result->{'tfa-limit-reached'}) {
839 # FIXME: send mail to the user (or admin/root if no email configured)
840 die "failed 1nd factor: TFA limit reached, user locked out\n";
841 }
842 if (!$result->{result}) {
843 die "failed 2nd factor\n";
844 }
845 }
846
847 return $tfa_challenge;
848 }
849
850 # Returns a tfa challenge or undef.
851 sub authenticate_2nd_new : prototype($$$$) {
852 my ($username, $realm, $tfa_response, $tfa_challenge) = @_;
853
854 my $result;
855
856 if (defined($tfa_response) && $tfa_response =~ m/^recovery:/) {
857 $result = lock_tfa_config(sub {
858 authenticate_2nd_new_do($username, $realm, $tfa_response, $tfa_challenge);
859 });
860 } else {
861 $result = authenticate_2nd_new_do($username, $realm, $tfa_response, $tfa_challenge);
862 }
863
864 # Yubico auth returns the authentication sub:
865 if (ref($result) eq 'CODE') {
866 $result = $result->();
867 }
868
869 return $result;
870 }
871
872 sub authenticate_yubico_new : prototype($$$) {
873 my ($tfa_cfg, $username, $realm, $tfa_challenge, $otp) = @_;
874
875 $tfa_challenge = verify_ticket($tfa_challenge, 0, $username);
876 $tfa_challenge = from_json($tfa_challenge);
877
878 if (!$tfa_challenge->{yubico}) {
879 die "no such challenge\n";
880 }
881
882 my $keys = $tfa_cfg->get_yubico_keys($username);
883 die "no keys configured\n" if !defined($keys) || !length($keys);
884
885 authenticate_yubico_do($otp, $keys, $realm);
886
887 # return `undef` to clear the tfa challenge.
888 return undef;
889 }
890
891 sub authenticate_yubico_do : prototype($$$) {
892 my ($value, $keys, $realm) = @_;
893
894 # fixme: proxy support?
895 my $proxy = undef;
896
897 PVE::OTP::yubico_verify_otp($value, $keys, $realm->{url}, $realm->{id}, $realm->{key}, $proxy);
898 }
899
900 sub configure_u2f_and_wa : prototype($) {
901 my ($tfa_cfg) = @_;
902
903 my $rpc_origin;
904 my $get_origin = sub {
905 return $rpc_origin if defined($rpc_origin);
906 my $rpcenv = PVE::RPCEnvironment::get();
907 if (my $origin = $rpcenv->get_request_host(1)) {
908 $rpc_origin = "https://$origin";
909 return $rpc_origin;
910 }
911 die "failed to figure out origin\n";
912 };
913
914 my $dc = cfs_read_file('datacenter.cfg');
915 if (my $u2f = $dc->{u2f}) {
916 eval {
917 $tfa_cfg->set_u2f_config({
918 origin => $u2f->{origin} // $get_origin->(),
919 appid => $u2f->{appid},
920 });
921 };
922 warn "u2f unavailable, configuration error: $@\n" if $@;
923 }
924 if (my $wa = $dc->{webauthn}) {
925 $wa->{origin} //= $get_origin->();
926 eval { $tfa_cfg->set_webauthn_config({%$wa}) };
927 warn "webauthn unavailable, configuration error: $@\n" if $@;
928 }
929 }
930
931 sub domain_set_password {
932 my ($realm, $username, $password) = @_;
933
934 die "no auth domain specified" if !$realm;
935
936 my $domain_cfg = cfs_read_file('domains.cfg');
937
938 my $cfg = $domain_cfg->{ids}->{$realm};
939 die "auth domain '$realm' does not exist\n" if !$cfg;
940 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
941 $plugin->store_password($cfg, $realm, $username, $password);
942 }
943
944 sub iterate_acl_tree {
945 my ($path, $node, $code) = @_;
946
947 $code->($path, $node);
948
949 $path = '' if $path eq '/'; # avoid leading '//'
950
951 my $children = $node->{children};
952
953 foreach my $child (keys %$children) {
954 iterate_acl_tree("$path/$child", $children->{$child}, $code);
955 }
956 }
957
958 # find ACL node corresponding to normalized $path under $root
959 sub find_acl_tree_node {
960 my ($root, $path) = @_;
961
962 my $split_path = [ split("/", $path) ];
963
964 if (!$split_path) {
965 return $root;
966 }
967
968 my $node = $root;
969 for my $p (@$split_path) {
970 next if !$p;
971
972 $node->{children} = {} if !$node->{children};
973 $node->{children}->{$p} = {} if !$node->{children}->{$p};
974
975 $node = $node->{children}->{$p};
976 }
977
978 return $node;
979 }
980
981 sub add_user_group {
982 my ($username, $usercfg, $group) = @_;
983
984 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
985 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
986 }
987
988 sub delete_user_group {
989 my ($username, $usercfg) = @_;
990
991 foreach my $group (keys %{$usercfg->{groups}}) {
992
993 delete ($usercfg->{groups}->{$group}->{users}->{$username})
994 if $usercfg->{groups}->{$group}->{users}->{$username};
995 }
996 }
997
998 sub delete_user_acl {
999 my ($username, $usercfg) = @_;
1000
1001 my $code = sub {
1002 my ($path, $acl_node) = @_;
1003
1004 delete ($acl_node->{users}->{$username})
1005 if $acl_node->{users}->{$username};
1006 };
1007
1008 iterate_acl_tree("/", $usercfg->{acl_root}, $code);
1009 }
1010
1011 sub delete_group_acl {
1012 my ($group, $usercfg) = @_;
1013
1014 my $code = sub {
1015 my ($path, $acl_node) = @_;
1016
1017 delete ($acl_node->{groups}->{$group})
1018 if $acl_node->{groups}->{$group};
1019 };
1020
1021 iterate_acl_tree("/", $usercfg->{acl_root}, $code);
1022 }
1023
1024 sub delete_pool_acl {
1025 my ($pool, $usercfg) = @_;
1026
1027 delete ($usercfg->{acl_root}->{children}->{pool}->{children}->{$pool});
1028 }
1029
1030 # we automatically create some predefined roles by splitting privs
1031 # into 3 groups (per category)
1032 # root: only root is allowed to do that
1033 # admin: an administrator can to that
1034 # user: a normal user/customer can to that
1035 my $privgroups = {
1036 VM => {
1037 root => [],
1038 admin => [
1039 'VM.Config.Disk',
1040 'VM.Config.CPU',
1041 'VM.Config.Memory',
1042 'VM.Config.Network',
1043 'VM.Config.HWType',
1044 'VM.Config.Options', # covers all other things
1045 'VM.Allocate',
1046 'VM.Clone',
1047 'VM.Migrate',
1048 'VM.Monitor',
1049 'VM.Snapshot',
1050 'VM.Snapshot.Rollback',
1051 ],
1052 user => [
1053 'VM.Config.CDROM', # change CDROM media
1054 'VM.Config.Cloudinit',
1055 'VM.Console',
1056 'VM.Backup',
1057 'VM.PowerMgmt',
1058 ],
1059 audit => [
1060 'VM.Audit',
1061 ],
1062 },
1063 Sys => {
1064 root => [
1065 'Sys.PowerMgmt',
1066 'Sys.Modify', # edit/change node settings
1067 'Sys.Incoming', # incoming storage/guest migrations
1068 'Sys.AccessNetwork', # for, e.g., downloading ISOs from any URL
1069 ],
1070 admin => [
1071 'Sys.Console',
1072 'Sys.Syslog',
1073 ],
1074 user => [],
1075 audit => [
1076 'Sys.Audit',
1077 ],
1078 },
1079 Datastore => {
1080 root => [],
1081 admin => [
1082 'Datastore.Allocate',
1083 'Datastore.AllocateTemplate',
1084 ],
1085 user => [
1086 'Datastore.AllocateSpace',
1087 ],
1088 audit => [
1089 'Datastore.Audit',
1090 ],
1091 },
1092 SDN => {
1093 root => [],
1094 admin => [
1095 'SDN.Allocate',
1096 'SDN.Audit',
1097 ],
1098 user => [
1099 'SDN.Use',
1100 ],
1101 audit => [
1102 'SDN.Audit',
1103 ],
1104 },
1105 User => {
1106 root => [
1107 'Realm.Allocate',
1108 ],
1109 admin => [
1110 'User.Modify',
1111 'Group.Allocate', # edit/change group settings
1112 'Realm.AllocateUser',
1113 ],
1114 user => [],
1115 audit => [],
1116 },
1117 Pool => {
1118 root => [],
1119 admin => [
1120 'Pool.Allocate', # create/delete pools
1121 ],
1122 user => [
1123 'Pool.Audit',
1124 ],
1125 audit => [
1126 'Pool.Audit',
1127 ],
1128 },
1129 Mapping => {
1130 root => [],
1131 admin => [
1132 'Mapping.Modify',
1133 ],
1134 user => [
1135 'Mapping.Use',
1136 ],
1137 audit => [
1138 'Mapping.Audit',
1139 ],
1140 },
1141 };
1142
1143 my $valid_privs = {
1144 'Permissions.Modify' => 1, # not contained in a group
1145 };
1146
1147 my $special_roles = {
1148 'NoAccess' => {}, # no privileges
1149 'Administrator' => $valid_privs, # all privileges
1150 };
1151
1152 sub create_roles {
1153
1154 for my $cat (keys %$privgroups) {
1155 my $cd = $privgroups->{$cat};
1156 # create map to easily check if a privilege is valid
1157 for my $priv (@{$cd->{root}}, @{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
1158 $valid_privs->{$priv} = 1;
1159 }
1160 # create grouped admin roles and PVEAdmin
1161 for my $priv (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
1162 $special_roles->{"PVE${cat}Admin"}->{$priv} = 1;
1163 $special_roles->{"PVEAdmin"}->{$priv} = 1;
1164 }
1165 # create grouped user and audit roles
1166 if (scalar(@{$cd->{user}})) {
1167 for my $priv (@{$cd->{user}}, @{$cd->{audit}}) {
1168 $special_roles->{"PVE${cat}User"}->{$priv} = 1;
1169 }
1170 }
1171 for my $priv (@{$cd->{audit}}) {
1172 $special_roles->{"PVEAuditor"}->{$priv} = 1;
1173 }
1174 }
1175
1176 # remove Mapping.Modify from PVEAdmin, only Administrator, root@pam and
1177 # PVEMappingAdmin should be able to use that for now
1178 delete $special_roles->{"PVEAdmin"}->{"Mapping.Modify"};
1179
1180 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
1181 };
1182
1183 create_roles();
1184
1185 sub create_priv_properties {
1186 my $properties = {};
1187 foreach my $priv (keys %$valid_privs) {
1188 $properties->{$priv} = {
1189 type => 'boolean',
1190 optional => 1,
1191 };
1192 }
1193 return $properties;
1194 }
1195
1196 sub role_is_special {
1197 my ($role) = @_;
1198 return (exists $special_roles->{$role}) ? 1 : 0;
1199 }
1200
1201 sub add_role_privs {
1202 my ($role, $usercfg, $privs) = @_;
1203
1204 return if !$privs;
1205
1206 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
1207
1208 foreach my $priv (split_list($privs)) {
1209 if (defined ($valid_privs->{$priv})) {
1210 $usercfg->{roles}->{$role}->{$priv} = 1;
1211 } else {
1212 die "invalid privilege '$priv'\n";
1213 }
1214 }
1215 }
1216
1217 sub lookup_username {
1218 my ($username, $noerr) = @_;
1219
1220 $username =~ m!^(${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex})$!;
1221
1222 my $realm = $2;
1223 my $domain_cfg = cfs_read_file("domains.cfg");
1224 my $casesensitive = $domain_cfg->{ids}->{$realm}->{'case-sensitive'} // 1;
1225 my $usercfg = cfs_read_file('user.cfg');
1226
1227 if (!$casesensitive) {
1228 my @matches = grep { lc $username eq lc $_ } (keys %{$usercfg->{users}});
1229
1230 die "ambiguous case insensitive match of username '$username', cannot safely grant access!\n"
1231 if scalar @matches > 1 && !$noerr;
1232
1233 return $matches[0]
1234 }
1235
1236 return $username;
1237 }
1238
1239 sub normalize_path {
1240 my $path = shift;
1241
1242 return undef if !$path;
1243
1244 $path =~ s|/+|/|g;
1245
1246 $path =~ s|/$||;
1247
1248 $path = '/' if !$path;
1249
1250 $path = "/$path" if $path !~ m|^/|;
1251
1252 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
1253
1254 return $path;
1255 }
1256
1257 sub check_path {
1258 my ($path) = @_;
1259 return $path =~ m!^(
1260 /
1261 |/access
1262 |/access/groups
1263 |/access/groups/[[:alnum:]\.\-\_]+
1264 |/access/realm
1265 |/access/realm/[[:alnum:]\.\-\_]+
1266 |/nodes
1267 |/nodes/[[:alnum:]\.\-\_]+
1268 |/pool
1269 |/pool/[A-Za-z0-9\.\-_]+(?:/[A-Za-z0-9\.\-_]+){0,2}
1270 |/sdn
1271 |/sdn/controllers
1272 |/sdn/controllers/[[:alnum:]\_\-]+
1273 |/sdn/dns
1274 |/sdn/dns/[[:alnum:]]+
1275 |/sdn/ipams
1276 |/sdn/ipams/[[:alnum:]]+
1277 |/sdn/zones
1278 |/sdn/zones/[[:alnum:]\.\-\_]+
1279 |/sdn/zones/[[:alnum:]\.\-\_]+/[[:alnum:]\.\-\_]+
1280 |/sdn/zones/[[:alnum:]\.\-\_]+/[[:alnum:]\.\-\_]+/[1-9][0-9]{0,3}
1281 |/storage
1282 |/storage/[[:alnum:]\.\-\_]+
1283 |/vms
1284 |/vms/[1-9][0-9]{2,}
1285 |/mapping
1286 |/mapping/[[:alnum:]\.\-\_]+
1287 |/mapping/[[:alnum:]\.\-\_]+/[[:alnum:]\.\-\_]+
1288 )$!xs;
1289 }
1290
1291 PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
1292 sub verify_groupname {
1293 my ($groupname, $noerr) = @_;
1294
1295 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
1296
1297 die "group name '$groupname' contains invalid characters\n" if !$noerr;
1298
1299 return undef;
1300 }
1301
1302 return $groupname;
1303 }
1304
1305 PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
1306 sub verify_rolename {
1307 my ($rolename, $noerr) = @_;
1308
1309 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
1310
1311 die "role name '$rolename' contains invalid characters\n" if !$noerr;
1312
1313 return undef;
1314 }
1315
1316 return $rolename;
1317 }
1318
1319 PVE::JSONSchema::register_format('pve-poolid', \&verify_poolname);
1320 sub verify_poolname {
1321 my ($poolname, $noerr) = @_;
1322
1323 if (split("/", $poolname) > 3) {
1324 die "pool name '$poolname' nested too deeply (max levels = 3)\n" if !$noerr;
1325
1326 return undef;
1327 }
1328
1329 # also adapt check_path above if changed!
1330 if ($poolname !~ m!^[A-Za-z0-9\.\-_]+(?:/[A-Za-z0-9\.\-_]+){0,2}$!) {
1331 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
1332
1333 return undef;
1334 }
1335
1336 return $poolname;
1337 }
1338
1339 PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
1340 sub verify_privname {
1341 my ($priv, $noerr) = @_;
1342
1343 if (!$valid_privs->{$priv}) {
1344 die "invalid privilege '$priv'\n" if !$noerr;
1345
1346 return undef;
1347 }
1348
1349 return $priv;
1350 }
1351
1352 sub userconfig_force_defaults {
1353 my ($cfg) = @_;
1354
1355 foreach my $r (keys %$special_roles) {
1356 $cfg->{roles}->{$r} = $special_roles->{$r};
1357 }
1358
1359 # add root user if not exists
1360 if (!$cfg->{users}->{'root@pam'}) {
1361 $cfg->{users}->{'root@pam'}->{enable} = 1;
1362 }
1363
1364 # add (empty) ACL tree root node
1365 if (!$cfg->{acl_root}) {
1366 $cfg->{acl_root} = {};
1367 }
1368 }
1369
1370 sub parse_user_config {
1371 my ($filename, $raw) = @_;
1372
1373 my $cfg = {};
1374
1375 userconfig_force_defaults($cfg);
1376
1377 $raw = '' if !defined($raw);
1378 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1379 my $line = $1;
1380 my @data;
1381
1382 foreach my $d (split (/:/, $line)) {
1383 $d =~ s/^\s+//;
1384 $d =~ s/\s+$//;
1385 push @data, $d
1386 }
1387
1388 my $et = shift @data;
1389
1390 if ($et eq 'user') {
1391 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
1392
1393 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1394 if (!$realm) {
1395 warn "user config - ignore user '$user' - invalid user name\n";
1396 next;
1397 }
1398
1399 $enable = $enable ? 1 : 0;
1400
1401 $expire = 0 if !$expire;
1402
1403 if ($expire !~ m/^\d+$/) {
1404 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
1405 next;
1406 }
1407 $expire = int($expire);
1408
1409 #if (!verify_groupname ($group, 1)) {
1410 # warn "user config - ignore user '$user' - invalid characters in group name\n";
1411 # next;
1412 #}
1413
1414 $cfg->{users}->{$user} = {
1415 enable => $enable,
1416 # group => $group,
1417 };
1418 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
1419 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
1420 $cfg->{users}->{$user}->{email} = $email;
1421 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1422 $cfg->{users}->{$user}->{expire} = $expire;
1423 # keys: allowed yubico key ids or oath secrets (base32 encoded)
1424 $cfg->{users}->{$user}->{keys} = $keys if $keys;
1425
1426 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
1427 #$cfg->{groups}->{$group}->{$user} = 1;
1428
1429 } elsif ($et eq 'group') {
1430 my ($group, $userlist, $comment) = @data;
1431
1432 if (!verify_groupname($group, 1)) {
1433 warn "user config - ignore group '$group' - invalid characters in group name\n";
1434 next;
1435 }
1436
1437 # make sure to add the group (even if there are no members)
1438 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
1439
1440 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1441
1442 foreach my $user (split_list($userlist)) {
1443
1444 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
1445 warn "user config - ignore invalid group member '$user'\n";
1446 next;
1447 }
1448
1449 if ($cfg->{users}->{$user}) { # user exists
1450 $cfg->{users}->{$user}->{groups}->{$group} = 1;
1451 } else {
1452 warn "user config - ignore invalid group member '$user'\n";
1453 }
1454 $cfg->{groups}->{$group}->{users}->{$user} = 1;
1455 }
1456
1457 } elsif ($et eq 'role') {
1458 my ($role, $privlist) = @data;
1459
1460 if (!verify_rolename($role, 1)) {
1461 warn "user config - ignore role '$role' - invalid characters in role name\n";
1462 next;
1463 }
1464
1465 # make sure to add the role (even if there are no privileges)
1466 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
1467
1468 foreach my $priv (split_list($privlist)) {
1469 if (defined ($valid_privs->{$priv})) {
1470 $cfg->{roles}->{$role}->{$priv} = 1;
1471 } else {
1472 warn "user config - ignore invalid privilege '$priv'\n";
1473 }
1474 }
1475
1476 } elsif ($et eq 'acl') {
1477 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
1478
1479 $propagate = $propagate ? 1 : 0;
1480
1481 if (my $path = normalize_path($pathtxt)) {
1482 my $acl_node;
1483 foreach my $role (split_list($rolelist)) {
1484
1485 if (!verify_rolename($role, 1)) {
1486 warn "user config - ignore invalid role name '$role' in acl\n";
1487 next;
1488 }
1489
1490 if (!$cfg->{roles}->{$role}) {
1491 warn "user config - ignore invalid acl role '$role'\n";
1492 next;
1493 }
1494
1495 foreach my $ug (split_list($uglist)) {
1496 my ($group) = $ug =~ m/^@(\S+)$/;
1497
1498 if ($group && verify_groupname($group, 1)) {
1499 if (!$cfg->{groups}->{$group}) { # group does not exist
1500 warn "user config - ignore invalid acl group '$group'\n";
1501 }
1502 $acl_node = find_acl_tree_node($cfg->{acl_root}, $path) if !$acl_node;
1503 $acl_node->{groups}->{$group}->{$role} = $propagate;
1504 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
1505 if (!$cfg->{users}->{$ug}) { # user does not exist
1506 warn "user config - ignore invalid acl member '$ug'\n";
1507 }
1508 $acl_node = find_acl_tree_node($cfg->{acl_root}, $path) if !$acl_node;
1509 $acl_node->{users}->{$ug}->{$role} = $propagate;
1510 } elsif (my ($user, $token) = split_tokenid($ug, 1)) {
1511 if (check_token_exist($cfg, $user, $token, 1)) {
1512 $acl_node = find_acl_tree_node($cfg->{acl_root}, $path) if !$acl_node;
1513 $acl_node->{tokens}->{$ug}->{$role} = $propagate;
1514 } else {
1515 warn "user config - ignore invalid acl token '$ug'\n";
1516 }
1517 } else {
1518 warn "user config - invalid user/group '$ug' in acl\n";
1519 }
1520 }
1521 }
1522 } else {
1523 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1524 }
1525 } elsif ($et eq 'pool') {
1526 my ($pool, $comment, $vmlist, $storelist) = @data;
1527
1528 if (!verify_poolname($pool, 1)) {
1529 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1530 next;
1531 }
1532
1533 # make sure to add the pool (even if there are no members)
1534 $cfg->{pools}->{$pool} = { vms => {}, storage => {}, pools => {} }
1535 if !$cfg->{pools}->{$pool};
1536
1537 if ($pool =~ m!/!) {
1538 my $curr = $pool;
1539 while ($curr =~ m!^(.+)/[^/]+$!) {
1540 # ensure nested pool info is correctly recorded
1541 my $parent = $1;
1542 $cfg->{pools}->{$curr}->{parent} = $parent;
1543 $cfg->{pools}->{$parent} = { vms => {}, storage => {}, pools => {} }
1544 if !$cfg->{pools}->{$parent};
1545 $cfg->{pools}->{$parent}->{pools}->{$curr} = 1;
1546 $curr = $parent;
1547 }
1548 }
1549
1550 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1551
1552 foreach my $vmid (split_list($vmlist)) {
1553 if ($vmid !~ m/^\d+$/) {
1554 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1555 next;
1556 }
1557 $vmid = int($vmid);
1558
1559 if ($cfg->{vms}->{$vmid}) {
1560 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1561 next;
1562 }
1563
1564 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
1565
1566 # record vmid ==> pool relation
1567 $cfg->{vms}->{$vmid} = $pool;
1568 }
1569
1570 foreach my $storeid (split_list($storelist)) {
1571 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1572 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1573 next;
1574 }
1575 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
1576 }
1577 } elsif ($et eq 'token') {
1578 my ($tokenid, $expire, $privsep, $comment) = @data;
1579
1580 my ($user, $token) = split_tokenid($tokenid, 1);
1581 if (!($user && $token)) {
1582 warn "user config - ignore invalid tokenid '$tokenid'\n";
1583 next;
1584 }
1585
1586 $privsep = $privsep ? 1 : 0;
1587
1588 $expire = 0 if !$expire;
1589
1590 if ($expire !~ m/^\d+$/) {
1591 warn "user config - ignore token '$tokenid' - (illegal characters in expire '$expire')\n";
1592 next;
1593 }
1594 $expire = int($expire);
1595
1596 if (my $user_cfg = $cfg->{users}->{$user}) { # user exists
1597 $user_cfg->{tokens}->{$token} = {} if !$user_cfg->{tokens}->{$token};
1598 my $token_cfg = $user_cfg->{tokens}->{$token};
1599 $token_cfg->{privsep} = $privsep;
1600 $token_cfg->{expire} = $expire;
1601 $token_cfg->{comment} = PVE::Tools::decode_text($comment) if $comment;
1602 } else {
1603 warn "user config - ignore token '$tokenid' - user does not exist\n";
1604 }
1605 } else {
1606 warn "user config - ignore config line: $line\n";
1607 }
1608 }
1609
1610 userconfig_force_defaults($cfg);
1611
1612 return $cfg;
1613 }
1614
1615 sub write_user_config {
1616 my ($filename, $cfg) = @_;
1617
1618 my $data = '';
1619
1620 foreach my $user (sort keys %{$cfg->{users}}) {
1621 my $d = $cfg->{users}->{$user};
1622 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1623 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1624 my $email = $d->{email} || '';
1625 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1626 my $expire = int($d->{expire} || 0);
1627 my $enable = $d->{enable} ? 1 : 0;
1628 my $keys = $d->{keys} ? $d->{keys} : '';
1629 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
1630
1631 my $user_tokens = $d->{tokens};
1632 foreach my $token (sort keys %$user_tokens) {
1633 my $td = $user_tokens->{$token};
1634 my $full_tokenid = join_tokenid($user, $token);
1635 my $comment = $td->{comment} ? PVE::Tools::encode_text($td->{comment}) : '';
1636 my $expire = int($td->{expire} || 0);
1637 my $privsep = $td->{privsep} ? 1 : 0;
1638 $data .= "token:$full_tokenid:$expire:$privsep:$comment:\n";
1639 }
1640 }
1641
1642 $data .= "\n";
1643
1644 foreach my $group (sort keys %{$cfg->{groups}}) {
1645 my $d = $cfg->{groups}->{$group};
1646 my $list = join (',', sort keys %{$d->{users}});
1647 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1648 $data .= "group:$group:$list:$comment:\n";
1649 }
1650
1651 $data .= "\n";
1652
1653 foreach my $pool (sort keys %{$cfg->{pools}}) {
1654 my $d = $cfg->{pools}->{$pool};
1655 my $vmlist = join (',', sort keys %{$d->{vms}});
1656 my $storelist = join (',', sort keys %{$d->{storage}});
1657 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1658 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1659 }
1660
1661 $data .= "\n";
1662
1663 foreach my $role (sort keys %{$cfg->{roles}}) {
1664 next if $special_roles->{$role};
1665
1666 my $d = $cfg->{roles}->{$role};
1667 my $list = join (',', sort keys %$d);
1668 $data .= "role:$role:$list:\n";
1669 }
1670
1671 $data .= "\n";
1672
1673 my $collect_rolelist_members = sub {
1674 my ($acl_members, $result, $prefix, $exclude) = @_;
1675
1676 foreach my $member (keys %$acl_members) {
1677 next if $exclude && $member eq $exclude;
1678
1679 my $l0 = '';
1680 my $l1 = '';
1681 foreach my $role (sort keys %{$acl_members->{$member}}) {
1682 my $propagate = $acl_members->{$member}->{$role};
1683 if ($propagate) {
1684 $l1 .= ',' if $l1;
1685 $l1 .= $role;
1686 } else {
1687 $l0 .= ',' if $l0;
1688 $l0 .= $role;
1689 }
1690 }
1691 $result->{0}->{$l0}->{"${prefix}${member}"} = 1 if $l0;
1692 $result->{1}->{$l1}->{"${prefix}${member}"} = 1 if $l1;
1693 }
1694 };
1695
1696 iterate_acl_tree("/", $cfg->{acl_root}, sub {
1697 my ($path, $d) = @_;
1698
1699 my $rolelist_members = {};
1700
1701 $collect_rolelist_members->($d->{'groups'}, $rolelist_members, '@');
1702
1703 # no need to save 'root@pam', it is always 'Administrator'
1704 $collect_rolelist_members->($d->{'users'}, $rolelist_members, '', 'root@pam');
1705
1706 $collect_rolelist_members->($d->{'tokens'}, $rolelist_members, '');
1707
1708 foreach my $propagate (0,1) {
1709 my $filtered = $rolelist_members->{$propagate};
1710 foreach my $rolelist (sort keys %$filtered) {
1711 my $uglist = join (',', sort keys %{$filtered->{$rolelist}});
1712 $data .= "acl:$propagate:$path:$uglist:$rolelist:\n";
1713 }
1714
1715 }
1716 });
1717
1718 return $data;
1719 }
1720
1721 # Creates a `PVE::RS::TFA` instance from the raw config data.
1722 # Its contained hash will also support the legacy functionality.
1723 sub parse_priv_tfa_config {
1724 my ($filename, $raw) = @_;
1725
1726 $raw = '' if !defined($raw);
1727 my $cfg = PVE::RS::TFA->new($raw);
1728
1729 # Purge invalid users:
1730 foreach my $user ($cfg->users()->@*) {
1731 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1732 if (!$realm) {
1733 warn "user tfa config - ignore user '$user' - invalid user name\n";
1734 $cfg->remove_user($user);
1735 }
1736 }
1737
1738 return $cfg;
1739 }
1740
1741 sub write_priv_tfa_config {
1742 my ($filename, $cfg) = @_;
1743
1744 return $cfg->write();
1745 }
1746
1747 sub roles {
1748 my ($cfg, $user, $path) = @_;
1749
1750 # NOTE: we do not consider pools here.
1751 # NOTE: for privsep tokens, this does not filter roles by those that the
1752 # corresponding user has.
1753 # Use $rpcenv->permission() for any actual permission checks!
1754
1755 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1756
1757 if (!defined($path)) {
1758 # this shouldn't happen!
1759 warn "internal error: ACL check called for undefined ACL path!\n";
1760 return {};
1761 }
1762
1763 if (pve_verify_tokenid($user, 1)) {
1764 my $tokenid = $user;
1765 my ($username, $token) = split_tokenid($tokenid);
1766
1767 my $token_info = $cfg->{users}->{$username}->{tokens}->{$token};
1768 return () if !$token_info;
1769
1770 my $user_roles = roles($cfg, $username, $path);
1771
1772 # return full user privileges
1773 return $user_roles if !$token_info->{privsep};
1774 }
1775
1776 my $roles = {};
1777
1778 my $split = [ split("/", $path) ];
1779 if ($path eq '/') {
1780 $split = [ '' ];
1781 }
1782
1783 my $acl = $cfg->{acl_root};
1784 my $i = 0;
1785
1786 while (@$split) {
1787 my $p = shift @$split;
1788 my $final = !@$split;
1789 if ($p ne '') {
1790 $acl = $acl->{children}->{$p};
1791 }
1792
1793 #print "CHECKACL $path $p\n";
1794 #print "ACL $path = " . Dumper ($acl);
1795 if (my $ri = $acl->{tokens}->{$user}) {
1796 my $new;
1797 foreach my $role (keys %$ri) {
1798 my $propagate = $ri->{$role};
1799 if ($final || $propagate) {
1800 #print "APPLY ROLE $p $user $role\n";
1801 $new = {} if !$new;
1802 $new->{$role} = $propagate;
1803 }
1804 }
1805 if ($new) {
1806 $roles = $new; # overwrite previous settings
1807 next;
1808 }
1809 }
1810
1811 if (my $ri = $acl->{users}->{$user}) {
1812 my $new;
1813 foreach my $role (keys %$ri) {
1814 my $propagate = $ri->{$role};
1815 if ($final || $propagate) {
1816 #print "APPLY ROLE $p $user $role\n";
1817 $new = {} if !$new;
1818 $new->{$role} = $propagate;
1819 }
1820 }
1821 if ($new) {
1822 $roles = $new; # overwrite previous settings
1823 next; # user privs always override group privs
1824 }
1825 }
1826
1827 my $new;
1828 foreach my $g (keys %{$acl->{groups}}) {
1829 next if !$cfg->{groups}->{$g}->{users}->{$user};
1830 if (my $ri = $acl->{groups}->{$g}) {
1831 foreach my $role (keys %$ri) {
1832 my $propagate = $ri->{$role};
1833 if ($final || $propagate) {
1834 #print "APPLY ROLE $p \@$g $role\n";
1835 $new = {} if !$new;
1836 $new->{$role} = $propagate;
1837 }
1838 }
1839 }
1840 }
1841 if ($new) {
1842 $roles = $new; # overwrite previous settings
1843 next;
1844 }
1845 }
1846
1847 return { 'NoAccess' => $roles->{NoAccess} } if defined ($roles->{NoAccess});
1848 #return () if defined ($roles->{NoAccess});
1849
1850 #print "permission $user $path = " . Dumper ($roles);
1851
1852 #print "roles $user $path = " . join (',', @ra) . "\n";
1853
1854 return $roles;
1855 }
1856
1857 sub remove_vm_access {
1858 my ($vmid) = @_;
1859 my $delVMaccessFn = sub {
1860 my $usercfg = cfs_read_file("user.cfg");
1861 my $modified;
1862
1863 if (my $acl = $usercfg->{acl_root}->{children}->{vms}->{children}->{$vmid}) {
1864 delete $usercfg->{acl_root}->{children}->{vms}->{children}->{$vmid};
1865 $modified = 1;
1866 }
1867 if (my $pool = $usercfg->{vms}->{$vmid}) {
1868 if (my $data = $usercfg->{pools}->{$pool}) {
1869 delete $data->{vms}->{$vmid};
1870 delete $usercfg->{vms}->{$vmid};
1871 $modified = 1;
1872 }
1873 }
1874 cfs_write_file("user.cfg", $usercfg) if $modified;
1875 };
1876
1877 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1878 }
1879
1880 sub remove_storage_access {
1881 my ($storeid) = @_;
1882
1883 my $deleteStorageAccessFn = sub {
1884 my $usercfg = cfs_read_file("user.cfg");
1885 my $modified;
1886
1887 if (my $acl = $usercfg->{acl_root}->{children}->{storage}->{children}->{$storeid}) {
1888 delete $usercfg->{acl_root}->{children}->{storage}->{children}->{$storeid};
1889 $modified = 1;
1890 }
1891 foreach my $pool (keys %{$usercfg->{pools}}) {
1892 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1893 $modified = 1;
1894 }
1895 cfs_write_file("user.cfg", $usercfg) if $modified;
1896 };
1897
1898 lock_user_config($deleteStorageAccessFn,
1899 "access permissions cleanup for storage $storeid failed");
1900 }
1901
1902 sub add_vm_to_pool {
1903 my ($vmid, $pool) = @_;
1904
1905 my $addVMtoPoolFn = sub {
1906 my $usercfg = cfs_read_file("user.cfg");
1907 if (my $data = $usercfg->{pools}->{$pool}) {
1908 $data->{vms}->{$vmid} = 1;
1909 $usercfg->{vms}->{$vmid} = $pool;
1910 cfs_write_file("user.cfg", $usercfg);
1911 }
1912 };
1913
1914 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1915 }
1916
1917 sub remove_vm_from_pool {
1918 my ($vmid) = @_;
1919
1920 my $delVMfromPoolFn = sub {
1921 my $usercfg = cfs_read_file("user.cfg");
1922 if (my $pool = $usercfg->{vms}->{$vmid}) {
1923 if (my $data = $usercfg->{pools}->{$pool}) {
1924 delete $data->{vms}->{$vmid};
1925 delete $usercfg->{vms}->{$vmid};
1926 cfs_write_file("user.cfg", $usercfg);
1927 }
1928 }
1929 };
1930
1931 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1932 }
1933
1934 my $USER_CONTROLLED_TFA_TYPES = {
1935 u2f => 1,
1936 oath => 1,
1937 };
1938
1939 sub user_remove_tfa : prototype($) {
1940 my ($userid) = @_;
1941
1942 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1943 $tfa_cfg->remove_user($userid);
1944 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1945 }
1946
1947 my sub add_old_yubico_keys : prototype($$$) {
1948 my ($userid, $tfa_cfg, $keys) = @_;
1949
1950 my $count = 0;
1951 foreach my $key (split_list($keys)) {
1952 my $description = "<old userconfig key $count>";
1953 ++$count;
1954 $tfa_cfg->add_yubico_entry($userid, $description, $key);
1955 }
1956 }
1957
1958 my sub normalize_totp_secret : prototype($) {
1959 my ($key) = @_;
1960
1961 my $binkey;
1962 # See PVE::OTP::oath_verify_otp:
1963 if ($key =~ /^v2-0x([0-9a-fA-F]+)$/) {
1964 # v2, hex
1965 $binkey = pack('H*', $1);
1966 } elsif ($key =~ /^v2-([A-Z2-7=]+)$/) {
1967 # v2, base32
1968 $binkey = MIME::Base32::decode_rfc3548($1);
1969 } elsif ($key =~ /^[A-Z2-7=]{16}$/) {
1970 $binkey = MIME::Base32::decode_rfc3548($key);
1971 } elsif ($key =~ /^[A-Fa-f0-9]{40}$/) {
1972 $binkey = pack('H*', $key);
1973 } else {
1974 return undef;
1975 }
1976
1977 return MIME::Base32::encode_rfc3548($binkey);
1978 }
1979
1980 my sub add_old_totp_keys : prototype($$$$) {
1981 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
1982
1983 my $issuer = 'Proxmox%20VE';
1984 my $account = uri_escape("Old key for $userid");
1985 my $digits = $realm_tfa->{digits} || 6;
1986 my $step = $realm_tfa->{step} || 30;
1987 my $uri = "otpauth://totp/$issuer:$account?digits=$digits&period=$step&algorithm=SHA1&secret=";
1988
1989 my $count = 0;
1990 foreach my $key (split_list($keys)) {
1991 $key = normalize_totp_secret($key);
1992 # and just skip invalid keys:
1993 next if !defined($key);
1994
1995 my $description = "<old userconfig key $count>";
1996 ++$count;
1997 eval { $tfa_cfg->add_totp_entry($userid, $description, $uri . $key) };
1998 warn $@ if $@;
1999 }
2000 }
2001
2002 sub add_old_keys_to_realm_tfa : prototype($$$$) {
2003 my ($userid, $tfa_cfg, $realm_tfa, $keys) = @_;
2004
2005 # if there's no realm tfa configured, we don't know what the keys mean, so we just ignore
2006 # them...
2007 return if !$realm_tfa;
2008
2009 my $type = $realm_tfa->{type};
2010 if ($type eq 'oath') {
2011 add_old_totp_keys($userid, $tfa_cfg, $realm_tfa, $keys);
2012 } elsif ($type eq 'yubico') {
2013 add_old_yubico_keys($userid, $tfa_cfg, $keys);
2014 } else {
2015 # invalid keys, we'll just drop them now...
2016 }
2017 }
2018
2019 sub user_get_tfa : prototype($$$) {
2020 my ($username, $realm) = @_;
2021
2022 my $user_cfg = cfs_read_file('user.cfg');
2023 my $user = $user_cfg->{users}->{$username}
2024 or die "user '$username' not found\n";
2025
2026 my $keys = $user->{keys};
2027
2028 my $domain_cfg = cfs_read_file('domains.cfg');
2029 my $realm_cfg = $domain_cfg->{ids}->{$realm};
2030 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
2031
2032 my $realm_tfa = $realm_cfg->{tfa};
2033 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
2034 if $realm_tfa;
2035
2036 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
2037 if (defined($keys) && $keys !~ /^x(?:!.*)$/) {
2038 add_old_keys_to_realm_tfa($username, $tfa_cfg, $realm_tfa, $keys);
2039 }
2040
2041 return ($tfa_cfg, $realm_tfa);
2042 }
2043
2044 # bash completion helpers
2045
2046 register_standard_option('userid-completed',
2047 get_standard_option('userid', { completion => \&complete_username}),
2048 );
2049
2050 sub complete_username {
2051
2052 my $user_cfg = cfs_read_file('user.cfg');
2053
2054 return [ keys %{$user_cfg->{users}} ];
2055 }
2056
2057 sub complete_group {
2058
2059 my $user_cfg = cfs_read_file('user.cfg');
2060
2061 return [ keys %{$user_cfg->{groups}} ];
2062 }
2063
2064 sub complete_realm {
2065
2066 my $domain_cfg = cfs_read_file('domains.cfg');
2067
2068 return [ keys %{$domain_cfg->{ids}} ];
2069 }
2070
2071 1;