]> git.proxmox.com Git - pve-access-control.git/blame - src/PVE/AccessControl.pm
add OpenId configuration
[pve-access-control.git] / src / PVE / AccessControl.pm
CommitLineData
2c3a6c0a
DM
1package PVE::AccessControl;
2
3use strict;
7c410d63 4use warnings;
2c3a6c0a
DM
5use Encode;
6use Crypt::OpenSSL::Random;
7use Crypt::OpenSSL::RSA;
cee5583b 8use Net::SSLeay;
25167526 9use Net::IP;
2c3a6c0a
DM
10use MIME::Base64;
11use Digest::SHA;
21800a71
FG
12use IO::File;
13use File::stat;
fda8ca85 14use JSON;
a1f8aaae 15
972859d1 16use PVE::OTP;
a1f8aaae 17use PVE::Ticket;
2c3a6c0a
DM
18use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
19use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
ab7b19b5 20use PVE::JSONSchema qw(register_standard_option get_standard_option);
5bb4e06a
DM
21
22use PVE::Auth::Plugin;
23use PVE::Auth::AD;
24use PVE::Auth::LDAP;
25use PVE::Auth::PVE;
26use PVE::Auth::PAM;
52d1c1b9 27use PVE::Auth::OpenId;
2c3a6c0a 28
5bb4e06a
DM
29# load and initialize all plugins
30
31PVE::Auth::AD->register();
32PVE::Auth::LDAP->register();
33PVE::Auth::PVE->register();
34PVE::Auth::PAM->register();
52d1c1b9 35PVE::Auth::OpenId->register();
5bb4e06a
DM
36PVE::Auth::Plugin->init();
37
2c3a6c0a
DM
38# $authdir must be writable by root only!
39my $confdir = "/etc/pve";
40my $authdir = "$confdir/priv";
21800a71 41
2c3a6c0a
DM
42my $pve_www_key_fn = "$confdir/pve-www.key";
43
21800a71
FG
44my $pve_auth_key_files = {
45 priv => "$authdir/authkey.key",
46 pub => "$confdir/authkey.pub",
47 pubold => "$confdir/authkey.pub.old",
48};
49
50my $pve_auth_key_cache = {};
51
243262f1 52my $ticket_lifetime = 3600 * 2; # 2 hours
8304b226 53my $auth_graceperiod = 60 * 5; # 5 minutes
243262f1 54my $authkey_lifetime = 3600 * 24; # rotate every 24 hours
2c3a6c0a
DM
55
56Crypt::OpenSSL::RSA->import_random_seed();
57
d7e8d24e
TL
58cfs_register_file('user.cfg', \&parse_user_config, \&write_user_config);
59cfs_register_file('priv/tfa.cfg', \&parse_priv_tfa_config, \&write_priv_tfa_config);
2c3a6c0a 60
5bb4e06a
DM
61sub verify_username {
62 PVE::Auth::Plugin::verify_username(@_);
2c3a6c0a
DM
63}
64
5bb4e06a
DM
65sub pve_verify_realm {
66 PVE::Auth::Plugin::pve_verify_realm(@_);
2c3a6c0a
DM
67}
68
5bb4e06a 69sub lock_user_config {
2c3a6c0a
DM
70 my ($code, $errmsg) = @_;
71
5bb4e06a
DM
72 cfs_lock_file("user.cfg", undef, $code);
73 if (my $err = $@) {
2c3a6c0a
DM
74 $errmsg ? die "$errmsg: $err" : die $err;
75 }
76}
77
21800a71
FG
78my $cache_read_key = sub {
79 my ($type) = @_;
80
81 my $path = $pve_auth_key_files->{$type};
82
83 my $read_key_and_mtime = sub {
84 my $fh = IO::File->new($path, "r");
85
86 return undef if !defined($fh);
87
88 my $st = stat($fh);
89 my $pem = PVE::Tools::safe_read_from($fh, 0, 0, $path);
90
91 close $fh;
92
93 my $key;
94 if ($type eq 'pub' || $type eq 'pubold') {
95 $key = eval { Crypt::OpenSSL::RSA->new_public_key($pem); };
96 } elsif ($type eq 'priv') {
97 $key = eval { Crypt::OpenSSL::RSA->new_private_key($pem); };
98 } else {
99 die "Invalid authkey type '$type'\n";
100 }
101
102 return { key => $key, mtime => $st->mtime };
103 };
104
105 if (!defined($pve_auth_key_cache->{$type})) {
106 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
107 } else {
108 my $st = stat($path);
109 if (!$st || $st->mtime != $pve_auth_key_cache->{$type}->{mtime}) {
110 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
111 }
112 }
113
114 return $pve_auth_key_cache->{$type};
115};
116
66931b11 117sub get_pubkey {
21800a71
FG
118 my ($old) = @_;
119
120 my $type = $old ? 'pubold' : 'pub';
121
122 my $res = $cache_read_key->($type);
123 return undef if !defined($res);
124
125 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
126}
127
128sub get_privkey {
129 my $res = $cache_read_key->('priv');
2c3a6c0a 130
21800a71
FG
131 if (!defined($res) || !check_authkey(1)) {
132 rotate_authkey();
133 $res = $cache_read_key->('priv');
134 }
2c3a6c0a 135
21800a71
FG
136 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
137}
2c3a6c0a 138
21800a71
FG
139sub check_authkey {
140 my ($quiet) = @_;
141
142 # skip check if non-quorate, as rotation is not possible anyway
143 return 1 if !PVE::Cluster::check_cfs_quorum(1);
144
145 my ($pub_key, $mtime) = get_pubkey();
146 if (!$pub_key) {
147 warn "auth key pair missing, generating new one..\n" if !$quiet;
148 return 0;
149 } else {
9de25de8
TL
150 my $now = time();
151 if ($now - $mtime >= $authkey_lifetime) {
21800a71
FG
152 warn "auth key pair too old, rotating..\n" if !$quiet;;
153 return 0;
9de25de8
TL
154 } elsif ($mtime > $now + $auth_graceperiod) {
155 # a nodes RTC had a time set in the future during key generation -> ticket
156 # validity is clamped to 0+5 min grace period until now >= mtime again
157 my (undef, $old_mtime) = get_pubkey(1);
158 if ($old_mtime && $mtime >= $old_mtime && $mtime - $old_mtime < $ticket_lifetime) {
159 warn "auth key pair generated in the future (key $mtime > host $now),"
160 ." but old key still exists and in valid grace period so avoid automatic"
161 ." fixup. Cluster time not in sync?\n" if !$quiet;
162 return 1;
163 }
164 warn "auth key pair generated in the future (key $mtime > host $now), rotating..\n" if !$quiet;
165 return 0;
21800a71
FG
166 } else {
167 warn "auth key new enough, skipping rotation\n" if !$quiet;;
168 return 1;
169 }
170 }
171}
2c3a6c0a 172
21800a71
FG
173sub rotate_authkey {
174 return if $authkey_lifetime == 0;
175
03593f3d 176 PVE::Cluster::cfs_lock_authkey(undef, sub {
21800a71
FG
177 # re-check with lock to avoid double rotation in clusters
178 return if check_authkey();
179
180 my $old = get_pubkey();
e770e667 181 my $new = Crypt::OpenSSL::RSA->generate_key(2048);
21800a71
FG
182
183 if ($old) {
184 eval {
185 my $pem = $old->get_public_key_x509_string();
b8055a4f 186 # mtime is used for caching and ticket age range calculation
21800a71
FG
187 PVE::Tools::file_set_contents($pve_auth_key_files->{pubold}, $pem);
188 };
189 die "Failed to store old auth key: $@\n" if $@;
190 }
191
21800a71
FG
192 eval {
193 my $pem = $new->get_public_key_x509_string();
b8055a4f
FG
194 # mtime is used for caching and ticket age range calculation,
195 # should be close to that of pubold above
21800a71
FG
196 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
197 };
198 if ($@) {
199 if ($old) {
200 warn "Failed to store new auth key - $@\n";
201 warn "Reverting to previous auth key\n";
202 eval {
203 my $pem = $old->get_public_key_x509_string();
204 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
205 };
206 die "Failed to restore old auth key: $@\n" if $@;
207 } else {
208 die "Failed to store new auth key - $@\n";
209 }
210 }
211
212 eval {
213 my $pem = $new->get_private_key_string();
214 PVE::Tools::file_set_contents($pve_auth_key_files->{priv}, $pem);
215 };
216 if ($@) {
217 warn "Failed to store new auth key - $@\n";
218 warn "Deleting auth key to force regeneration\n";
219 unlink $pve_auth_key_files->{pub};
220 unlink $pve_auth_key_files->{priv};
221 }
222 });
223 die $@ if $@;
2c3a6c0a
DM
224}
225
571e9d06
FG
226PVE::JSONSchema::register_standard_option('tokenid', {
227 description => "API token identifier.",
228 type => "string",
229 format => "pve-tokenid",
230});
231
28e3dc05
FG
232our $token_subid_regex = $PVE::Auth::Plugin::realm_regex;
233
234# username@realm username realm tokenid
235our $token_full_regex = qr/((${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex}))!(${token_subid_regex})/;
236
237our $userid_or_token_regex = qr/^$PVE::Auth::Plugin::user_regex\@$PVE::Auth::Plugin::realm_regex(?:!$token_subid_regex)?$/;
238
239sub split_tokenid {
240 my ($tokenid, $noerr) = @_;
241
242 if ($tokenid =~ /^${token_full_regex}$/) {
243 return ($1, $4);
244 }
245
246 die "'$tokenid' is not a valid token ID - not able to split into user and token parts\n" if !$noerr;
247
248 return undef;
249}
250
251sub join_tokenid {
252 my ($username, $tokensubid) = @_;
253
254 my $joined = "${username}!${tokensubid}";
255
256 return pve_verify_tokenid($joined);
257}
258
259PVE::JSONSchema::register_format('pve-tokenid', \&pve_verify_tokenid);
260sub pve_verify_tokenid {
261 my ($tokenid, $noerr) = @_;
262
263 if ($tokenid =~ /^${token_full_regex}$/) {
264 return wantarray ? ($tokenid, $2, $3, $4) : $tokenid;
265 }
266
267 die "value '$tokenid' does not look like a valid token ID\n" if !$noerr;
268
269 return undef;
270}
271
272
2c3a6c0a 273my $csrf_prevention_secret;
e149b1c6 274my $csrf_prevention_secret_legacy;
2c3a6c0a
DM
275my $get_csrfr_secret = sub {
276 if (!$csrf_prevention_secret) {
66931b11 277 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
51e6f56d 278 $csrf_prevention_secret = Digest::SHA::hmac_sha256_base64($input);
e149b1c6 279 $csrf_prevention_secret_legacy = Digest::SHA::sha1_base64($input);
2c3a6c0a
DM
280 }
281 return $csrf_prevention_secret;
282};
283
284sub assemble_csrf_prevention_token {
285 my ($username) = @_;
286
a1f8aaae 287 my $secret = &$get_csrfr_secret();
2c3a6c0a 288
a1f8aaae 289 return PVE::Ticket::assemble_csrf_prevention_token ($secret, $username);
2c3a6c0a
DM
290}
291
292sub verify_csrf_prevention_token {
293 my ($username, $token, $noerr) = @_;
294
e149b1c6
TL
295 my $secret = $get_csrfr_secret->();
296
297 # FIXME: remove with PVE 7 and/or refactor all into PVE::Ticket ?
298 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
299 my $sig = $2;
300 if (length($sig) == 27) {
301 # the legacy secret got populated by above get_csrfr_secret call
302 $secret = $csrf_prevention_secret_legacy;
303 }
304 }
2c3a6c0a 305
a1f8aaae 306 return PVE::Ticket::verify_csrf_prevention_token(
8304b226 307 $secret, $username, $token, -$auth_graceperiod, $ticket_lifetime, $noerr);
2c3a6c0a
DM
308}
309
21800a71
FG
310my $get_ticket_age_range = sub {
311 my ($now, $mtime, $rotated) = @_;
312
313 my $key_age = $now - $mtime;
314 $key_age = 0 if $key_age < 0;
315
8304b226 316 my $min = -$auth_graceperiod;
21800a71
FG
317 my $max = $ticket_lifetime;
318
319 if ($rotated) {
320 # ticket creation after rotation is not allowed
8304b226 321 $min = $key_age - $auth_graceperiod;
21800a71
FG
322 } else {
323 if ($key_age > $authkey_lifetime && $authkey_lifetime > 0) {
324 if (PVE::Cluster::check_cfs_quorum(1)) {
325 # key should have been rotated, clamp range accordingly
326 $min = $key_age - $authkey_lifetime;
327 } else {
328 warn "Cluster not quorate - extending auth key lifetime!\n";
329 }
330 }
331
8304b226 332 $max = $key_age + $auth_graceperiod if $key_age < $ticket_lifetime;
21800a71 333 }
2c3a6c0a 334
21800a71
FG
335 return undef if $min > $ticket_lifetime;
336 return ($min, $max);
337};
2c3a6c0a
DM
338
339sub assemble_ticket {
18f8ba18 340 my ($data) = @_;
2c3a6c0a
DM
341
342 my $rsa_priv = get_privkey();
343
18f8ba18 344 return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $data);
2c3a6c0a
DM
345}
346
347sub verify_ticket {
348 my ($ticket, $noerr) = @_;
349
21800a71
FG
350 my $now = time();
351
352 my $check = sub {
353 my ($old) = @_;
354
355 my ($rsa_pub, $rsa_mtime) = get_pubkey($old);
356 return undef if !$rsa_pub;
357
358 my ($min, $max) = $get_ticket_age_range->($now, $rsa_mtime, $old);
5bb966fe 359 return undef if !defined($min);
21800a71
FG
360
361 return PVE::Ticket::verify_rsa_ticket(
362 $rsa_pub, 'PVE', $ticket, undef, $min, $max, 1);
363 };
a1f8aaae 364
18f8ba18 365 my ($data, $age) = $check->();
a1f8aaae 366
21800a71 367 # check with old, rotated key if current key failed
18f8ba18 368 ($data, $age) = $check->(1) if !defined($data);
21800a71 369
18f8ba18 370 my $auth_failure = sub {
21800a71
FG
371 if ($noerr) {
372 return undef;
373 } else {
374 # raise error via undef ticket
375 PVE::Ticket::verify_rsa_ticket(undef, 'PVE');
376 }
18f8ba18
WB
377 };
378
379 if (!defined($data)) {
380 return $auth_failure->();
381 }
382
f25628d3 383 my ($username, $tfa_info);
18f8ba18
WB
384 if ($data =~ m{^u2f!([^!]+)!([0-9a-zA-Z/.=_\-+]+)$}) {
385 # Ticket for u2f-users:
f25628d3 386 ($username, my $challenge) = ($1, $2);
18f8ba18
WB
387 if ($challenge eq 'verified') {
388 # u2f challenge was completed
389 $challenge = undef;
390 } elsif (!wantarray) {
391 # The caller is not aware there could be an ongoing challenge,
392 # so we treat this ticket as invalid:
393 return $auth_failure->();
394 }
f25628d3
WB
395 $tfa_info = {
396 type => 'u2f',
397 challenge => $challenge,
398 };
399 } elsif ($data =~ /^tfa!(.*)$/) {
400 # TOTP and Yubico don't require a challenge so this is the generic
401 # 'missing 2nd factor ticket'
402 $username = $1;
403 $tfa_info = { type => 'tfa' };
18f8ba18
WB
404 } else {
405 # Regular ticket (full access)
406 $username = $data;
21800a71 407 }
2c3a6c0a 408
a1f8aaae 409 return undef if !PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 410
f25628d3 411 return wantarray ? ($username, $age, $tfa_info) : $username;
2c3a6c0a
DM
412}
413
35c3ca0f
FG
414sub verify_token {
415 my ($api_token) = @_;
416
417 die "no API token specified\n" if !$api_token;
418
419 my ($tokenid, $value);
420 if ($api_token =~ /^(.*)=(.*)$/) {
421 $tokenid = $1;
422 $value = $2;
423 } else {
424 die "no tokenid specified\n";
425 }
426
427 my ($username, $token) = split_tokenid($tokenid);
428
429 my $usercfg = cfs_read_file('user.cfg');
430 check_user_enabled($usercfg, $username);
431 check_token_exist($usercfg, $username, $token);
432
35c3ca0f 433 my $user = $usercfg->{users}->{$username};
35c3ca0f 434 my $token_info = $user->{tokens}->{$token};
8a724f7b
DM
435
436 my $ctime = time();
35c3ca0f
FG
437 die "token expired\n" if $token_info->{expire} && ($token_info->{expire} < $ctime);
438
439 die "invalid token value!\n" if !PVE::Cluster::verify_token($tokenid, $value);
440
441 return wantarray ? ($tokenid) : $tokenid;
442}
443
444
adf8d771
DM
445# VNC tickets
446# - they do not contain the username in plain text
447# - they are restricted to a specific resource path (example: '/vms/100')
448sub assemble_vnc_ticket {
449 my ($username, $path) = @_;
450
451 my $rsa_priv = get_privkey();
452
adf8d771
DM
453 $path = normalize_path($path);
454
a1f8aaae 455 my $secret_data = "$username:$path";
adf8d771 456
a1f8aaae
DM
457 return PVE::Ticket::assemble_rsa_ticket(
458 $rsa_priv, 'PVEVNC', undef, $secret_data);
adf8d771
DM
459}
460
461sub verify_vnc_ticket {
462 my ($ticket, $username, $path, $noerr) = @_;
463
a1f8aaae 464 my $secret_data = "$username:$path";
adf8d771 465
21800a71 466 my ($rsa_pub, $rsa_mtime) = get_pubkey();
5efff6c1 467 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime && $authkey_lifetime > 0)) {
21800a71
FG
468 if ($noerr) {
469 return undef;
470 } else {
471 # raise error via undef ticket
472 PVE::Ticket::verify_rsa_ticket($rsa_pub, 'PVEVNC');
473 }
474 }
475
a1f8aaae
DM
476 return PVE::Ticket::verify_rsa_ticket(
477 $rsa_pub, 'PVEVNC', $ticket, $secret_data, -20, 40, $noerr);
adf8d771
DM
478}
479
23b35225 480sub assemble_spice_ticket {
bf3e6d31 481 my ($username, $vmid, $node) = @_;
23b35225 482
3f62bdbe 483 my $secret = &$get_csrfr_secret();
23b35225 484
a1f8aaae
DM
485 return PVE::Ticket::assemble_spice_ticket(
486 $secret, $username, $vmid, $node);
bf3e6d31
DM
487}
488
489sub verify_spice_connect_url {
490 my ($connect_str) = @_;
491
a1f8aaae 492 my $secret = &$get_csrfr_secret();
bf3e6d31 493
a1f8aaae 494 return PVE::Ticket::verify_spice_connect_url($secret, $connect_str);
23b35225
AD
495}
496
cee5583b
DM
497sub read_x509_subject_spice {
498 my ($filename) = @_;
499
500 # read x509 subject
501 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
44903703
FG
502 die "Could not open $filename using OpenSSL\n"
503 if !$bio;
504
cee5583b
DM
505 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
506 Net::SSLeay::BIO_free($bio);
44903703
FG
507
508 die "Could not parse X509 certificate in $filename\n"
509 if !$x509;
510
cee5583b
DM
511 my $nameobj = Net::SSLeay::X509_get_subject_name($x509);
512 my $subject = Net::SSLeay::X509_NAME_oneline($nameobj);
513 Net::SSLeay::X509_free($x509);
66931b11 514
cee5583b
DM
515 # remote-viewer wants comma as seperator (not '/')
516 $subject =~ s!^/!!;
517 $subject =~ s!/(\w+=)!,$1!g;
518
519 return $subject;
520}
521
522# helper to generate SPICE remote-viewer configuration
523sub remote_viewer_config {
524 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
525
526 if (!$proxy) {
527 my $host = `hostname -f` || PVE::INotify::nodename();
528 chomp $host;
529 $proxy = $host;
530 }
531
532 my ($ticket, $proxyticket) = assemble_spice_ticket($authuser, $vmid, $node);
533
534 my $filename = "/etc/pve/local/pve-ssl.pem";
535 my $subject = read_x509_subject_spice($filename);
536
537 my $cacert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192);
538 $cacert =~ s/\n/\\n/g;
63691fc6 539
25167526 540 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
cee5583b 541 my $config = {
63691fc6
DM
542 'secure-attention' => "Ctrl+Alt+Ins",
543 'toggle-fullscreen' => "Shift+F11",
544 'release-cursor' => "Ctrl+Alt+R",
cee5583b
DM
545 type => 'spice',
546 title => $title,
1075c589 547 host => $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
cee5583b
DM
548 proxy => "http://$proxy:3128",
549 'tls-port' => $port,
550 'host-subject' => $subject,
551 ca => $cacert,
552 password => $ticket,
553 'delete-this-file' => 1,
554 };
555
556 return ($ticket, $proxyticket, $config);
557}
558
37d45deb 559sub check_user_exist {
7070c1ae 560 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 561
5bb4e06a 562 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 563 return undef if !$username;
66931b11 564
37d45deb
DM
565 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
566
567 die "no such user ('$username')\n" if !$noerr;
66931b11 568
37d45deb
DM
569 return undef;
570}
571
572sub check_user_enabled {
573 my ($usercfg, $username, $noerr) = @_;
574
575 my $data = check_user_exist($usercfg, $username, $noerr);
576 return undef if !$data;
577
578 return 1 if $data->{enable};
2c3a6c0a 579
37d45deb 580 die "user '$username' is disabled\n" if !$noerr;
66931b11 581
8a724f7b
DM
582 my $ctime = time();
583 my $expire = $usercfg->{users}->{$username}->{expire};
584
585 die "account expired\n" if $expire && ($expire < $ctime);
586
7070c1ae 587 return undef;
2c3a6c0a
DM
588}
589
571e9d06
FG
590sub check_token_exist {
591 my ($usercfg, $username, $tokenid, $noerr) = @_;
592
593 my $user = check_user_exist($usercfg, $username, $noerr);
594 return undef if !$user;
595
596 return $user->{tokens}->{$tokenid}
597 if defined($user->{tokens}) && $user->{tokens}->{$tokenid};
598
599 die "no such token '$tokenid' for user '$username'\n" if !$noerr;
600
601 return undef;
602}
603
96f8ebd6 604sub verify_one_time_pw {
fda8ca85 605 my ($type, $username, $keys, $tfa_cfg, $otp) = @_;
96f8ebd6 606
1075c589 607 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
96f8ebd6
DM
608
609 # fixme: proxy support?
610 my $proxy;
611
612 if ($type eq 'yubico') {
972859d1
DM
613 PVE::OTP::yubico_verify_otp($otp, $keys, $tfa_cfg->{url},
614 $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
1abc2c0a 615 } elsif ($type eq 'oath') {
972859d1 616 PVE::OTP::oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
96f8ebd6
DM
617 } else {
618 die "unknown tfa type '$type'\n";
619 }
96f8ebd6
DM
620}
621
2c3a6c0a 622# password should be utf8 encoded
1075c589 623# Note: some plugins delay/sleep if auth fails
2c3a6c0a 624sub authenticate_user {
96f8ebd6 625 my ($username, $password, $otp) = @_;
2c3a6c0a
DM
626
627 die "no username specified\n" if !$username;
66931b11 628
5bb4e06a 629 my ($ruid, $realm);
2c3a6c0a 630
5bb4e06a 631 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
2c3a6c0a
DM
632
633 my $usercfg = cfs_read_file('user.cfg');
634
6126ab75 635 check_user_enabled($usercfg, $username);
2c3a6c0a 636
5bb4e06a 637 my $domain_cfg = cfs_read_file('domains.cfg');
2c3a6c0a 638
6126ab75 639 my $cfg = $domain_cfg->{ids}->{$realm};
3443faca 640 die "auth domain '$realm' does not exist\n" if !$cfg;
6126ab75
DM
641 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
642 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
2c3a6c0a 643
fda8ca85
WB
644 my ($type, $tfa_data) = user_get_tfa($username, $realm);
645 if ($type) {
646 if ($type eq 'u2f') {
647 # Note that if the user did not manage to complete the initial u2f registration
648 # challenge we have a hash containing a 'challenge' entry in the user's tfa.cfg entry:
f25628d3
WB
649 $tfa_data = undef if exists $tfa_data->{challenge};
650 } elsif (!defined($otp)) {
651 # The user requires a 2nd factor but has not provided one. Return success but
652 # don't clear $tfa_data.
fda8ca85
WB
653 } else {
654 my $keys = $tfa_data->{keys};
655 my $tfa_cfg = $tfa_data->{config};
656 verify_one_time_pw($type, $username, $keys, $tfa_cfg, $otp);
f25628d3
WB
657 $tfa_data = undef;
658 }
659
660 # Return the type along with the rest:
661 if ($tfa_data) {
662 $tfa_data = {
663 type => $type,
664 data => $tfa_data,
665 };
fda8ca85 666 }
96f8ebd6
DM
667 }
668
f25628d3 669 return wantarray ? ($username, $tfa_data) : $username;
2c3a6c0a
DM
670}
671
672sub domain_set_password {
5bb4e06a 673 my ($realm, $username, $password) = @_;
2c3a6c0a
DM
674
675 die "no auth domain specified" if !$realm;
676
5bb4e06a
DM
677 my $domain_cfg = cfs_read_file('domains.cfg');
678
679 my $cfg = $domain_cfg->{ids}->{$realm};
1075c589 680 die "auth domain '$realm' does not exist\n" if !$cfg;
5bb4e06a
DM
681 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
682 $plugin->store_password($cfg, $realm, $username, $password);
2c3a6c0a
DM
683}
684
685sub add_user_group {
2c3a6c0a 686 my ($username, $usercfg, $group) = @_;
66931b11 687
2c3a6c0a
DM
688 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
689 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
690}
691
692sub delete_user_group {
2c3a6c0a 693 my ($username, $usercfg) = @_;
66931b11 694
2c3a6c0a
DM
695 foreach my $group (keys %{$usercfg->{groups}}) {
696
66931b11 697 delete ($usercfg->{groups}->{$group}->{users}->{$username})
2c3a6c0a
DM
698 if $usercfg->{groups}->{$group}->{users}->{$username};
699 }
700}
701
702sub delete_user_acl {
2c3a6c0a
DM
703 my ($username, $usercfg) = @_;
704
705 foreach my $acl (keys %{$usercfg->{acl}}) {
706
66931b11 707 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
2c3a6c0a
DM
708 if $usercfg->{acl}->{$acl}->{users}->{$username};
709 }
2c3a6c0a 710}
39c85db8 711
2c3a6c0a 712sub delete_group_acl {
2c3a6c0a
DM
713 my ($group, $usercfg) = @_;
714
715 foreach my $acl (keys %{$usercfg->{acl}}) {
716
66931b11 717 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
2c3a6c0a
DM
718 if $usercfg->{acl}->{$acl}->{groups}->{$group};
719 }
39c85db8
DM
720}
721
722sub delete_pool_acl {
39c85db8 723 my ($pool, $usercfg) = @_;
2c3a6c0a 724
39c85db8
DM
725 my $path = "/pool/$pool";
726
3b4a3f94 727 delete ($usercfg->{acl}->{$path})
2c3a6c0a
DM
728}
729
730# we automatically create some predefined roles by splitting privs
731# into 3 groups (per category)
732# root: only root is allowed to do that
733# admin: an administrator can to that
1075c589 734# user: a normal user/customer can to that
2c3a6c0a
DM
735my $privgroups = {
736 VM => {
737 root => [],
66931b11
DM
738 admin => [
739 'VM.Config.Disk',
740 'VM.Config.CPU',
741 'VM.Config.Memory',
742 'VM.Config.Network',
c0fead8c 743 'VM.Config.HWType',
66931b11
DM
744 'VM.Config.Options', # covers all other things
745 'VM.Allocate',
746 'VM.Clone',
2c3a6c0a 747 'VM.Migrate',
66931b11
DM
748 'VM.Monitor',
749 'VM.Snapshot',
aad513f6 750 'VM.Snapshot.Rollback',
2c3a6c0a
DM
751 ],
752 user => [
cc7bdf33 753 'VM.Config.CDROM', # change CDROM media
cb381abc 754 'VM.Config.Cloudinit',
66931b11 755 'VM.Console',
68d5a86d 756 'VM.Backup',
2c3a6c0a
DM
757 'VM.PowerMgmt',
758 ],
66931b11 759 audit => [
82b63965 760 'VM.Audit',
2c3a6c0a
DM
761 ],
762 },
763 Sys => {
764 root => [
66931b11 765 'Sys.PowerMgmt',
37d45deb 766 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
767 ],
768 admin => [
2e376c58 769 'Permissions.Modify',
66931b11 770 'Sys.Console',
2c3a6c0a
DM
771 'Sys.Syslog',
772 ],
773 user => [],
774 audit => [
775 'Sys.Audit',
776 ],
777 },
778 Datastore => {
2e376c58 779 root => [],
19f60b5e
DM
780 admin => [
781 'Datastore.Allocate',
373cb383 782 'Datastore.AllocateTemplate',
19f60b5e 783 ],
2c3a6c0a
DM
784 user => [
785 'Datastore.AllocateSpace',
786 ],
787 audit => [
788 'Datastore.Audit',
789 ],
790 },
40672671
AD
791 SDN => {
792 root => [],
793 admin => [
794 'SDN.Allocate',
795 'SDN.Audit',
796 ],
797 audit => [
798 'SDN.Audit',
799 ],
800 },
12683df7 801 User => {
82b63965
DM
802 root => [
803 'Realm.Allocate',
804 ],
12683df7
DM
805 admin => [
806 'User.Modify',
82b63965 807 'Group.Allocate', # edit/change group settings
66931b11 808 'Realm.AllocateUser',
19f60b5e 809 ],
12683df7
DM
810 user => [],
811 audit => [],
812 },
dee1c882
DM
813 Pool => {
814 root => [],
815 admin => [
816 'Pool.Allocate', # create/delete pools
817 ],
6d048ad6
LS
818 user => [
819 'Pool.Audit',
820 ],
821 audit => [
822 'Pool.Audit',
823 ],
dee1c882 824 },
2c3a6c0a
DM
825};
826
827my $valid_privs = {};
828
829my $special_roles = {
1075c589
FG
830 'NoAccess' => {}, # no privileges
831 'Administrator' => $valid_privs, # all privileges
2c3a6c0a
DM
832};
833
834sub create_roles {
835
836 foreach my $cat (keys %$privgroups) {
837 my $cd = $privgroups->{$cat};
66931b11 838 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
2c3a6c0a
DM
839 @{$cd->{user}}, @{$cd->{audit}}) {
840 $valid_privs->{$p} = 1;
841 }
842 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
843
844 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
845 $special_roles->{"PVEAdmin"}->{$p} = 1;
846 }
847 if (scalar(@{$cd->{user}})) {
848 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
849 $special_roles->{"PVE${cat}User"}->{$p} = 1;
850 }
851 }
852 foreach my $p (@{$cd->{audit}}) {
853 $special_roles->{"PVEAuditor"}->{$p} = 1;
854 }
855 }
ff4b2235 856
7b395f99 857 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
858};
859
860create_roles();
861
0fea3f16
DC
862sub create_priv_properties {
863 my $properties = {};
864 foreach my $priv (keys %$valid_privs) {
865 $properties->{$priv} = {
866 type => 'boolean',
867 optional => 1,
868 };
869 }
870 return $properties;
871}
872
894e6f0c
PA
873sub role_is_special {
874 my ($role) = @_;
b7ba86d4 875 return (exists $special_roles->{$role}) ? 1 : 0;
894e6f0c
PA
876}
877
2c3a6c0a
DM
878sub add_role_privs {
879 my ($role, $usercfg, $privs) = @_;
880
881 return if !$privs;
882
883 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
884
885 foreach my $priv (split_list($privs)) {
886 if (defined ($valid_privs->{$priv})) {
887 $usercfg->{roles}->{$role}->{$priv} = 1;
888 } else {
1075c589 889 die "invalid privilege '$priv'\n";
66931b11
DM
890 }
891 }
2c3a6c0a
DM
892}
893
eb41d200 894sub lookup_username {
f335d265 895 my ($username, $noerr) = @_;
eb41d200
WL
896
897 $username =~ m!^(${PVE::Auth::Plugin::user_regex})\@(${PVE::Auth::Plugin::realm_regex})$!;
898
899 my $realm = $2;
900 my $domain_cfg = cfs_read_file("domains.cfg");
901 my $casesensitive = $domain_cfg->{ids}->{$realm}->{'case-sensitive'} // 1;
902 my $usercfg = cfs_read_file('user.cfg');
903
904 if (!$casesensitive) {
905 my @matches = grep { lc $username eq lc $_ } (keys %{$usercfg->{users}});
906
907 die "ambiguous case insensitive match of username '$username', cannot safely grant access!\n"
f335d265 908 if scalar @matches > 1 && !$noerr;
eb41d200
WL
909
910 return $matches[0]
911 }
912
913 return $username;
914}
915
2c3a6c0a
DM
916sub normalize_path {
917 my $path = shift;
918
4bc17477 919 $path =~ s|/+|/|g;
2c3a6c0a
DM
920
921 $path =~ s|/$||;
922
923 $path = '/' if !$path;
924
4bc17477
DM
925 $path = "/$path" if $path !~ m|^/|;
926
e4f8fc2e 927 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
2c3a6c0a
DM
928
929 return $path;
66931b11 930}
2c3a6c0a 931
20c60513 932sub check_path {
91c30089
TL
933 my ($path) = @_;
934 return $path =~ m!^(
20c60513
LS
935 /
936 |/access
937 |/access/groups
8737ff37 938 |/access/groups/[[:alnum:]\.\-\_]+
20c60513 939 |/access/realm
8737ff37 940 |/access/realm/[[:alnum:]\.\-\_]+
20c60513
LS
941 |/nodes
942 |/nodes/[[:alnum:]\.\-\_]+
943 |/pool
944 |/pool/[[:alnum:]\.\-\_]+
945 |/sdn
0a06acb1 946 |/sdn/zones/[[:alnum:]\.\-\_]+
20c60513
LS
947 |/storage
948 |/storage/[[:alnum:]\.\-\_]+
949 |/vms
ad1ef9fc 950 |/vms/[1-9][0-9]{2,}
20c60513
LS
951 )$!xs;
952}
953
2c3a6c0a
DM
954PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
955sub verify_groupname {
956 my ($groupname, $noerr) = @_;
957
958 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
959
960 die "group name '$groupname' contains invalid characters\n" if !$noerr;
961
962 return undef;
963 }
66931b11 964
2c3a6c0a
DM
965 return $groupname;
966}
967
968PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
969sub verify_rolename {
970 my ($rolename, $noerr) = @_;
971
972 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
973
974 die "role name '$rolename' contains invalid characters\n" if !$noerr;
975
976 return undef;
977 }
66931b11 978
2c3a6c0a
DM
979 return $rolename;
980}
981
16e50b59 982PVE::JSONSchema::register_format('pve-poolid', \&verify_poolname);
39c85db8
DM
983sub verify_poolname {
984 my ($poolname, $noerr) = @_;
985
986 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
987
988 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
989
990 return undef;
991 }
66931b11 992
39c85db8
DM
993 return $poolname;
994}
995
2c3a6c0a
DM
996PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
997sub verify_privname {
998 my ($priv, $noerr) = @_;
999
1000 if (!$valid_privs->{$priv}) {
1075c589 1001 die "invalid privilege '$priv'\n" if !$noerr;
2c3a6c0a
DM
1002
1003 return undef;
1004 }
66931b11 1005
2c3a6c0a
DM
1006 return $priv;
1007}
1008
1009sub userconfig_force_defaults {
1010 my ($cfg) = @_;
1011
1012 foreach my $r (keys %$special_roles) {
1013 $cfg->{roles}->{$r} = $special_roles->{$r};
1014 }
1015
7279f31c
WL
1016 # add root user if not exists
1017 if (!$cfg->{users}->{'root@pam'}) {
66931b11 1018 $cfg->{users}->{'root@pam'}->{enable} = 1;
7279f31c 1019 }
2c3a6c0a
DM
1020}
1021
1022sub parse_user_config {
1023 my ($filename, $raw) = @_;
1024
1025 my $cfg = {};
1026
1027 userconfig_force_defaults($cfg);
1028
d6eb6621 1029 $raw = '' if !defined($raw);
62af314a 1030 while ($raw =~ /^\s*(.+?)\s*$/gm) {
2c3a6c0a 1031 my $line = $1;
2c3a6c0a
DM
1032 my @data;
1033
1034 foreach my $d (split (/:/, $line)) {
66931b11 1035 $d =~ s/^\s+//;
2c3a6c0a
DM
1036 $d =~ s/\s+$//;
1037 push @data, $d
1038 }
1039
1040 my $et = shift @data;
1041
1042 if ($et eq 'user') {
96f8ebd6 1043 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
2c3a6c0a 1044
5bb4e06a 1045 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
1046 if (!$realm) {
1047 warn "user config - ignore user '$user' - invalid user name\n";
1048 next;
1049 }
1050
1051 $enable = $enable ? 1 : 0;
1052
1053 $expire = 0 if !$expire;
1054
1055 if ($expire !~ m/^\d+$/) {
1056 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
1057 next;
1058 }
1059 $expire = int($expire);
1060
1061 #if (!verify_groupname ($group, 1)) {
1062 # warn "user config - ignore user '$user' - invalid characters in group name\n";
1063 # next;
1064 #}
1065
1066 $cfg->{users}->{$user} = {
1067 enable => $enable,
1068 # group => $group,
1069 };
1070 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
1071 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
1072 $cfg->{users}->{$user}->{email} = $email;
1073 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1074 $cfg->{users}->{$user}->{expire} = $expire;
1abc2c0a 1075 # keys: allowed yubico key ids or oath secrets (base32 encoded)
66931b11 1076 $cfg->{users}->{$user}->{keys} = $keys if $keys;
2c3a6c0a
DM
1077
1078 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
1079 #$cfg->{groups}->{$group}->{$user} = 1;
1080
1081 } elsif ($et eq 'group') {
1082 my ($group, $userlist, $comment) = @data;
1083
1084 if (!verify_groupname($group, 1)) {
1085 warn "user config - ignore group '$group' - invalid characters in group name\n";
1086 next;
1087 }
1088
1089 # make sure to add the group (even if there are no members)
1090 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
1091
1092 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
1093
1094 foreach my $user (split_list($userlist)) {
1095
5bb4e06a 1096 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
2c3a6c0a
DM
1097 warn "user config - ignore invalid group member '$user'\n";
1098 next;
1099 }
1100
66931b11 1101 if ($cfg->{users}->{$user}) { # user exists
2c3a6c0a 1102 $cfg->{users}->{$user}->{groups}->{$group} = 1;
2c3a6c0a
DM
1103 } else {
1104 warn "user config - ignore invalid group member '$user'\n";
1105 }
5654260e 1106 $cfg->{groups}->{$group}->{users}->{$user} = 1;
2c3a6c0a
DM
1107 }
1108
1109 } elsif ($et eq 'role') {
1110 my ($role, $privlist) = @data;
66931b11 1111
2c3a6c0a
DM
1112 if (!verify_rolename($role, 1)) {
1113 warn "user config - ignore role '$role' - invalid characters in role name\n";
1114 next;
1115 }
1116
1117 # make sure to add the role (even if there are no privileges)
1118 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
1119
1120 foreach my $priv (split_list($privlist)) {
1121 if (defined ($valid_privs->{$priv})) {
1122 $cfg->{roles}->{$role}->{$priv} = 1;
1123 } else {
1516bfa0 1124 warn "user config - ignore invalid privilege '$priv'\n";
66931b11 1125 }
2c3a6c0a 1126 }
66931b11 1127
2c3a6c0a
DM
1128 } elsif ($et eq 'acl') {
1129 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
1130
733371da
FG
1131 $propagate = $propagate ? 1 : 0;
1132
2c3a6c0a
DM
1133 if (my $path = normalize_path($pathtxt)) {
1134 foreach my $role (split_list($rolelist)) {
66931b11 1135
2c3a6c0a
DM
1136 if (!verify_rolename($role, 1)) {
1137 warn "user config - ignore invalid role name '$role' in acl\n";
1138 next;
1139 }
1140
21f523a5
FG
1141 if (!$cfg->{roles}->{$role}) {
1142 warn "user config - ignore invalid acl role '$role'\n";
1143 next;
1144 }
1145
2c3a6c0a 1146 foreach my $ug (split_list($uglist)) {
508e11f1
FG
1147 my ($group) = $ug =~ m/^@(\S+)$/;
1148
1149 if ($group && verify_groupname($group, 1)) {
5654260e 1150 if (!$cfg->{groups}->{$group}) { # group does not exist
2c3a6c0a
DM
1151 warn "user config - ignore invalid acl group '$group'\n";
1152 }
5654260e 1153 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
5bb4e06a 1154 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
5654260e 1155 if (!$cfg->{users}->{$ug}) { # user does not exist
2c3a6c0a
DM
1156 warn "user config - ignore invalid acl member '$ug'\n";
1157 }
5654260e 1158 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
28e3dc05 1159 } elsif (my ($user, $token) = split_tokenid($ug, 1)) {
571e9d06 1160 if (check_token_exist($cfg, $user, $token, 1)) {
28e3dc05
FG
1161 $cfg->{acl}->{$path}->{tokens}->{$ug}->{$role} = $propagate;
1162 } else {
1163 warn "user config - ignore invalid acl token '$ug'\n";
1164 }
2c3a6c0a
DM
1165 } else {
1166 warn "user config - invalid user/group '$ug' in acl\n";
1167 }
1168 }
1169 }
1170 } else {
1171 warn "user config - ignore invalid path in acl '$pathtxt'\n";
1172 }
4bc17477 1173 } elsif ($et eq 'pool') {
39c85db8 1174 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 1175
39c85db8
DM
1176 if (!verify_poolname($pool, 1)) {
1177 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
1178 next;
1179 }
4bc17477 1180
39c85db8
DM
1181 # make sure to add the pool (even if there are no members)
1182 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 1183
39c85db8 1184 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 1185
39c85db8
DM
1186 foreach my $vmid (split_list($vmlist)) {
1187 if ($vmid !~ m/^\d+$/) {
1188 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
1189 next;
4bc17477 1190 }
39c85db8 1191 $vmid = int($vmid);
4bc17477 1192
39c85db8
DM
1193 if ($cfg->{vms}->{$vmid}) {
1194 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
1195 next;
4bc17477
DM
1196 }
1197
39c85db8 1198 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
66931b11 1199
39c85db8
DM
1200 # record vmid ==> pool relation
1201 $cfg->{vms}->{$vmid} = $pool;
1202 }
1203
1204 foreach my $storeid (split_list($storelist)) {
1205 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1206 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1207 next;
1208 }
1209 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
4bc17477 1210 }
28e3dc05
FG
1211 } elsif ($et eq 'token') {
1212 my ($tokenid, $expire, $privsep, $comment) = @data;
1213
1214 my ($user, $token) = split_tokenid($tokenid, 1);
1215 if (!($user && $token)) {
1216 warn "user config - ignore invalid tokenid '$tokenid'\n";
1217 next;
1218 }
1219
1220 $privsep = $privsep ? 1 : 0;
1221
1222 $expire = 0 if !$expire;
1223
1224 if ($expire !~ m/^\d+$/) {
1225 warn "user config - ignore token '$tokenid' - (illegal characters in expire '$expire')\n";
1226 next;
1227 }
1228 $expire = int($expire);
1229
1230 if (my $user_cfg = $cfg->{users}->{$user}) { # user exists
1231 $user_cfg->{tokens}->{$token} = {} if !$user_cfg->{tokens}->{$token};
1232 my $token_cfg = $user_cfg->{tokens}->{$token};
1233 $token_cfg->{privsep} = $privsep;
1234 $token_cfg->{expire} = $expire;
1235 $token_cfg->{comment} = PVE::Tools::decode_text($comment) if $comment;
1236 } else {
1237 warn "user config - ignore token '$tokenid' - user does not exist\n";
1238 }
2c3a6c0a
DM
1239 } else {
1240 warn "user config - ignore config line: $line\n";
1241 }
1242 }
1243
1244 userconfig_force_defaults($cfg);
1245
1246 return $cfg;
1247}
1248
2c3a6c0a
DM
1249sub write_user_config {
1250 my ($filename, $cfg) = @_;
1251
1252 my $data = '';
1253
93c7e9c3 1254 foreach my $user (sort keys %{$cfg->{users}}) {
2c3a6c0a
DM
1255 my $d = $cfg->{users}->{$user};
1256 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1257 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1258 my $email = $d->{email} || '';
1259 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 1260 my $expire = int($d->{expire} || 0);
2c3a6c0a 1261 my $enable = $d->{enable} ? 1 : 0;
96f8ebd6
DM
1262 my $keys = $d->{keys} ? $d->{keys} : '';
1263 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
28e3dc05
FG
1264
1265 my $user_tokens = $d->{tokens};
1266 foreach my $token (sort keys %$user_tokens) {
1267 my $td = $user_tokens->{$token};
1268 my $full_tokenid = join_tokenid($user, $token);
1269 my $comment = $td->{comment} ? PVE::Tools::encode_text($td->{comment}) : '';
1270 my $expire = int($td->{expire} || 0);
1271 my $privsep = $td->{privsep} ? 1 : 0;
1272 $data .= "token:$full_tokenid:$expire:$privsep:$comment:\n";
1273 }
2c3a6c0a
DM
1274 }
1275
1276 $data .= "\n";
1277
93c7e9c3 1278 foreach my $group (sort keys %{$cfg->{groups}}) {
2c3a6c0a 1279 my $d = $cfg->{groups}->{$group};
a5ec58ea 1280 my $list = join (',', sort keys %{$d->{users}});
66931b11 1281 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
2c3a6c0a
DM
1282 $data .= "group:$group:$list:$comment:\n";
1283 }
1284
1285 $data .= "\n";
1286
93c7e9c3 1287 foreach my $pool (sort keys %{$cfg->{pools}}) {
39c85db8 1288 my $d = $cfg->{pools}->{$pool};
a5ec58ea
FG
1289 my $vmlist = join (',', sort keys %{$d->{vms}});
1290 my $storelist = join (',', sort keys %{$d->{storage}});
66931b11 1291 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 1292 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
1293 }
1294
1295 $data .= "\n";
1296
93c7e9c3 1297 foreach my $role (sort keys %{$cfg->{roles}}) {
2c3a6c0a
DM
1298 next if $special_roles->{$role};
1299
1300 my $d = $cfg->{roles}->{$role};
a5ec58ea 1301 my $list = join (',', sort keys %$d);
2c3a6c0a
DM
1302 $data .= "role:$role:$list:\n";
1303 }
1304
1305 $data .= "\n";
1306
9a12a08c
FG
1307 my $collect_rolelist_members = sub {
1308 my ($acl_members, $result, $prefix, $exclude) = @_;
2c3a6c0a 1309
9a12a08c
FG
1310 foreach my $member (keys %$acl_members) {
1311 next if $exclude && $member eq $exclude;
2c3a6c0a 1312
2c3a6c0a
DM
1313 my $l0 = '';
1314 my $l1 = '';
9a12a08c
FG
1315 foreach my $role (sort keys %{$acl_members->{$member}}) {
1316 my $propagate = $acl_members->{$member}->{$role};
2c3a6c0a
DM
1317 if ($propagate) {
1318 $l1 .= ',' if $l1;
1319 $l1 .= $role;
1320 } else {
1321 $l0 .= ',' if $l0;
1322 $l0 .= $role;
1323 }
1324 }
9a12a08c
FG
1325 $result->{0}->{$l0}->{"${prefix}${member}"} = 1 if $l0;
1326 $result->{1}->{$l1}->{"${prefix}${member}"} = 1 if $l1;
2c3a6c0a 1327 }
9a12a08c 1328 };
2c3a6c0a 1329
9a12a08c
FG
1330 foreach my $path (sort keys %{$cfg->{acl}}) {
1331 my $d = $cfg->{acl}->{$path};
2c3a6c0a 1332
9a12a08c 1333 my $rolelist_members = {};
2c3a6c0a 1334
9a12a08c
FG
1335 $collect_rolelist_members->($d->{'groups'}, $rolelist_members, '@');
1336
1337 # no need to save 'root@pam', it is always 'Administrator'
1338 $collect_rolelist_members->($d->{'users'}, $rolelist_members, '', 'root@pam');
1339
28e3dc05
FG
1340 $collect_rolelist_members->($d->{'tokens'}, $rolelist_members, '');
1341
9a12a08c
FG
1342 foreach my $propagate (0,1) {
1343 my $filtered = $rolelist_members->{$propagate};
1344 foreach my $rolelist (sort keys %$filtered) {
1345 my $uglist = join (',', sort keys %{$filtered->{$rolelist}});
1346 $data .= "acl:$propagate:$path:$uglist:$rolelist:\n";
1347 }
28e3dc05 1348
2c3a6c0a
DM
1349 }
1350 }
1351
1352 return $data;
1353}
1354
fda8ca85
WB
1355# The TFA configuration in priv/tfa.cfg format contains one line per user of
1356# the form:
1357# USER:TYPE:DATA
1358# DATA is a base64 encoded json string and its format depends on the type.
1359sub parse_priv_tfa_config {
1360 my ($filename, $raw) = @_;
1361
1362 my $users = {};
1363 my $cfg = { users => $users };
1364
1365 $raw = '' if !defined($raw);
1366 while ($raw =~ /^\s*(.+?)\s*$/gm) {
1367 my $line = $1;
1368 my ($user, $type, $data) = split(/:/, $line, 3);
1369
1370 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
1371 if (!$realm) {
1372 warn "user tfa config - ignore user '$user' - invalid user name\n";
1373 next;
1374 }
1375
1376 $data = decode_json(decode_base64($data));
1377
1378 $users->{$user} = {
1379 type => $type,
1380 data => $data,
1381 };
1382 }
1383
1384 return $cfg;
1385}
1386
1387sub write_priv_tfa_config {
1388 my ($filename, $cfg) = @_;
1389
1390 my $output = '';
1391
1392 my $users = $cfg->{users};
1393 foreach my $user (sort keys %$users) {
1394 my $info = $users->{$user};
1395 next if !%$info; # skip empty entries
1396
1397 $info = {%$info}; # copy to verify contents:
1398
1399 my $type = delete $info->{type};
1400 my $data = delete $info->{data};
1401
1402 if (my @keys = keys %$info) {
1403 die "invalid keys in TFA config for user $user: " . join(', ', @keys) . "\n";
1404 }
1405
1406 $data = encode_base64(encode_json($data), '');
1407 $output .= "${user}:${type}:${data}\n";
1408 }
1409
1410 return $output;
1411}
1412
2c3a6c0a
DM
1413sub roles {
1414 my ($cfg, $user, $path) = @_;
1415
66931b11 1416 # NOTE: we do not consider pools here.
e915e9e4
FG
1417 # NOTE: for privsep tokens, this does not filter roles by those that the
1418 # corresponding user has.
a31f1d85 1419 # Use $rpcenv->permission() for any actual permission checks!
4bc17477 1420
2c3a6c0a
DM
1421 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1422
e915e9e4
FG
1423 if (pve_verify_tokenid($user, 1)) {
1424 my $tokenid = $user;
1425 my ($username, $token) = split_tokenid($tokenid);
1426
1427 my $token_info = $cfg->{users}->{$username}->{tokens}->{$token};
1428 return () if !$token_info;
1429
7e8bcaa7 1430 my $user_roles = roles($cfg, $username, $path);
e915e9e4
FG
1431
1432 # return full user privileges
7e8bcaa7 1433 return $user_roles if !$token_info->{privsep};
e915e9e4
FG
1434 }
1435
7e8bcaa7 1436 my $roles = {};
2c3a6c0a
DM
1437
1438 foreach my $p (sort keys %{$cfg->{acl}}) {
1439 my $final = ($path eq $p);
1440
1441 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1442
1443 my $acl = $cfg->{acl}->{$p};
1444
1445 #print "CHECKACL $path $p\n";
1446 #print "ACL $path = " . Dumper ($acl);
e915e9e4
FG
1447 if (my $ri = $acl->{tokens}->{$user}) {
1448 my $new;
1449 foreach my $role (keys %$ri) {
1450 my $propagate = $ri->{$role};
1451 if ($final || $propagate) {
1452 #print "APPLY ROLE $p $user $role\n";
1453 $new = {} if !$new;
7e8bcaa7 1454 $new->{$role} = $propagate;
e915e9e4
FG
1455 }
1456 }
1457 if ($new) {
7e8bcaa7 1458 $roles = $new; # overwrite previous settings
e915e9e4
FG
1459 next;
1460 }
1461 }
2c3a6c0a
DM
1462
1463 if (my $ri = $acl->{users}->{$user}) {
1464 my $new;
1465 foreach my $role (keys %$ri) {
1466 my $propagate = $ri->{$role};
1467 if ($final || $propagate) {
1468 #print "APPLY ROLE $p $user $role\n";
1469 $new = {} if !$new;
7e8bcaa7 1470 $new->{$role} = $propagate;
2c3a6c0a
DM
1471 }
1472 }
1473 if ($new) {
7e8bcaa7 1474 $roles = $new; # overwrite previous settings
2c3a6c0a
DM
1475 next; # user privs always override group privs
1476 }
1477 }
1478
1479 my $new;
1480 foreach my $g (keys %{$acl->{groups}}) {
1481 next if !$cfg->{groups}->{$g}->{users}->{$user};
1482 if (my $ri = $acl->{groups}->{$g}) {
1483 foreach my $role (keys %$ri) {
1484 my $propagate = $ri->{$role};
1485 if ($final || $propagate) {
1486 #print "APPLY ROLE $p \@$g $role\n";
1487 $new = {} if !$new;
7e8bcaa7 1488 $new->{$role} = $propagate;
2c3a6c0a
DM
1489 }
1490 }
1491 }
1492 }
1493 if ($new) {
7e8bcaa7 1494 $roles = $new; # overwrite previous settings
2c3a6c0a
DM
1495 next;
1496 }
2c3a6c0a
DM
1497 }
1498
7e8bcaa7
FG
1499 return { 'NoAccess' => $roles->{NoAccess} } if defined ($roles->{NoAccess});
1500 #return () if defined ($roles->{NoAccess});
66931b11 1501
7e8bcaa7 1502 #print "permission $user $path = " . Dumper ($roles);
2c3a6c0a
DM
1503
1504 #print "roles $user $path = " . join (',', @ra) . "\n";
1505
7e8bcaa7 1506 return $roles;
2c3a6c0a 1507}
66931b11 1508
3b4a3f94
AG
1509sub remove_vm_access {
1510 my ($vmid) = @_;
1511 my $delVMaccessFn = sub {
1512 my $usercfg = cfs_read_file("user.cfg");
57a70473 1513 my $modified;
3b4a3f94 1514
57a70473
DM
1515 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1516 delete $usercfg->{acl}->{"/vms/$vmid"};
1517 $modified = 1;
3b4a3f94
AG
1518 }
1519 if (my $pool = $usercfg->{vms}->{$vmid}) {
1520 if (my $data = $usercfg->{pools}->{$pool}) {
1521 delete $data->{vms}->{$vmid};
1522 delete $usercfg->{vms}->{$vmid};
57a70473 1523 $modified = 1;
3b4a3f94
AG
1524 }
1525 }
57a70473 1526 cfs_write_file("user.cfg", $usercfg) if $modified;
3b4a3f94
AG
1527 };
1528
1529 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1530}
1531
60844761
AG
1532sub remove_storage_access {
1533 my ($storeid) = @_;
1534
1535 my $deleteStorageAccessFn = sub {
1536 my $usercfg = cfs_read_file("user.cfg");
1537 my $modified;
1538
1539 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1540 delete $usercfg->{acl}->{"/storage/$storeid"};
1541 $modified = 1;
1542 }
1543 foreach my $pool (keys %{$usercfg->{pools}}) {
1544 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1545 $modified = 1;
1546 }
1547 cfs_write_file("user.cfg", $usercfg) if $modified;
1548 };
1549
1550 lock_user_config($deleteStorageAccessFn,
1551 "access permissions cleanup for storage $storeid failed");
1552}
1553
018ae3a9
DM
1554sub add_vm_to_pool {
1555 my ($vmid, $pool) = @_;
1556
1557 my $addVMtoPoolFn = sub {
1558 my $usercfg = cfs_read_file("user.cfg");
1559 if (my $data = $usercfg->{pools}->{$pool}) {
1560 $data->{vms}->{$vmid} = 1;
1561 $usercfg->{vms}->{$vmid} = $pool;
1562 cfs_write_file("user.cfg", $usercfg);
1563 }
1564 };
1565
1566 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1567}
1568
1569sub remove_vm_from_pool {
1570 my ($vmid) = @_;
66931b11 1571
018ae3a9
DM
1572 my $delVMfromPoolFn = sub {
1573 my $usercfg = cfs_read_file("user.cfg");
1574 if (my $pool = $usercfg->{vms}->{$vmid}) {
1575 if (my $data = $usercfg->{pools}->{$pool}) {
1576 delete $data->{vms}->{$vmid};
1577 delete $usercfg->{vms}->{$vmid};
1578 cfs_write_file("user.cfg", $usercfg);
1579 }
1580 }
1581 };
1582
1583 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1584}
1585
49b15310 1586my $USER_CONTROLLED_TFA_TYPES = {
fda8ca85
WB
1587 u2f => 1,
1588 oath => 1,
1589};
1590
1591# Delete an entry by setting $data=undef in which case $type is ignored.
1592# Otherwise both must be valid.
1593sub user_set_tfa {
1594 my ($userid, $realm, $type, $data, $cached_usercfg, $cached_domaincfg) = @_;
1595
1596 if (defined($data) && !defined($type)) {
1597 # This is an internal usage error and should not happen
1598 die "cannot set tfa data without a type\n";
1599 }
1600
1601 my $user_cfg = $cached_usercfg || cfs_read_file('user.cfg');
1602 my $user = $user_cfg->{users}->{$userid}
1603 or die "user '$userid' not found\n";
1604
1605 my $domain_cfg = $cached_domaincfg || cfs_read_file('domains.cfg');
1606 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1607 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1608
1609 my $realm_tfa = $realm_cfg->{tfa};
1610 if (defined($realm_tfa)) {
1611 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa);
1612 # If the realm has a TFA setting, we're only allowed to use that.
1613 if (defined($data)) {
1614 my $required_type = $realm_tfa->{type};
1615 if ($required_type ne $type) {
1616 die "realm '$realm' only allows TFA of type '$required_type\n";
1617 }
1618
1619 if (defined($data->{config})) {
1620 # XXX: Is it enough if the type matches? Or should the configuration also match?
1621 }
1622
1623 # realm-configured tfa always uses a simple key list, so use the user.cfg
1624 $user->{keys} = $data->{keys};
1625 } else {
1626 die "realm '$realm' does not allow removing the 2nd factor\n";
1627 }
1628 } else {
1629 # Without a realm-enforced TFA setting the user can add a u2f or totp entry by themselves.
1630 # The 'yubico' type requires yubico server settings, which have to be configured on the
1631 # realm, so this is not supported here:
1632 die "domain '$realm' does not support TFA type '$type'\n"
49b15310 1633 if defined($data) && !$USER_CONTROLLED_TFA_TYPES->{$type};
fda8ca85
WB
1634 }
1635
1636 # Custom TFA entries are stored in priv/tfa.cfg as they can be more complet: u2f uses a
1637 # public key and a key handle, TOTP requires the usual totp settings...
1638
1639 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1640 my $tfa = ($tfa_cfg->{users}->{$userid} //= {});
1641
1642 if (defined($data)) {
1643 $tfa->{type} = $type;
1644 $tfa->{data} = $data;
1645 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1646
7e58c66d 1647 $user->{keys} = "x!$type";
fda8ca85
WB
1648 } else {
1649 delete $tfa_cfg->{users}->{$userid};
1650 cfs_write_file('priv/tfa.cfg', $tfa_cfg);
1651
1652 delete $user->{keys};
1653 }
1654
1655 cfs_write_file('user.cfg', $user_cfg);
1656}
1657
1658sub user_get_tfa {
1659 my ($username, $realm) = @_;
1660
1661 my $user_cfg = cfs_read_file('user.cfg');
1662 my $user = $user_cfg->{users}->{$username}
1663 or die "user '$username' not found\n";
1664
1665 my $keys = $user->{keys};
fda8ca85
WB
1666
1667 my $domain_cfg = cfs_read_file('domains.cfg');
1668 my $realm_cfg = $domain_cfg->{ids}->{$realm};
1669 die "auth domain '$realm' does not exist\n" if !$realm_cfg;
1670
1671 my $realm_tfa = $realm_cfg->{tfa};
1672 $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa)
1673 if $realm_tfa;
1674
6063b65b
WB
1675 if (!$keys) {
1676 return if !$realm_tfa;
1677 die "missing required 2nd keys\n";
1678 }
1679
7e58c66d 1680 # new style config starts with an 'x' and optionally contains a !<type> suffix
0a956b94 1681 if ($keys !~ /^x(?:!.*)?$/) {
fda8ca85
WB
1682 # old style config, find the type via the realm
1683 return if !$realm_tfa;
1684 return ($realm_tfa->{type}, {
1685 keys => $keys,
1686 config => $realm_tfa,
1687 });
1688 } else {
1689 my $tfa_cfg = cfs_read_file('priv/tfa.cfg');
1690 my $tfa = $tfa_cfg->{users}->{$username};
1691 return if !$tfa; # should not happen (user.cfg wasn't cleaned up?)
1692
1693 if ($realm_tfa) {
1694 # if the realm has a tfa setting we need to verify the type:
1695 die "auth domain '$realm' and user have mismatching TFA settings\n"
1696 if $realm_tfa && $realm_tfa->{type} ne $tfa->{type};
1697 }
1698
1699 return ($tfa->{type}, $tfa->{data});
1700 }
1701}
1702
3e5bfdf6
DM
1703# bash completion helpers
1704
ab7b19b5
SI
1705register_standard_option('userid-completed',
1706 get_standard_option('userid', { completion => \&complete_username}),
1707);
1708
3e5bfdf6
DM
1709sub complete_username {
1710
1711 my $user_cfg = cfs_read_file('user.cfg');
1712
1713 return [ keys %{$user_cfg->{users}} ];
1714}
1715
1716sub complete_group {
1717
1718 my $user_cfg = cfs_read_file('user.cfg');
1719
1720 return [ keys %{$user_cfg->{groups}} ];
1721}
1722
1723sub complete_realm {
1724
1725 my $domain_cfg = cfs_read_file('domains.cfg');
1726
1727 return [ keys %{$domain_cfg->{ids}} ];
1728}
1729
2c3a6c0a 17301;