assemble_spice_ticket: do not use base32 encoding
[pve-access-control.git] / PVE / AccessControl.pm
CommitLineData
2c3a6c0a
DM
1package PVE::AccessControl;
2
3use strict;
4use Encode;
5use Crypt::OpenSSL::Random;
6use Crypt::OpenSSL::RSA;
7use MIME::Base64;
8use Digest::SHA;
2c3a6c0a
DM
9use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
10use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
11use PVE::JSONSchema;
5bb4e06a
DM
12
13use PVE::Auth::Plugin;
14use PVE::Auth::AD;
15use PVE::Auth::LDAP;
16use PVE::Auth::PVE;
17use PVE::Auth::PAM;
2c3a6c0a
DM
18
19use Data::Dumper; # fixme: remove
20
5bb4e06a
DM
21# load and initialize all plugins
22
23PVE::Auth::AD->register();
24PVE::Auth::LDAP->register();
25PVE::Auth::PVE->register();
26PVE::Auth::PAM->register();
27PVE::Auth::Plugin->init();
28
2c3a6c0a
DM
29# $authdir must be writable by root only!
30my $confdir = "/etc/pve";
31my $authdir = "$confdir/priv";
32my $authprivkeyfn = "$authdir/authkey.key";
33my $authpubkeyfn = "$confdir/authkey.pub";
2c3a6c0a
DM
34my $pve_www_key_fn = "$confdir/pve-www.key";
35
36my $ticket_lifetime = 3600*2; # 2 hours
37
38Crypt::OpenSSL::RSA->import_random_seed();
39
40cfs_register_file('user.cfg',
41 \&parse_user_config,
42 \&write_user_config);
43
2c3a6c0a 44
5bb4e06a
DM
45sub verify_username {
46 PVE::Auth::Plugin::verify_username(@_);
2c3a6c0a
DM
47}
48
5bb4e06a
DM
49sub pve_verify_realm {
50 PVE::Auth::Plugin::pve_verify_realm(@_);
2c3a6c0a
DM
51}
52
5bb4e06a 53sub lock_user_config {
2c3a6c0a
DM
54 my ($code, $errmsg) = @_;
55
5bb4e06a
DM
56 cfs_lock_file("user.cfg", undef, $code);
57 if (my $err = $@) {
2c3a6c0a
DM
58 $errmsg ? die "$errmsg: $err" : die $err;
59 }
60}
61
62my $pve_auth_pub_key;
63sub get_pubkey {
64
65 return $pve_auth_pub_key if $pve_auth_pub_key;
66
67 my $input = PVE::Tools::file_get_contents($authpubkeyfn);
68
69 $pve_auth_pub_key = Crypt::OpenSSL::RSA->new_public_key($input);
70
71 return $pve_auth_pub_key;
72}
73
74my $csrf_prevention_secret;
75my $get_csrfr_secret = sub {
76 if (!$csrf_prevention_secret) {
77 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
78 $csrf_prevention_secret = Digest::SHA::sha1_base64($input);
79 }
80 return $csrf_prevention_secret;
81};
82
83sub assemble_csrf_prevention_token {
84 my ($username) = @_;
85
86 my $timestamp = sprintf("%08X", time());
87
88 my $digest = Digest::SHA::sha1_base64("$timestamp:$username", &$get_csrfr_secret());
89
90 return "$timestamp:$digest";
91}
92
93sub verify_csrf_prevention_token {
94 my ($username, $token, $noerr) = @_;
95
96 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
97 my $sig = $2;
98 my $timestamp = $1;
99 my $ttime = hex($timestamp);
100
101 my $digest = Digest::SHA::sha1_base64("$timestamp:$username", &$get_csrfr_secret());
102
103 my $age = time() - $ttime;
104 return if ($digest eq $sig) && ($age > -300) && ($age < $ticket_lifetime);
105 }
106
107 die "Permission denied - invalid csrf token\n" if !$noerr;
108
109 return undef;
110}
111
112my $pve_auth_priv_key;
113sub get_privkey {
114
115 return $pve_auth_priv_key if $pve_auth_priv_key;
116
117 my $input = PVE::Tools::file_get_contents($authprivkeyfn);
118
119 $pve_auth_priv_key = Crypt::OpenSSL::RSA->new_private_key($input);
120
121 return $pve_auth_priv_key;
122}
123
124sub assemble_ticket {
125 my ($username) = @_;
126
127 my $rsa_priv = get_privkey();
128
129 my $timestamp = sprintf("%08X", time());
130
131 my $plain = "PVE:$username:$timestamp";
132
133 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($plain), '');
134
135 return $ticket;
136}
137
138sub verify_ticket {
139 my ($ticket, $noerr) = @_;
140
adf8d771 141 if ($ticket && $ticket =~ m/^(PVE:\S+)::([^:\s]+)$/) {
2c3a6c0a
DM
142 my $plain = $1;
143 my $sig = $2;
144
145 my $rsa_pub = get_pubkey();
146 if ($rsa_pub->verify($plain, decode_base64($sig))) {
533219a1 147 if ($plain =~ m/^PVE:(\S+):([A-Z0-9]{8})$/) {
2c3a6c0a 148 my $username = $1;
533219a1 149 my $timestamp = $2;
2c3a6c0a
DM
150 my $ttime = hex($timestamp);
151
152 my $age = time() - $ttime;
153
5bb4e06a 154 if (PVE::Auth::Plugin::verify_username($username, 1) &&
533219a1 155 ($age > -300) && ($age < $ticket_lifetime)) {
2c3a6c0a
DM
156 return wantarray ? ($username, $age) : $username;
157 }
158 }
159 }
160 }
161
162 die "permission denied - invalid ticket\n" if !$noerr;
163
164 return undef;
165}
166
adf8d771
DM
167# VNC tickets
168# - they do not contain the username in plain text
169# - they are restricted to a specific resource path (example: '/vms/100')
170sub assemble_vnc_ticket {
171 my ($username, $path) = @_;
172
173 my $rsa_priv = get_privkey();
174
175 my $timestamp = sprintf("%08X", time());
176
177 my $plain = "PVEVNC:$timestamp";
178
179 $path = normalize_path($path);
180
181 my $full = "$plain:$username:$path";
182
183 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($full), '');
184
185 return $ticket;
186}
187
188sub verify_vnc_ticket {
189 my ($ticket, $username, $path, $noerr) = @_;
190
191 if ($ticket && $ticket =~ m/^(PVEVNC:\S+)::([^:\s]+)$/) {
192 my $plain = $1;
193 my $sig = $2;
194 my $full = "$plain:$username:$path";
195
196 my $rsa_pub = get_pubkey();
197 # Note: sign only match if $username and $path is correct
198 if ($rsa_pub->verify($full, decode_base64($sig))) {
199 if ($plain =~ m/^PVEVNC:([A-Z0-9]{8})$/) {
200 my $ttime = hex($1);
201
202 my $age = time() - $ttime;
203
204 if (($age > -20) && ($age < 40)) {
205 return 1;
206 }
207 }
208 }
209 }
210
211 die "permission denied - invalid vnc ticket\n" if !$noerr;
212
213 return undef;
214}
215
23b35225
AD
216sub assemble_spice_ticket {
217 my ($username, $path) = @_;
218
219 my $rsa_priv = get_privkey();
220
221 my $timestamp = sprintf("%08X", time());
222
223 my $plain = "PVESPICE:$timestamp";
224
225 $path = normalize_path($path);
226
227 my $full = "$plain:$path";
228
229 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($full), '');
83d1f13e
DM
230
231 return $ticket;
23b35225
AD
232}
233
37d45deb 234sub check_user_exist {
7070c1ae 235 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 236
5bb4e06a 237 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a
DM
238 return undef if !$username;
239
37d45deb
DM
240 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
241
242 die "no such user ('$username')\n" if !$noerr;
243
244 return undef;
245}
246
247sub check_user_enabled {
248 my ($usercfg, $username, $noerr) = @_;
249
250 my $data = check_user_exist($usercfg, $username, $noerr);
251 return undef if !$data;
252
253 return 1 if $data->{enable};
2c3a6c0a
DM
254
255 return 1 if $username eq 'root@pam'; # root is always enabled
256
37d45deb 257 die "user '$username' is disabled\n" if !$noerr;
7070c1ae
DM
258
259 return undef;
2c3a6c0a
DM
260}
261
262# password should be utf8 encoded
263sub authenticate_user {
264 my ($username, $password) = @_;
265
266 die "no username specified\n" if !$username;
267
5bb4e06a 268 my ($ruid, $realm);
2c3a6c0a 269
5bb4e06a 270 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
2c3a6c0a
DM
271
272 my $usercfg = cfs_read_file('user.cfg');
273
7070c1ae
DM
274 eval { check_user_enabled($usercfg, $username); };
275 if (my $err = $@) {
2c3a6c0a 276 sleep(2);
7070c1ae 277 die $err;
2c3a6c0a
DM
278 }
279
280 my $ctime = time();
281 my $expire = $usercfg->{users}->{$username}->{expire};
282
283 if ($expire && ($expire < $ctime)) {
284 sleep(2);
285 die "account expired\n"
286 }
287
5bb4e06a 288 my $domain_cfg = cfs_read_file('domains.cfg');
2c3a6c0a 289
5bb4e06a
DM
290 eval {
291 my $cfg = $domain_cfg->{ids}->{$realm};
292 die "auth domain '$realm' does not exists\n" if !$cfg;
293 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
294 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
295 };
296 if (my $err = $@) {
297 sleep(2); # timeout after failed auth
298 die $err;
299 }
2c3a6c0a 300
5bb4e06a 301 return $username;
2c3a6c0a
DM
302}
303
304sub domain_set_password {
5bb4e06a 305 my ($realm, $username, $password) = @_;
2c3a6c0a
DM
306
307 die "no auth domain specified" if !$realm;
308
5bb4e06a
DM
309 my $domain_cfg = cfs_read_file('domains.cfg');
310
311 my $cfg = $domain_cfg->{ids}->{$realm};
312 die "auth domain '$realm' does not exists\n" if !$cfg;
313 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
314 $plugin->store_password($cfg, $realm, $username, $password);
2c3a6c0a
DM
315}
316
317sub add_user_group {
318
319 my ($username, $usercfg, $group) = @_;
320 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
321 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
322}
323
324sub delete_user_group {
325
326 my ($username, $usercfg) = @_;
327
328 foreach my $group (keys %{$usercfg->{groups}}) {
329
330 delete ($usercfg->{groups}->{$group}->{users}->{$username})
331 if $usercfg->{groups}->{$group}->{users}->{$username};
332 }
333}
334
335sub delete_user_acl {
336
337 my ($username, $usercfg) = @_;
338
339 foreach my $acl (keys %{$usercfg->{acl}}) {
340
341 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
342 if $usercfg->{acl}->{$acl}->{users}->{$username};
343 }
2c3a6c0a 344}
39c85db8 345
2c3a6c0a
DM
346sub delete_group_acl {
347
348 my ($group, $usercfg) = @_;
349
350 foreach my $acl (keys %{$usercfg->{acl}}) {
351
352 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
353 if $usercfg->{acl}->{$acl}->{groups}->{$group};
354 }
39c85db8
DM
355}
356
357sub delete_pool_acl {
358
359 my ($pool, $usercfg) = @_;
2c3a6c0a 360
39c85db8
DM
361 my $path = "/pool/$pool";
362
363 foreach my $aclpath (keys %{$usercfg->{acl}}) {
364 delete ($usercfg->{acl}->{$aclpath})
365 if $usercfg->{acl}->{$aclpath} eq 'path';
366 }
2c3a6c0a
DM
367}
368
369# we automatically create some predefined roles by splitting privs
370# into 3 groups (per category)
371# root: only root is allowed to do that
372# admin: an administrator can to that
373# user: a normak user/customer can to that
374my $privgroups = {
375 VM => {
376 root => [],
377 admin => [
c0fead8c 378 'VM.Config.Disk',
c0fead8c
DM
379 'VM.Config.CPU',
380 'VM.Config.Memory',
381 'VM.Config.Network',
382 'VM.Config.HWType',
383 'VM.Config.Options', # covers all other things
2c3a6c0a 384 'VM.Allocate',
7b395f99 385 'VM.Clone',
2c3a6c0a 386 'VM.Migrate',
c0fead8c 387 'VM.Monitor',
e3e6510c 388 'VM.Snapshot',
2c3a6c0a
DM
389 ],
390 user => [
cc7bdf33 391 'VM.Config.CDROM', # change CDROM media
2c3a6c0a 392 'VM.Console',
68d5a86d 393 'VM.Backup',
2c3a6c0a
DM
394 'VM.PowerMgmt',
395 ],
396 audit => [
82b63965 397 'VM.Audit',
2c3a6c0a
DM
398 ],
399 },
400 Sys => {
401 root => [
402 'Sys.PowerMgmt',
37d45deb 403 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
404 ],
405 admin => [
2e376c58 406 'Permissions.Modify',
2c3a6c0a
DM
407 'Sys.Console',
408 'Sys.Syslog',
409 ],
410 user => [],
411 audit => [
412 'Sys.Audit',
413 ],
414 },
415 Datastore => {
2e376c58 416 root => [],
19f60b5e
DM
417 admin => [
418 'Datastore.Allocate',
373cb383 419 'Datastore.AllocateTemplate',
19f60b5e 420 ],
2c3a6c0a
DM
421 user => [
422 'Datastore.AllocateSpace',
423 ],
424 audit => [
425 'Datastore.Audit',
426 ],
427 },
12683df7 428 User => {
82b63965
DM
429 root => [
430 'Realm.Allocate',
431 ],
12683df7
DM
432 admin => [
433 'User.Modify',
82b63965
DM
434 'Group.Allocate', # edit/change group settings
435 'Realm.AllocateUser',
19f60b5e 436 ],
12683df7
DM
437 user => [],
438 audit => [],
439 },
dee1c882
DM
440 Pool => {
441 root => [],
442 admin => [
443 'Pool.Allocate', # create/delete pools
444 ],
445 user => [],
446 audit => [],
447 },
2c3a6c0a
DM
448};
449
450my $valid_privs = {};
451
452my $special_roles = {
453 'NoAccess' => {}, # no priviledges
454 'Administrator' => $valid_privs, # all priviledges
455};
456
457sub create_roles {
458
459 foreach my $cat (keys %$privgroups) {
460 my $cd = $privgroups->{$cat};
461 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
462 @{$cd->{user}}, @{$cd->{audit}}) {
463 $valid_privs->{$p} = 1;
464 }
465 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
466
467 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
468 $special_roles->{"PVEAdmin"}->{$p} = 1;
469 }
470 if (scalar(@{$cd->{user}})) {
471 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
472 $special_roles->{"PVE${cat}User"}->{$p} = 1;
473 }
474 }
475 foreach my $p (@{$cd->{audit}}) {
476 $special_roles->{"PVEAuditor"}->{$p} = 1;
477 }
478 }
ff4b2235 479
7b395f99 480 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
481};
482
483create_roles();
484
2c3a6c0a
DM
485sub add_role_privs {
486 my ($role, $usercfg, $privs) = @_;
487
488 return if !$privs;
489
490 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
491
492 foreach my $priv (split_list($privs)) {
493 if (defined ($valid_privs->{$priv})) {
494 $usercfg->{roles}->{$role}->{$priv} = 1;
495 } else {
496 die "invalid priviledge '$priv'\n";
497 }
498 }
499}
500
501sub normalize_path {
502 my $path = shift;
503
4bc17477 504 $path =~ s|/+|/|g;
2c3a6c0a
DM
505
506 $path =~ s|/$||;
507
508 $path = '/' if !$path;
509
4bc17477
DM
510 $path = "/$path" if $path !~ m|^/|;
511
2c3a6c0a
DM
512 return undef if $path !~ m|^[[:alnum:]\-\_\/]+$|;
513
514 return $path;
515}
516
2c3a6c0a
DM
517
518PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
519sub verify_groupname {
520 my ($groupname, $noerr) = @_;
521
522 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
523
524 die "group name '$groupname' contains invalid characters\n" if !$noerr;
525
526 return undef;
527 }
528
529 return $groupname;
530}
531
532PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
533sub verify_rolename {
534 my ($rolename, $noerr) = @_;
535
536 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
537
538 die "role name '$rolename' contains invalid characters\n" if !$noerr;
539
540 return undef;
541 }
542
543 return $rolename;
544}
545
39c85db8
DM
546PVE::JSONSchema::register_format('pve-poolid', \&verify_groupname);
547sub verify_poolname {
548 my ($poolname, $noerr) = @_;
549
550 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
551
552 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
553
554 return undef;
555 }
556
557 return $poolname;
558}
559
2c3a6c0a
DM
560PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
561sub verify_privname {
562 my ($priv, $noerr) = @_;
563
564 if (!$valid_privs->{$priv}) {
565 die "invalid priviledge '$priv'\n" if !$noerr;
566
567 return undef;
568 }
569
570 return $priv;
571}
572
573sub userconfig_force_defaults {
574 my ($cfg) = @_;
575
576 foreach my $r (keys %$special_roles) {
577 $cfg->{roles}->{$r} = $special_roles->{$r};
578 }
579
580 # fixme: remove 'root' group (not required)?
581
582 # add root user
583 $cfg->{users}->{'root@pam'}->{enable} = 1;
584}
585
586sub parse_user_config {
587 my ($filename, $raw) = @_;
588
589 my $cfg = {};
590
591 userconfig_force_defaults($cfg);
592
593 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
594 my $line = $1;
595
596 next if $line =~ m/^\s*$/; # skip empty lines
597
598 my @data;
599
600 foreach my $d (split (/:/, $line)) {
601 $d =~ s/^\s+//;
602 $d =~ s/\s+$//;
603 push @data, $d
604 }
605
606 my $et = shift @data;
607
608 if ($et eq 'user') {
609 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment) = @data;
610
5bb4e06a 611 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
612 if (!$realm) {
613 warn "user config - ignore user '$user' - invalid user name\n";
614 next;
615 }
616
617 $enable = $enable ? 1 : 0;
618
619 $expire = 0 if !$expire;
620
621 if ($expire !~ m/^\d+$/) {
622 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
623 next;
624 }
625 $expire = int($expire);
626
627 #if (!verify_groupname ($group, 1)) {
628 # warn "user config - ignore user '$user' - invalid characters in group name\n";
629 # next;
630 #}
631
632 $cfg->{users}->{$user} = {
633 enable => $enable,
634 # group => $group,
635 };
636 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
637 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
638 $cfg->{users}->{$user}->{email} = $email;
639 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
640 $cfg->{users}->{$user}->{expire} = $expire;
641
642 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
643 #$cfg->{groups}->{$group}->{$user} = 1;
644
645 } elsif ($et eq 'group') {
646 my ($group, $userlist, $comment) = @data;
647
648 if (!verify_groupname($group, 1)) {
649 warn "user config - ignore group '$group' - invalid characters in group name\n";
650 next;
651 }
652
653 # make sure to add the group (even if there are no members)
654 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
655
656 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
657
658 foreach my $user (split_list($userlist)) {
659
5bb4e06a 660 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
2c3a6c0a
DM
661 warn "user config - ignore invalid group member '$user'\n";
662 next;
663 }
664
665 if ($cfg->{users}->{$user}) { # user exists
666 $cfg->{users}->{$user}->{groups}->{$group} = 1;
667 $cfg->{groups}->{$group}->{users}->{$user} = 1;
668 } else {
669 warn "user config - ignore invalid group member '$user'\n";
670 }
671 }
672
673 } elsif ($et eq 'role') {
674 my ($role, $privlist) = @data;
675
676 if (!verify_rolename($role, 1)) {
677 warn "user config - ignore role '$role' - invalid characters in role name\n";
678 next;
679 }
680
681 # make sure to add the role (even if there are no privileges)
682 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
683
684 foreach my $priv (split_list($privlist)) {
685 if (defined ($valid_privs->{$priv})) {
686 $cfg->{roles}->{$role}->{$priv} = 1;
687 } else {
688 warn "user config - ignore invalid priviledge '$priv'\n";
689 }
690 }
691
692 } elsif ($et eq 'acl') {
693 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
694
695 if (my $path = normalize_path($pathtxt)) {
696 foreach my $role (split_list($rolelist)) {
697
698 if (!verify_rolename($role, 1)) {
699 warn "user config - ignore invalid role name '$role' in acl\n";
700 next;
701 }
702
703 foreach my $ug (split_list($uglist)) {
9b217226 704 if ($ug =~ m/^@(\S+)$/) {
2c3a6c0a
DM
705 my $group = $1;
706 if ($cfg->{groups}->{$group}) { # group exists
707 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
708 } else {
709 warn "user config - ignore invalid acl group '$group'\n";
710 }
5bb4e06a 711 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
2c3a6c0a
DM
712 if ($cfg->{users}->{$ug}) { # user exists
713 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
714 } else {
715 warn "user config - ignore invalid acl member '$ug'\n";
716 }
717 } else {
718 warn "user config - invalid user/group '$ug' in acl\n";
719 }
720 }
721 }
722 } else {
723 warn "user config - ignore invalid path in acl '$pathtxt'\n";
724 }
4bc17477 725 } elsif ($et eq 'pool') {
39c85db8 726 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 727
39c85db8
DM
728 if (!verify_poolname($pool, 1)) {
729 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
730 next;
731 }
4bc17477 732
39c85db8
DM
733 # make sure to add the pool (even if there are no members)
734 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 735
39c85db8 736 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 737
39c85db8
DM
738 foreach my $vmid (split_list($vmlist)) {
739 if ($vmid !~ m/^\d+$/) {
740 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
741 next;
4bc17477 742 }
39c85db8 743 $vmid = int($vmid);
4bc17477 744
39c85db8
DM
745 if ($cfg->{vms}->{$vmid}) {
746 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
747 next;
4bc17477
DM
748 }
749
39c85db8
DM
750 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
751
752 # record vmid ==> pool relation
753 $cfg->{vms}->{$vmid} = $pool;
754 }
755
756 foreach my $storeid (split_list($storelist)) {
757 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
758 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
759 next;
760 }
761 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
4bc17477 762 }
2c3a6c0a
DM
763 } else {
764 warn "user config - ignore config line: $line\n";
765 }
766 }
767
768 userconfig_force_defaults($cfg);
769
770 return $cfg;
771}
772
2c3a6c0a
DM
773sub write_user_config {
774 my ($filename, $cfg) = @_;
775
776 my $data = '';
777
778 foreach my $user (keys %{$cfg->{users}}) {
2c3a6c0a
DM
779 my $d = $cfg->{users}->{$user};
780 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
781 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
782 my $email = $d->{email} || '';
783 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 784 my $expire = int($d->{expire} || 0);
2c3a6c0a
DM
785 my $enable = $d->{enable} ? 1 : 0;
786 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:\n";
787 }
788
789 $data .= "\n";
790
791 foreach my $group (keys %{$cfg->{groups}}) {
792 my $d = $cfg->{groups}->{$group};
793 my $list = join (',', keys %{$d->{users}});
794 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
795 $data .= "group:$group:$list:$comment:\n";
796 }
797
798 $data .= "\n";
799
39c85db8
DM
800 foreach my $pool (keys %{$cfg->{pools}}) {
801 my $d = $cfg->{pools}->{$pool};
4bc17477
DM
802 my $vmlist = join (',', keys %{$d->{vms}});
803 my $storelist = join (',', keys %{$d->{storage}});
804 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 805 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
806 }
807
808 $data .= "\n";
809
2c3a6c0a
DM
810 foreach my $role (keys %{$cfg->{roles}}) {
811 next if $special_roles->{$role};
812
813 my $d = $cfg->{roles}->{$role};
814 my $list = join (',', keys %$d);
815 $data .= "role:$role:$list:\n";
816 }
817
818 $data .= "\n";
819
820 foreach my $path (sort keys %{$cfg->{acl}}) {
821 my $d = $cfg->{acl}->{$path};
822
823 my $ra = {};
824
825 foreach my $group (keys %{$d->{groups}}) {
826 my $l0 = '';
827 my $l1 = '';
828 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
829 my $propagate = $d->{groups}->{$group}->{$role};
830 if ($propagate) {
831 $l1 .= ',' if $l1;
832 $l1 .= $role;
833 } else {
834 $l0 .= ',' if $l0;
835 $l0 .= $role;
836 }
837 }
838 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
839 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
840 }
841
842 foreach my $user (keys %{$d->{users}}) {
843 # no need to save, because root is always 'Administartor'
844 next if $user eq 'root@pam';
845
846 my $l0 = '';
847 my $l1 = '';
848 foreach my $role (sort keys %{$d->{users}->{$user}}) {
849 my $propagate = $d->{users}->{$user}->{$role};
850 if ($propagate) {
851 $l1 .= ',' if $l1;
852 $l1 .= $role;
853 } else {
854 $l0 .= ',' if $l0;
855 $l0 .= $role;
856 }
857 }
858 $ra->{0}->{$l0}->{$user} = 1 if $l0;
859 $ra->{1}->{$l1}->{$user} = 1 if $l1;
860 }
861
862 foreach my $rolelist (sort keys %{$ra->{0}}) {
863 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
864 $data .= "acl:0:$path:$uglist:$rolelist:\n";
865 }
866 foreach my $rolelist (sort keys %{$ra->{1}}) {
867 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
868 $data .= "acl:1:$path:$uglist:$rolelist:\n";
869 }
870 }
871
872 return $data;
873}
874
875sub roles {
876 my ($cfg, $user, $path) = @_;
877
4bc17477
DM
878 # NOTE: we do not consider pools here.
879 # You need to use $rpcenv->roles() instead if you want that.
880
2c3a6c0a
DM
881 return 'Administrator' if $user eq 'root@pam'; # root can do anything
882
883 my $perm = {};
884
885 foreach my $p (sort keys %{$cfg->{acl}}) {
886 my $final = ($path eq $p);
887
888 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
889
890 my $acl = $cfg->{acl}->{$p};
891
892 #print "CHECKACL $path $p\n";
893 #print "ACL $path = " . Dumper ($acl);
894
895 if (my $ri = $acl->{users}->{$user}) {
896 my $new;
897 foreach my $role (keys %$ri) {
898 my $propagate = $ri->{$role};
899 if ($final || $propagate) {
900 #print "APPLY ROLE $p $user $role\n";
901 $new = {} if !$new;
902 $new->{$role} = 1;
903 }
904 }
905 if ($new) {
906 $perm = $new; # overwrite previous settings
907 next; # user privs always override group privs
908 }
909 }
910
911 my $new;
912 foreach my $g (keys %{$acl->{groups}}) {
913 next if !$cfg->{groups}->{$g}->{users}->{$user};
914 if (my $ri = $acl->{groups}->{$g}) {
915 foreach my $role (keys %$ri) {
916 my $propagate = $ri->{$role};
917 if ($final || $propagate) {
918 #print "APPLY ROLE $p \@$g $role\n";
919 $new = {} if !$new;
920 $new->{$role} = 1;
921 }
922 }
923 }
924 }
925 if ($new) {
926 $perm = $new; # overwrite previous settings
927 next;
928 }
2c3a6c0a
DM
929 }
930
4bc17477
DM
931 return ('NoAccess') if defined ($perm->{NoAccess});
932 #return () if defined ($perm->{NoAccess});
2c3a6c0a
DM
933
934 #print "permission $user $path = " . Dumper ($perm);
935
4bc17477 936 my @ra = keys %$perm;
2c3a6c0a
DM
937
938 #print "roles $user $path = " . join (',', @ra) . "\n";
939
940 return @ra;
941}
942
943sub permission {
944 my ($cfg, $user, $path) = @_;
945
5bb4e06a 946 $user = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
947 return {} if !$user;
948
949 my @ra = roles($cfg, $user, $path);
950
951 my $privs = {};
952
953 foreach my $role (@ra) {
954 if (my $privset = $cfg->{roles}->{$role}) {
955 foreach my $p (keys %$privset) {
956 $privs->{$p} = 1;
957 }
958 }
959 }
960
961 #print "priviledges $user $path = " . Dumper ($privs);
962
963 return $privs;
964}
965
966sub check_permissions {
967 my ($username, $path, $privlist) = @_;
968
969 $path = normalize_path($path);
970 my $usercfg = cfs_read_file('user.cfg');
971 my $perm = permission($usercfg, $username, $path);
972
973 foreach my $priv (split_list($privlist)) {
974 return undef if !$perm->{$priv};
975 };
976
977 return 1;
978}
979
018ae3a9
DM
980sub add_vm_to_pool {
981 my ($vmid, $pool) = @_;
982
983 my $addVMtoPoolFn = sub {
984 my $usercfg = cfs_read_file("user.cfg");
985 if (my $data = $usercfg->{pools}->{$pool}) {
986 $data->{vms}->{$vmid} = 1;
987 $usercfg->{vms}->{$vmid} = $pool;
988 cfs_write_file("user.cfg", $usercfg);
989 }
990 };
991
992 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
993}
994
995sub remove_vm_from_pool {
996 my ($vmid) = @_;
997
998 my $delVMfromPoolFn = sub {
999 my $usercfg = cfs_read_file("user.cfg");
1000 if (my $pool = $usercfg->{vms}->{$vmid}) {
1001 if (my $data = $usercfg->{pools}->{$pool}) {
1002 delete $data->{vms}->{$vmid};
1003 delete $usercfg->{vms}->{$vmid};
1004 cfs_write_file("user.cfg", $usercfg);
1005 }
1006 }
1007 };
1008
1009 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1010}
1011
2c3a6c0a 10121;