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