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