fix #2079: add periodic auth key rotation
[pve-access-control.git] / 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::Base64;
11 use Digest::SHA;
12 use IO::File;
13 use File::stat;
14
15 use PVE::OTP;
16 use PVE::Ticket;
17 use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
18 use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
19 use PVE::JSONSchema qw(register_standard_option get_standard_option);
20
21 use PVE::Auth::Plugin;
22 use PVE::Auth::AD;
23 use PVE::Auth::LDAP;
24 use PVE::Auth::PVE;
25 use PVE::Auth::PAM;
26
27 # load and initialize all plugins
28
29 PVE::Auth::AD->register();
30 PVE::Auth::LDAP->register();
31 PVE::Auth::PVE->register();
32 PVE::Auth::PAM->register();
33 PVE::Auth::Plugin->init();
34
35 # $authdir must be writable by root only!
36 my $confdir = "/etc/pve";
37 my $authdir = "$confdir/priv";
38
39 my $pve_www_key_fn = "$confdir/pve-www.key";
40
41 my $pve_auth_key_files = {
42 priv => "$authdir/authkey.key",
43 pub => "$confdir/authkey.pub",
44 pubold => "$confdir/authkey.pub.old",
45 };
46
47 my $pve_auth_key_cache = {};
48
49 my $ticket_lifetime = 3600*2; # 2 hours
50 # TODO: set to 24h for PVE 6.0
51 my $authkey_lifetime = 3600*0; # rotation disabled
52
53 Crypt::OpenSSL::RSA->import_random_seed();
54
55 cfs_register_file('user.cfg',
56 \&parse_user_config,
57 \&write_user_config);
58
59 sub verify_username {
60 PVE::Auth::Plugin::verify_username(@_);
61 }
62
63 sub pve_verify_realm {
64 PVE::Auth::Plugin::pve_verify_realm(@_);
65 }
66
67 sub lock_user_config {
68 my ($code, $errmsg) = @_;
69
70 cfs_lock_file("user.cfg", undef, $code);
71 if (my $err = $@) {
72 $errmsg ? die "$errmsg: $err" : die $err;
73 }
74 }
75
76 my $cache_read_key = sub {
77 my ($type) = @_;
78
79 my $path = $pve_auth_key_files->{$type};
80
81 my $read_key_and_mtime = sub {
82 my $fh = IO::File->new($path, "r");
83
84 return undef if !defined($fh);
85
86 my $st = stat($fh);
87 my $pem = PVE::Tools::safe_read_from($fh, 0, 0, $path);
88
89 close $fh;
90
91 my $key;
92 if ($type eq 'pub' || $type eq 'pubold') {
93 $key = eval { Crypt::OpenSSL::RSA->new_public_key($pem); };
94 } elsif ($type eq 'priv') {
95 $key = eval { Crypt::OpenSSL::RSA->new_private_key($pem); };
96 } else {
97 die "Invalid authkey type '$type'\n";
98 }
99
100 return { key => $key, mtime => $st->mtime };
101 };
102
103 if (!defined($pve_auth_key_cache->{$type})) {
104 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
105 } else {
106 my $st = stat($path);
107 if (!$st || $st->mtime != $pve_auth_key_cache->{$type}->{mtime}) {
108 $pve_auth_key_cache->{$type} = $read_key_and_mtime->();
109 }
110 }
111
112 return $pve_auth_key_cache->{$type};
113 };
114
115 sub get_pubkey {
116 my ($old) = @_;
117
118 my $type = $old ? 'pubold' : 'pub';
119
120 my $res = $cache_read_key->($type);
121 return undef if !defined($res);
122
123 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
124 }
125
126 sub get_privkey {
127 my $res = $cache_read_key->('priv');
128
129 if (!defined($res) || !check_authkey(1)) {
130 rotate_authkey();
131 $res = $cache_read_key->('priv');
132 }
133
134 return wantarray ? ($res->{key}, $res->{mtime}) : $res->{key};
135 }
136
137 sub check_authkey {
138 my ($quiet) = @_;
139
140 # skip check if non-quorate, as rotation is not possible anyway
141 return 1 if !PVE::Cluster::check_cfs_quorum(1);
142
143 my ($pub_key, $mtime) = get_pubkey();
144 if (!$pub_key) {
145 warn "auth key pair missing, generating new one..\n" if !$quiet;
146 return 0;
147 } else {
148 if (time() - $mtime >= $authkey_lifetime) {
149 warn "auth key pair too old, rotating..\n" if !$quiet;;
150 return 0;
151 } else {
152 warn "auth key new enough, skipping rotation\n" if !$quiet;;
153 return 1;
154 }
155 }
156 }
157
158 sub rotate_authkey {
159 return if $authkey_lifetime == 0;
160
161 cfs_lock_authkey(undef, sub {
162 # re-check with lock to avoid double rotation in clusters
163 return if check_authkey();
164
165 my $old = get_pubkey();
166
167 if ($old) {
168 eval {
169 my $pem = $old->get_public_key_x509_string();
170 PVE::Tools::file_set_contents($pve_auth_key_files->{pubold}, $pem);
171 };
172 die "Failed to store old auth key: $@\n" if $@;
173 }
174
175 my $new = Crypt::OpenSSL::RSA->generate_key(2048);
176 eval {
177 my $pem = $new->get_public_key_x509_string();
178 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
179 };
180 if ($@) {
181 if ($old) {
182 warn "Failed to store new auth key - $@\n";
183 warn "Reverting to previous auth key\n";
184 eval {
185 my $pem = $old->get_public_key_x509_string();
186 PVE::Tools::file_set_contents($pve_auth_key_files->{pub}, $pem);
187 };
188 die "Failed to restore old auth key: $@\n" if $@;
189 } else {
190 die "Failed to store new auth key - $@\n";
191 }
192 }
193
194 eval {
195 my $pem = $new->get_private_key_string();
196 PVE::Tools::file_set_contents($pve_auth_key_files->{priv}, $pem);
197 };
198 if ($@) {
199 warn "Failed to store new auth key - $@\n";
200 warn "Deleting auth key to force regeneration\n";
201 unlink $pve_auth_key_files->{pub};
202 unlink $pve_auth_key_files->{priv};
203 }
204 });
205 die $@ if $@;
206 }
207
208 my $csrf_prevention_secret;
209 my $get_csrfr_secret = sub {
210 if (!$csrf_prevention_secret) {
211 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
212 $csrf_prevention_secret = Digest::SHA::sha1_base64($input);
213 }
214 return $csrf_prevention_secret;
215 };
216
217 sub assemble_csrf_prevention_token {
218 my ($username) = @_;
219
220 my $secret = &$get_csrfr_secret();
221
222 return PVE::Ticket::assemble_csrf_prevention_token ($secret, $username);
223 }
224
225 sub verify_csrf_prevention_token {
226 my ($username, $token, $noerr) = @_;
227
228 my $secret = &$get_csrfr_secret();
229
230 return PVE::Ticket::verify_csrf_prevention_token(
231 $secret, $username, $token, -300, $ticket_lifetime, $noerr);
232 }
233
234 my $get_ticket_age_range = sub {
235 my ($now, $mtime, $rotated) = @_;
236
237 my $key_age = $now - $mtime;
238 $key_age = 0 if $key_age < 0;
239
240 my $min = -300;
241 my $max = $ticket_lifetime;
242
243 if ($rotated) {
244 # ticket creation after rotation is not allowed
245 $min = $key_age - 300;
246 } else {
247 if ($key_age > $authkey_lifetime && $authkey_lifetime > 0) {
248 if (PVE::Cluster::check_cfs_quorum(1)) {
249 # key should have been rotated, clamp range accordingly
250 $min = $key_age - $authkey_lifetime;
251 } else {
252 warn "Cluster not quorate - extending auth key lifetime!\n";
253 }
254 }
255
256 $max = $key_age + 300 if $key_age < $ticket_lifetime;
257 }
258
259 return undef if $min > $ticket_lifetime;
260 return ($min, $max);
261 };
262
263 sub assemble_ticket {
264 my ($username) = @_;
265
266 my $rsa_priv = get_privkey();
267
268 return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $username);
269 }
270
271 sub verify_ticket {
272 my ($ticket, $noerr) = @_;
273
274 my $now = time();
275
276 my $check = sub {
277 my ($old) = @_;
278
279 my ($rsa_pub, $rsa_mtime) = get_pubkey($old);
280 return undef if !$rsa_pub;
281
282 my ($min, $max) = $get_ticket_age_range->($now, $rsa_mtime, $old);
283 return undef if !$min;
284
285 return PVE::Ticket::verify_rsa_ticket(
286 $rsa_pub, 'PVE', $ticket, undef, $min, $max, 1);
287 };
288
289 my ($username, $age) = $check->();
290
291 # check with old, rotated key if current key failed
292 ($username, $age) = $check->(1) if !defined($username);
293
294 if (!defined($username)) {
295 if ($noerr) {
296 return undef;
297 } else {
298 # raise error via undef ticket
299 PVE::Ticket::verify_rsa_ticket(undef, 'PVE');
300 }
301 }
302
303 return undef if !PVE::Auth::Plugin::verify_username($username, $noerr);
304
305 return wantarray ? ($username, $age) : $username;
306 }
307
308 # VNC tickets
309 # - they do not contain the username in plain text
310 # - they are restricted to a specific resource path (example: '/vms/100')
311 sub assemble_vnc_ticket {
312 my ($username, $path) = @_;
313
314 my $rsa_priv = get_privkey();
315
316 $path = normalize_path($path);
317
318 my $secret_data = "$username:$path";
319
320 return PVE::Ticket::assemble_rsa_ticket(
321 $rsa_priv, 'PVEVNC', undef, $secret_data);
322 }
323
324 sub verify_vnc_ticket {
325 my ($ticket, $username, $path, $noerr) = @_;
326
327 my $secret_data = "$username:$path";
328
329 my ($rsa_pub, $rsa_mtime) = get_pubkey();
330 if (!$rsa_pub || (time() - $rsa_mtime > $authkey_lifetime)) {
331 if ($noerr) {
332 return undef;
333 } else {
334 # raise error via undef ticket
335 PVE::Ticket::verify_rsa_ticket($rsa_pub, 'PVEVNC');
336 }
337 }
338
339 return PVE::Ticket::verify_rsa_ticket(
340 $rsa_pub, 'PVEVNC', $ticket, $secret_data, -20, 40, $noerr);
341 }
342
343 sub assemble_spice_ticket {
344 my ($username, $vmid, $node) = @_;
345
346 my $secret = &$get_csrfr_secret();
347
348 return PVE::Ticket::assemble_spice_ticket(
349 $secret, $username, $vmid, $node);
350 }
351
352 sub verify_spice_connect_url {
353 my ($connect_str) = @_;
354
355 my $secret = &$get_csrfr_secret();
356
357 return PVE::Ticket::verify_spice_connect_url($secret, $connect_str);
358 }
359
360 sub read_x509_subject_spice {
361 my ($filename) = @_;
362
363 # read x509 subject
364 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
365 die "Could not open $filename using OpenSSL\n"
366 if !$bio;
367
368 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
369 Net::SSLeay::BIO_free($bio);
370
371 die "Could not parse X509 certificate in $filename\n"
372 if !$x509;
373
374 my $nameobj = Net::SSLeay::X509_get_subject_name($x509);
375 my $subject = Net::SSLeay::X509_NAME_oneline($nameobj);
376 Net::SSLeay::X509_free($x509);
377
378 # remote-viewer wants comma as seperator (not '/')
379 $subject =~ s!^/!!;
380 $subject =~ s!/(\w+=)!,$1!g;
381
382 return $subject;
383 }
384
385 # helper to generate SPICE remote-viewer configuration
386 sub remote_viewer_config {
387 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
388
389 if (!$proxy) {
390 my $host = `hostname -f` || PVE::INotify::nodename();
391 chomp $host;
392 $proxy = $host;
393 }
394
395 my ($ticket, $proxyticket) = assemble_spice_ticket($authuser, $vmid, $node);
396
397 my $filename = "/etc/pve/local/pve-ssl.pem";
398 my $subject = read_x509_subject_spice($filename);
399
400 my $cacert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192);
401 $cacert =~ s/\n/\\n/g;
402
403 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
404 my $config = {
405 'secure-attention' => "Ctrl+Alt+Ins",
406 'toggle-fullscreen' => "Shift+F11",
407 'release-cursor' => "Ctrl+Alt+R",
408 type => 'spice',
409 title => $title,
410 host => $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
411 proxy => "http://$proxy:3128",
412 'tls-port' => $port,
413 'host-subject' => $subject,
414 ca => $cacert,
415 password => $ticket,
416 'delete-this-file' => 1,
417 };
418
419 return ($ticket, $proxyticket, $config);
420 }
421
422 sub check_user_exist {
423 my ($usercfg, $username, $noerr) = @_;
424
425 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
426 return undef if !$username;
427
428 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
429
430 die "no such user ('$username')\n" if !$noerr;
431
432 return undef;
433 }
434
435 sub check_user_enabled {
436 my ($usercfg, $username, $noerr) = @_;
437
438 my $data = check_user_exist($usercfg, $username, $noerr);
439 return undef if !$data;
440
441 return 1 if $data->{enable};
442
443 die "user '$username' is disabled\n" if !$noerr;
444
445 return undef;
446 }
447
448 sub verify_one_time_pw {
449 my ($usercfg, $username, $tfa_cfg, $otp) = @_;
450
451 my $type = $tfa_cfg->{type};
452
453 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
454
455 # fixme: proxy support?
456 my $proxy;
457
458 if ($type eq 'yubico') {
459 my $keys = $usercfg->{users}->{$username}->{keys};
460 PVE::OTP::yubico_verify_otp($otp, $keys, $tfa_cfg->{url},
461 $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
462 } elsif ($type eq 'oath') {
463 my $keys = $usercfg->{users}->{$username}->{keys};
464 PVE::OTP::oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
465 } else {
466 die "unknown tfa type '$type'\n";
467 }
468 }
469
470 # password should be utf8 encoded
471 # Note: some plugins delay/sleep if auth fails
472 sub authenticate_user {
473 my ($username, $password, $otp) = @_;
474
475 die "no username specified\n" if !$username;
476
477 my ($ruid, $realm);
478
479 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
480
481 my $usercfg = cfs_read_file('user.cfg');
482
483 check_user_enabled($usercfg, $username);
484
485 my $ctime = time();
486 my $expire = $usercfg->{users}->{$username}->{expire};
487
488 die "account expired\n" if $expire && ($expire < $ctime);
489
490 my $domain_cfg = cfs_read_file('domains.cfg');
491
492 my $cfg = $domain_cfg->{ids}->{$realm};
493 die "auth domain '$realm' does not exists\n" if !$cfg;
494 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
495 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
496
497 if ($cfg->{tfa}) {
498 my $tfa_cfg = PVE::Auth::Plugin::parse_tfa_config($cfg->{tfa});
499 verify_one_time_pw($usercfg, $username, $tfa_cfg, $otp);
500 }
501
502 return $username;
503 }
504
505 sub domain_set_password {
506 my ($realm, $username, $password) = @_;
507
508 die "no auth domain specified" if !$realm;
509
510 my $domain_cfg = cfs_read_file('domains.cfg');
511
512 my $cfg = $domain_cfg->{ids}->{$realm};
513 die "auth domain '$realm' does not exist\n" if !$cfg;
514 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
515 $plugin->store_password($cfg, $realm, $username, $password);
516 }
517
518 sub add_user_group {
519 my ($username, $usercfg, $group) = @_;
520
521 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
522 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
523 }
524
525 sub delete_user_group {
526 my ($username, $usercfg) = @_;
527
528 foreach my $group (keys %{$usercfg->{groups}}) {
529
530 delete ($usercfg->{groups}->{$group}->{users}->{$username})
531 if $usercfg->{groups}->{$group}->{users}->{$username};
532 }
533 }
534
535 sub delete_user_acl {
536 my ($username, $usercfg) = @_;
537
538 foreach my $acl (keys %{$usercfg->{acl}}) {
539
540 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
541 if $usercfg->{acl}->{$acl}->{users}->{$username};
542 }
543 }
544
545 sub delete_group_acl {
546 my ($group, $usercfg) = @_;
547
548 foreach my $acl (keys %{$usercfg->{acl}}) {
549
550 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
551 if $usercfg->{acl}->{$acl}->{groups}->{$group};
552 }
553 }
554
555 sub delete_pool_acl {
556 my ($pool, $usercfg) = @_;
557
558 my $path = "/pool/$pool";
559
560 delete ($usercfg->{acl}->{$path})
561 }
562
563 # we automatically create some predefined roles by splitting privs
564 # into 3 groups (per category)
565 # root: only root is allowed to do that
566 # admin: an administrator can to that
567 # user: a normal user/customer can to that
568 my $privgroups = {
569 VM => {
570 root => [],
571 admin => [
572 'VM.Config.Disk',
573 'VM.Config.CPU',
574 'VM.Config.Memory',
575 'VM.Config.Network',
576 'VM.Config.HWType',
577 'VM.Config.Options', # covers all other things
578 'VM.Allocate',
579 'VM.Clone',
580 'VM.Migrate',
581 'VM.Monitor',
582 'VM.Snapshot',
583 'VM.Snapshot.Rollback',
584 ],
585 user => [
586 'VM.Config.CDROM', # change CDROM media
587 'VM.Console',
588 'VM.Backup',
589 'VM.PowerMgmt',
590 ],
591 audit => [
592 'VM.Audit',
593 ],
594 },
595 Sys => {
596 root => [
597 'Sys.PowerMgmt',
598 'Sys.Modify', # edit/change node settings
599 ],
600 admin => [
601 'Permissions.Modify',
602 'Sys.Console',
603 'Sys.Syslog',
604 ],
605 user => [],
606 audit => [
607 'Sys.Audit',
608 ],
609 },
610 Datastore => {
611 root => [],
612 admin => [
613 'Datastore.Allocate',
614 'Datastore.AllocateTemplate',
615 ],
616 user => [
617 'Datastore.AllocateSpace',
618 ],
619 audit => [
620 'Datastore.Audit',
621 ],
622 },
623 User => {
624 root => [
625 'Realm.Allocate',
626 ],
627 admin => [
628 'User.Modify',
629 'Group.Allocate', # edit/change group settings
630 'Realm.AllocateUser',
631 ],
632 user => [],
633 audit => [],
634 },
635 Pool => {
636 root => [],
637 admin => [
638 'Pool.Allocate', # create/delete pools
639 ],
640 user => [],
641 audit => [],
642 },
643 };
644
645 my $valid_privs = {};
646
647 my $special_roles = {
648 'NoAccess' => {}, # no privileges
649 'Administrator' => $valid_privs, # all privileges
650 };
651
652 sub create_roles {
653
654 foreach my $cat (keys %$privgroups) {
655 my $cd = $privgroups->{$cat};
656 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
657 @{$cd->{user}}, @{$cd->{audit}}) {
658 $valid_privs->{$p} = 1;
659 }
660 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
661
662 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
663 $special_roles->{"PVEAdmin"}->{$p} = 1;
664 }
665 if (scalar(@{$cd->{user}})) {
666 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
667 $special_roles->{"PVE${cat}User"}->{$p} = 1;
668 }
669 }
670 foreach my $p (@{$cd->{audit}}) {
671 $special_roles->{"PVEAuditor"}->{$p} = 1;
672 }
673 }
674
675 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
676 };
677
678 create_roles();
679
680 sub create_priv_properties {
681 my $properties = {};
682 foreach my $priv (keys %$valid_privs) {
683 $properties->{$priv} = {
684 type => 'boolean',
685 optional => 1,
686 };
687 }
688 return $properties;
689 }
690
691 sub role_is_special {
692 my ($role) = @_;
693 return (exists $special_roles->{$role}) ? 1 : 0;
694 }
695
696 sub add_role_privs {
697 my ($role, $usercfg, $privs) = @_;
698
699 return if !$privs;
700
701 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
702
703 foreach my $priv (split_list($privs)) {
704 if (defined ($valid_privs->{$priv})) {
705 $usercfg->{roles}->{$role}->{$priv} = 1;
706 } else {
707 die "invalid privilege '$priv'\n";
708 }
709 }
710 }
711
712 sub normalize_path {
713 my $path = shift;
714
715 $path =~ s|/+|/|g;
716
717 $path =~ s|/$||;
718
719 $path = '/' if !$path;
720
721 $path = "/$path" if $path !~ m|^/|;
722
723 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
724
725 return $path;
726 }
727
728 PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
729 sub verify_groupname {
730 my ($groupname, $noerr) = @_;
731
732 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
733
734 die "group name '$groupname' contains invalid characters\n" if !$noerr;
735
736 return undef;
737 }
738
739 return $groupname;
740 }
741
742 PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
743 sub verify_rolename {
744 my ($rolename, $noerr) = @_;
745
746 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
747
748 die "role name '$rolename' contains invalid characters\n" if !$noerr;
749
750 return undef;
751 }
752
753 return $rolename;
754 }
755
756 PVE::JSONSchema::register_format('pve-poolid', \&verify_poolname);
757 sub verify_poolname {
758 my ($poolname, $noerr) = @_;
759
760 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
761
762 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
763
764 return undef;
765 }
766
767 return $poolname;
768 }
769
770 PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
771 sub verify_privname {
772 my ($priv, $noerr) = @_;
773
774 if (!$valid_privs->{$priv}) {
775 die "invalid privilege '$priv'\n" if !$noerr;
776
777 return undef;
778 }
779
780 return $priv;
781 }
782
783 sub userconfig_force_defaults {
784 my ($cfg) = @_;
785
786 foreach my $r (keys %$special_roles) {
787 $cfg->{roles}->{$r} = $special_roles->{$r};
788 }
789
790 # add root user if not exists
791 if (!$cfg->{users}->{'root@pam'}) {
792 $cfg->{users}->{'root@pam'}->{enable} = 1;
793 }
794 }
795
796 sub parse_user_config {
797 my ($filename, $raw) = @_;
798
799 my $cfg = {};
800
801 userconfig_force_defaults($cfg);
802
803 $raw = '' if !defined($raw);
804 while ($raw =~ /^\s*(.+?)\s*$/gm) {
805 my $line = $1;
806 my @data;
807
808 foreach my $d (split (/:/, $line)) {
809 $d =~ s/^\s+//;
810 $d =~ s/\s+$//;
811 push @data, $d
812 }
813
814 my $et = shift @data;
815
816 if ($et eq 'user') {
817 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
818
819 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
820 if (!$realm) {
821 warn "user config - ignore user '$user' - invalid user name\n";
822 next;
823 }
824
825 $enable = $enable ? 1 : 0;
826
827 $expire = 0 if !$expire;
828
829 if ($expire !~ m/^\d+$/) {
830 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
831 next;
832 }
833 $expire = int($expire);
834
835 #if (!verify_groupname ($group, 1)) {
836 # warn "user config - ignore user '$user' - invalid characters in group name\n";
837 # next;
838 #}
839
840 $cfg->{users}->{$user} = {
841 enable => $enable,
842 # group => $group,
843 };
844 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
845 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
846 $cfg->{users}->{$user}->{email} = $email;
847 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
848 $cfg->{users}->{$user}->{expire} = $expire;
849 # keys: allowed yubico key ids or oath secrets (base32 encoded)
850 $cfg->{users}->{$user}->{keys} = $keys if $keys;
851
852 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
853 #$cfg->{groups}->{$group}->{$user} = 1;
854
855 } elsif ($et eq 'group') {
856 my ($group, $userlist, $comment) = @data;
857
858 if (!verify_groupname($group, 1)) {
859 warn "user config - ignore group '$group' - invalid characters in group name\n";
860 next;
861 }
862
863 # make sure to add the group (even if there are no members)
864 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
865
866 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
867
868 foreach my $user (split_list($userlist)) {
869
870 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
871 warn "user config - ignore invalid group member '$user'\n";
872 next;
873 }
874
875 if ($cfg->{users}->{$user}) { # user exists
876 $cfg->{users}->{$user}->{groups}->{$group} = 1;
877 $cfg->{groups}->{$group}->{users}->{$user} = 1;
878 } else {
879 warn "user config - ignore invalid group member '$user'\n";
880 }
881 }
882
883 } elsif ($et eq 'role') {
884 my ($role, $privlist) = @data;
885
886 if (!verify_rolename($role, 1)) {
887 warn "user config - ignore role '$role' - invalid characters in role name\n";
888 next;
889 }
890
891 # make sure to add the role (even if there are no privileges)
892 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
893
894 foreach my $priv (split_list($privlist)) {
895 if (defined ($valid_privs->{$priv})) {
896 $cfg->{roles}->{$role}->{$priv} = 1;
897 } else {
898 warn "user config - ignore invalid priviledge '$priv'\n";
899 }
900 }
901
902 } elsif ($et eq 'acl') {
903 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
904
905 if (my $path = normalize_path($pathtxt)) {
906 foreach my $role (split_list($rolelist)) {
907
908 if (!verify_rolename($role, 1)) {
909 warn "user config - ignore invalid role name '$role' in acl\n";
910 next;
911 }
912
913 foreach my $ug (split_list($uglist)) {
914 if ($ug =~ m/^@(\S+)$/) {
915 my $group = $1;
916 if ($cfg->{groups}->{$group}) { # group exists
917 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
918 } else {
919 warn "user config - ignore invalid acl group '$group'\n";
920 }
921 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
922 if ($cfg->{users}->{$ug}) { # user exists
923 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
924 } else {
925 warn "user config - ignore invalid acl member '$ug'\n";
926 }
927 } else {
928 warn "user config - invalid user/group '$ug' in acl\n";
929 }
930 }
931 }
932 } else {
933 warn "user config - ignore invalid path in acl '$pathtxt'\n";
934 }
935 } elsif ($et eq 'pool') {
936 my ($pool, $comment, $vmlist, $storelist) = @data;
937
938 if (!verify_poolname($pool, 1)) {
939 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
940 next;
941 }
942
943 # make sure to add the pool (even if there are no members)
944 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
945
946 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
947
948 foreach my $vmid (split_list($vmlist)) {
949 if ($vmid !~ m/^\d+$/) {
950 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
951 next;
952 }
953 $vmid = int($vmid);
954
955 if ($cfg->{vms}->{$vmid}) {
956 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
957 next;
958 }
959
960 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
961
962 # record vmid ==> pool relation
963 $cfg->{vms}->{$vmid} = $pool;
964 }
965
966 foreach my $storeid (split_list($storelist)) {
967 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
968 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
969 next;
970 }
971 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
972 }
973 } else {
974 warn "user config - ignore config line: $line\n";
975 }
976 }
977
978 userconfig_force_defaults($cfg);
979
980 return $cfg;
981 }
982
983 sub write_user_config {
984 my ($filename, $cfg) = @_;
985
986 my $data = '';
987
988 foreach my $user (keys %{$cfg->{users}}) {
989 my $d = $cfg->{users}->{$user};
990 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
991 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
992 my $email = $d->{email} || '';
993 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
994 my $expire = int($d->{expire} || 0);
995 my $enable = $d->{enable} ? 1 : 0;
996 my $keys = $d->{keys} ? $d->{keys} : '';
997 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
998 }
999
1000 $data .= "\n";
1001
1002 foreach my $group (keys %{$cfg->{groups}}) {
1003 my $d = $cfg->{groups}->{$group};
1004 my $list = join (',', keys %{$d->{users}});
1005 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1006 $data .= "group:$group:$list:$comment:\n";
1007 }
1008
1009 $data .= "\n";
1010
1011 foreach my $pool (keys %{$cfg->{pools}}) {
1012 my $d = $cfg->{pools}->{$pool};
1013 my $vmlist = join (',', keys %{$d->{vms}});
1014 my $storelist = join (',', keys %{$d->{storage}});
1015 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1016 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
1017 }
1018
1019 $data .= "\n";
1020
1021 foreach my $role (keys %{$cfg->{roles}}) {
1022 next if $special_roles->{$role};
1023
1024 my $d = $cfg->{roles}->{$role};
1025 my $list = join (',', keys %$d);
1026 $data .= "role:$role:$list:\n";
1027 }
1028
1029 $data .= "\n";
1030
1031 foreach my $path (sort keys %{$cfg->{acl}}) {
1032 my $d = $cfg->{acl}->{$path};
1033
1034 my $ra = {};
1035
1036 foreach my $group (keys %{$d->{groups}}) {
1037 my $l0 = '';
1038 my $l1 = '';
1039 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
1040 my $propagate = $d->{groups}->{$group}->{$role};
1041 if ($propagate) {
1042 $l1 .= ',' if $l1;
1043 $l1 .= $role;
1044 } else {
1045 $l0 .= ',' if $l0;
1046 $l0 .= $role;
1047 }
1048 }
1049 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
1050 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
1051 }
1052
1053 foreach my $user (keys %{$d->{users}}) {
1054 # no need to save, because root is always 'Administrator'
1055 next if $user eq 'root@pam';
1056
1057 my $l0 = '';
1058 my $l1 = '';
1059 foreach my $role (sort keys %{$d->{users}->{$user}}) {
1060 my $propagate = $d->{users}->{$user}->{$role};
1061 if ($propagate) {
1062 $l1 .= ',' if $l1;
1063 $l1 .= $role;
1064 } else {
1065 $l0 .= ',' if $l0;
1066 $l0 .= $role;
1067 }
1068 }
1069 $ra->{0}->{$l0}->{$user} = 1 if $l0;
1070 $ra->{1}->{$l1}->{$user} = 1 if $l1;
1071 }
1072
1073 foreach my $rolelist (sort keys %{$ra->{0}}) {
1074 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
1075 $data .= "acl:0:$path:$uglist:$rolelist:\n";
1076 }
1077 foreach my $rolelist (sort keys %{$ra->{1}}) {
1078 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
1079 $data .= "acl:1:$path:$uglist:$rolelist:\n";
1080 }
1081 }
1082
1083 return $data;
1084 }
1085
1086 sub roles {
1087 my ($cfg, $user, $path) = @_;
1088
1089 # NOTE: we do not consider pools here.
1090 # You need to use $rpcenv->roles() instead if you want that.
1091
1092 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1093
1094 my $perm = {};
1095
1096 foreach my $p (sort keys %{$cfg->{acl}}) {
1097 my $final = ($path eq $p);
1098
1099 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1100
1101 my $acl = $cfg->{acl}->{$p};
1102
1103 #print "CHECKACL $path $p\n";
1104 #print "ACL $path = " . Dumper ($acl);
1105
1106 if (my $ri = $acl->{users}->{$user}) {
1107 my $new;
1108 foreach my $role (keys %$ri) {
1109 my $propagate = $ri->{$role};
1110 if ($final || $propagate) {
1111 #print "APPLY ROLE $p $user $role\n";
1112 $new = {} if !$new;
1113 $new->{$role} = 1;
1114 }
1115 }
1116 if ($new) {
1117 $perm = $new; # overwrite previous settings
1118 next; # user privs always override group privs
1119 }
1120 }
1121
1122 my $new;
1123 foreach my $g (keys %{$acl->{groups}}) {
1124 next if !$cfg->{groups}->{$g}->{users}->{$user};
1125 if (my $ri = $acl->{groups}->{$g}) {
1126 foreach my $role (keys %$ri) {
1127 my $propagate = $ri->{$role};
1128 if ($final || $propagate) {
1129 #print "APPLY ROLE $p \@$g $role\n";
1130 $new = {} if !$new;
1131 $new->{$role} = 1;
1132 }
1133 }
1134 }
1135 }
1136 if ($new) {
1137 $perm = $new; # overwrite previous settings
1138 next;
1139 }
1140 }
1141
1142 return ('NoAccess') if defined ($perm->{NoAccess});
1143 #return () if defined ($perm->{NoAccess});
1144
1145 #print "permission $user $path = " . Dumper ($perm);
1146
1147 my @ra = keys %$perm;
1148
1149 #print "roles $user $path = " . join (',', @ra) . "\n";
1150
1151 return @ra;
1152 }
1153
1154 sub permission {
1155 my ($cfg, $user, $path) = @_;
1156
1157 $user = PVE::Auth::Plugin::verify_username($user, 1);
1158 return {} if !$user;
1159
1160 my @ra = roles($cfg, $user, $path);
1161
1162 my $privs = {};
1163
1164 foreach my $role (@ra) {
1165 if (my $privset = $cfg->{roles}->{$role}) {
1166 foreach my $p (keys %$privset) {
1167 $privs->{$p} = 1;
1168 }
1169 }
1170 }
1171
1172 #print "priviledges $user $path = " . Dumper ($privs);
1173
1174 return $privs;
1175 }
1176
1177 sub check_permissions {
1178 my ($username, $path, $privlist) = @_;
1179
1180 $path = normalize_path($path);
1181 my $usercfg = cfs_read_file('user.cfg');
1182 my $perm = permission($usercfg, $username, $path);
1183
1184 foreach my $priv (split_list($privlist)) {
1185 return undef if !$perm->{$priv};
1186 };
1187
1188 return 1;
1189 }
1190
1191 sub remove_vm_access {
1192 my ($vmid) = @_;
1193 my $delVMaccessFn = sub {
1194 my $usercfg = cfs_read_file("user.cfg");
1195 my $modified;
1196
1197 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1198 delete $usercfg->{acl}->{"/vms/$vmid"};
1199 $modified = 1;
1200 }
1201 if (my $pool = $usercfg->{vms}->{$vmid}) {
1202 if (my $data = $usercfg->{pools}->{$pool}) {
1203 delete $data->{vms}->{$vmid};
1204 delete $usercfg->{vms}->{$vmid};
1205 $modified = 1;
1206 }
1207 }
1208 cfs_write_file("user.cfg", $usercfg) if $modified;
1209 };
1210
1211 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1212 }
1213
1214 sub remove_storage_access {
1215 my ($storeid) = @_;
1216
1217 my $deleteStorageAccessFn = sub {
1218 my $usercfg = cfs_read_file("user.cfg");
1219 my $modified;
1220
1221 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1222 delete $usercfg->{acl}->{"/storage/$storeid"};
1223 $modified = 1;
1224 }
1225 foreach my $pool (keys %{$usercfg->{pools}}) {
1226 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1227 $modified = 1;
1228 }
1229 cfs_write_file("user.cfg", $usercfg) if $modified;
1230 };
1231
1232 lock_user_config($deleteStorageAccessFn,
1233 "access permissions cleanup for storage $storeid failed");
1234 }
1235
1236 sub add_vm_to_pool {
1237 my ($vmid, $pool) = @_;
1238
1239 my $addVMtoPoolFn = sub {
1240 my $usercfg = cfs_read_file("user.cfg");
1241 if (my $data = $usercfg->{pools}->{$pool}) {
1242 $data->{vms}->{$vmid} = 1;
1243 $usercfg->{vms}->{$vmid} = $pool;
1244 cfs_write_file("user.cfg", $usercfg);
1245 }
1246 };
1247
1248 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1249 }
1250
1251 sub remove_vm_from_pool {
1252 my ($vmid) = @_;
1253
1254 my $delVMfromPoolFn = sub {
1255 my $usercfg = cfs_read_file("user.cfg");
1256 if (my $pool = $usercfg->{vms}->{$vmid}) {
1257 if (my $data = $usercfg->{pools}->{$pool}) {
1258 delete $data->{vms}->{$vmid};
1259 delete $usercfg->{vms}->{$vmid};
1260 cfs_write_file("user.cfg", $usercfg);
1261 }
1262 }
1263 };
1264
1265 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1266 }
1267
1268 # bash completion helpers
1269
1270 register_standard_option('userid-completed',
1271 get_standard_option('userid', { completion => \&complete_username}),
1272 );
1273
1274 sub complete_username {
1275
1276 my $user_cfg = cfs_read_file('user.cfg');
1277
1278 return [ keys %{$user_cfg->{users}} ];
1279 }
1280
1281 sub complete_group {
1282
1283 my $user_cfg = cfs_read_file('user.cfg');
1284
1285 return [ keys %{$user_cfg->{groups}} ];
1286 }
1287
1288 sub complete_realm {
1289
1290 my $domain_cfg = cfs_read_file('domains.cfg');
1291
1292 return [ keys %{$domain_cfg->{ids}} ];
1293 }
1294
1295 1;