bump version to 3.0-5
[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 216sub assemble_spice_ticket {
bf3e6d31 217 my ($username, $vmid, $node) = @_;
23b35225
AD
218
219 my $rsa_priv = get_privkey();
220
bf3e6d31 221 my $timestamp = sprintf("%08x", time());
23b35225 222
bf3e6d31 223 my $randomstr = "PVESPICE:$timestamp:$vmid:$node:" . rand(10);
23b35225 224
bf3e6d31
DM
225 # this should be uses as one-time password
226 # max length is 60 chars (spice limit)
227 # we pass this to qemu set_pasword and limit lifetime there
228 # keep this secret
229 my $ticket = Digest::SHA::sha1_hex($rsa_priv->sign($randomstr));
23b35225 230
bf3e6d31
DM
231 # Note: spice proxy connects with HTTP, so $proxyticket is exposed to public
232 # we use a signature/timestamp to make sure nobody can fake such ticket
233 # an attacker can use this $proxyticket, but he will fail because $ticket is
234 # private.
235 # The proxy need to be able to extract/verify the ticket
236 # Note: data needs to be lower case only, because virt-viewer needs that
237 my $plain = "pvespiceproxy:$timestamp:$vmid:$node";
238 my $sig = unpack("H*", $rsa_priv->sign($plain));
23b35225 239
bf3e6d31 240 my $proxyticket = $plain . "::" . $sig;
83d1f13e 241
bf3e6d31
DM
242 return ($ticket, $proxyticket);
243}
244
245sub verify_spice_connect_url {
246 my ($connect_str) = @_;
247
248 # Note: we pass the spice ticket as 'host', so the
249 # spice viewer connects with "$ticket:$port"
250
251 return undef if !$connect_str;
252
253 if ($connect_str =~m/^pvespiceproxy:([a-z0-9]{8}):(\d+):(\S+)::([a-z0-9]{512}):(\d+)$/) {
254 my ($timestamp, $vmid, $node, $hexsig, $port) = ($1, $2, $3, $4, $5, $6);
255 my $ttime = hex($timestamp);
256 my $age = time() - $ttime;
257
258 # use very limited lifetime - is this enough?
259 return undef if !(($age > -20) && ($age < 40));
260
261 my $sig = pack("H*", $hexsig);
262
263 my $rsa_pub = get_pubkey();
264
265 my $plain = "pvespiceproxy:$timestamp:$vmid:$node";
266
267 if ($rsa_pub->verify($plain, $sig)) {
268 return ($vmid, $node, $port);
269 }
270 }
271
272 return undef;
23b35225
AD
273}
274
37d45deb 275sub check_user_exist {
7070c1ae 276 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 277
5bb4e06a 278 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a
DM
279 return undef if !$username;
280
37d45deb
DM
281 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
282
283 die "no such user ('$username')\n" if !$noerr;
284
285 return undef;
286}
287
288sub check_user_enabled {
289 my ($usercfg, $username, $noerr) = @_;
290
291 my $data = check_user_exist($usercfg, $username, $noerr);
292 return undef if !$data;
293
294 return 1 if $data->{enable};
2c3a6c0a
DM
295
296 return 1 if $username eq 'root@pam'; # root is always enabled
297
37d45deb 298 die "user '$username' is disabled\n" if !$noerr;
7070c1ae
DM
299
300 return undef;
2c3a6c0a
DM
301}
302
303# password should be utf8 encoded
304sub authenticate_user {
305 my ($username, $password) = @_;
306
307 die "no username specified\n" if !$username;
308
5bb4e06a 309 my ($ruid, $realm);
2c3a6c0a 310
5bb4e06a 311 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
2c3a6c0a
DM
312
313 my $usercfg = cfs_read_file('user.cfg');
314
7070c1ae
DM
315 eval { check_user_enabled($usercfg, $username); };
316 if (my $err = $@) {
2c3a6c0a 317 sleep(2);
7070c1ae 318 die $err;
2c3a6c0a
DM
319 }
320
321 my $ctime = time();
322 my $expire = $usercfg->{users}->{$username}->{expire};
323
324 if ($expire && ($expire < $ctime)) {
325 sleep(2);
326 die "account expired\n"
327 }
328
5bb4e06a 329 my $domain_cfg = cfs_read_file('domains.cfg');
2c3a6c0a 330
5bb4e06a
DM
331 eval {
332 my $cfg = $domain_cfg->{ids}->{$realm};
333 die "auth domain '$realm' does not exists\n" if !$cfg;
334 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
335 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
336 };
337 if (my $err = $@) {
338 sleep(2); # timeout after failed auth
339 die $err;
340 }
2c3a6c0a 341
5bb4e06a 342 return $username;
2c3a6c0a
DM
343}
344
345sub domain_set_password {
5bb4e06a 346 my ($realm, $username, $password) = @_;
2c3a6c0a
DM
347
348 die "no auth domain specified" if !$realm;
349
5bb4e06a
DM
350 my $domain_cfg = cfs_read_file('domains.cfg');
351
352 my $cfg = $domain_cfg->{ids}->{$realm};
353 die "auth domain '$realm' does not exists\n" if !$cfg;
354 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
355 $plugin->store_password($cfg, $realm, $username, $password);
2c3a6c0a
DM
356}
357
358sub add_user_group {
359
360 my ($username, $usercfg, $group) = @_;
361 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
362 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
363}
364
365sub delete_user_group {
366
367 my ($username, $usercfg) = @_;
368
369 foreach my $group (keys %{$usercfg->{groups}}) {
370
371 delete ($usercfg->{groups}->{$group}->{users}->{$username})
372 if $usercfg->{groups}->{$group}->{users}->{$username};
373 }
374}
375
376sub delete_user_acl {
377
378 my ($username, $usercfg) = @_;
379
380 foreach my $acl (keys %{$usercfg->{acl}}) {
381
382 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
383 if $usercfg->{acl}->{$acl}->{users}->{$username};
384 }
2c3a6c0a 385}
39c85db8 386
2c3a6c0a
DM
387sub delete_group_acl {
388
389 my ($group, $usercfg) = @_;
390
391 foreach my $acl (keys %{$usercfg->{acl}}) {
392
393 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
394 if $usercfg->{acl}->{$acl}->{groups}->{$group};
395 }
39c85db8
DM
396}
397
398sub delete_pool_acl {
399
400 my ($pool, $usercfg) = @_;
2c3a6c0a 401
39c85db8
DM
402 my $path = "/pool/$pool";
403
404 foreach my $aclpath (keys %{$usercfg->{acl}}) {
405 delete ($usercfg->{acl}->{$aclpath})
406 if $usercfg->{acl}->{$aclpath} eq 'path';
407 }
2c3a6c0a
DM
408}
409
410# we automatically create some predefined roles by splitting privs
411# into 3 groups (per category)
412# root: only root is allowed to do that
413# admin: an administrator can to that
414# user: a normak user/customer can to that
415my $privgroups = {
416 VM => {
417 root => [],
418 admin => [
c0fead8c 419 'VM.Config.Disk',
c0fead8c
DM
420 'VM.Config.CPU',
421 'VM.Config.Memory',
422 'VM.Config.Network',
423 'VM.Config.HWType',
424 'VM.Config.Options', # covers all other things
2c3a6c0a 425 'VM.Allocate',
7b395f99 426 'VM.Clone',
2c3a6c0a 427 'VM.Migrate',
c0fead8c 428 'VM.Monitor',
e3e6510c 429 'VM.Snapshot',
2c3a6c0a
DM
430 ],
431 user => [
cc7bdf33 432 'VM.Config.CDROM', # change CDROM media
2c3a6c0a 433 'VM.Console',
68d5a86d 434 'VM.Backup',
2c3a6c0a
DM
435 'VM.PowerMgmt',
436 ],
437 audit => [
82b63965 438 'VM.Audit',
2c3a6c0a
DM
439 ],
440 },
441 Sys => {
442 root => [
443 'Sys.PowerMgmt',
37d45deb 444 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
445 ],
446 admin => [
2e376c58 447 'Permissions.Modify',
2c3a6c0a
DM
448 'Sys.Console',
449 'Sys.Syslog',
450 ],
451 user => [],
452 audit => [
453 'Sys.Audit',
454 ],
455 },
456 Datastore => {
2e376c58 457 root => [],
19f60b5e
DM
458 admin => [
459 'Datastore.Allocate',
373cb383 460 'Datastore.AllocateTemplate',
19f60b5e 461 ],
2c3a6c0a
DM
462 user => [
463 'Datastore.AllocateSpace',
464 ],
465 audit => [
466 'Datastore.Audit',
467 ],
468 },
12683df7 469 User => {
82b63965
DM
470 root => [
471 'Realm.Allocate',
472 ],
12683df7
DM
473 admin => [
474 'User.Modify',
82b63965
DM
475 'Group.Allocate', # edit/change group settings
476 'Realm.AllocateUser',
19f60b5e 477 ],
12683df7
DM
478 user => [],
479 audit => [],
480 },
dee1c882
DM
481 Pool => {
482 root => [],
483 admin => [
484 'Pool.Allocate', # create/delete pools
485 ],
486 user => [],
487 audit => [],
488 },
2c3a6c0a
DM
489};
490
491my $valid_privs = {};
492
493my $special_roles = {
494 'NoAccess' => {}, # no priviledges
495 'Administrator' => $valid_privs, # all priviledges
496};
497
498sub create_roles {
499
500 foreach my $cat (keys %$privgroups) {
501 my $cd = $privgroups->{$cat};
502 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
503 @{$cd->{user}}, @{$cd->{audit}}) {
504 $valid_privs->{$p} = 1;
505 }
506 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
507
508 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
509 $special_roles->{"PVEAdmin"}->{$p} = 1;
510 }
511 if (scalar(@{$cd->{user}})) {
512 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
513 $special_roles->{"PVE${cat}User"}->{$p} = 1;
514 }
515 }
516 foreach my $p (@{$cd->{audit}}) {
517 $special_roles->{"PVEAuditor"}->{$p} = 1;
518 }
519 }
ff4b2235 520
7b395f99 521 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
522};
523
524create_roles();
525
2c3a6c0a
DM
526sub add_role_privs {
527 my ($role, $usercfg, $privs) = @_;
528
529 return if !$privs;
530
531 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
532
533 foreach my $priv (split_list($privs)) {
534 if (defined ($valid_privs->{$priv})) {
535 $usercfg->{roles}->{$role}->{$priv} = 1;
536 } else {
537 die "invalid priviledge '$priv'\n";
538 }
539 }
540}
541
542sub normalize_path {
543 my $path = shift;
544
4bc17477 545 $path =~ s|/+|/|g;
2c3a6c0a
DM
546
547 $path =~ s|/$||;
548
549 $path = '/' if !$path;
550
4bc17477
DM
551 $path = "/$path" if $path !~ m|^/|;
552
2c3a6c0a
DM
553 return undef if $path !~ m|^[[:alnum:]\-\_\/]+$|;
554
555 return $path;
556}
557
2c3a6c0a
DM
558
559PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
560sub verify_groupname {
561 my ($groupname, $noerr) = @_;
562
563 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
564
565 die "group name '$groupname' contains invalid characters\n" if !$noerr;
566
567 return undef;
568 }
569
570 return $groupname;
571}
572
573PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
574sub verify_rolename {
575 my ($rolename, $noerr) = @_;
576
577 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
578
579 die "role name '$rolename' contains invalid characters\n" if !$noerr;
580
581 return undef;
582 }
583
584 return $rolename;
585}
586
39c85db8
DM
587PVE::JSONSchema::register_format('pve-poolid', \&verify_groupname);
588sub verify_poolname {
589 my ($poolname, $noerr) = @_;
590
591 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
592
593 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
594
595 return undef;
596 }
597
598 return $poolname;
599}
600
2c3a6c0a
DM
601PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
602sub verify_privname {
603 my ($priv, $noerr) = @_;
604
605 if (!$valid_privs->{$priv}) {
606 die "invalid priviledge '$priv'\n" if !$noerr;
607
608 return undef;
609 }
610
611 return $priv;
612}
613
614sub userconfig_force_defaults {
615 my ($cfg) = @_;
616
617 foreach my $r (keys %$special_roles) {
618 $cfg->{roles}->{$r} = $special_roles->{$r};
619 }
620
621 # fixme: remove 'root' group (not required)?
622
623 # add root user
624 $cfg->{users}->{'root@pam'}->{enable} = 1;
625}
626
627sub parse_user_config {
628 my ($filename, $raw) = @_;
629
630 my $cfg = {};
631
632 userconfig_force_defaults($cfg);
633
634 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
635 my $line = $1;
636
637 next if $line =~ m/^\s*$/; # skip empty lines
638
639 my @data;
640
641 foreach my $d (split (/:/, $line)) {
642 $d =~ s/^\s+//;
643 $d =~ s/\s+$//;
644 push @data, $d
645 }
646
647 my $et = shift @data;
648
649 if ($et eq 'user') {
650 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment) = @data;
651
5bb4e06a 652 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
653 if (!$realm) {
654 warn "user config - ignore user '$user' - invalid user name\n";
655 next;
656 }
657
658 $enable = $enable ? 1 : 0;
659
660 $expire = 0 if !$expire;
661
662 if ($expire !~ m/^\d+$/) {
663 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
664 next;
665 }
666 $expire = int($expire);
667
668 #if (!verify_groupname ($group, 1)) {
669 # warn "user config - ignore user '$user' - invalid characters in group name\n";
670 # next;
671 #}
672
673 $cfg->{users}->{$user} = {
674 enable => $enable,
675 # group => $group,
676 };
677 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
678 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
679 $cfg->{users}->{$user}->{email} = $email;
680 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
681 $cfg->{users}->{$user}->{expire} = $expire;
682
683 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
684 #$cfg->{groups}->{$group}->{$user} = 1;
685
686 } elsif ($et eq 'group') {
687 my ($group, $userlist, $comment) = @data;
688
689 if (!verify_groupname($group, 1)) {
690 warn "user config - ignore group '$group' - invalid characters in group name\n";
691 next;
692 }
693
694 # make sure to add the group (even if there are no members)
695 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
696
697 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
698
699 foreach my $user (split_list($userlist)) {
700
5bb4e06a 701 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
2c3a6c0a
DM
702 warn "user config - ignore invalid group member '$user'\n";
703 next;
704 }
705
706 if ($cfg->{users}->{$user}) { # user exists
707 $cfg->{users}->{$user}->{groups}->{$group} = 1;
708 $cfg->{groups}->{$group}->{users}->{$user} = 1;
709 } else {
710 warn "user config - ignore invalid group member '$user'\n";
711 }
712 }
713
714 } elsif ($et eq 'role') {
715 my ($role, $privlist) = @data;
716
717 if (!verify_rolename($role, 1)) {
718 warn "user config - ignore role '$role' - invalid characters in role name\n";
719 next;
720 }
721
722 # make sure to add the role (even if there are no privileges)
723 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
724
725 foreach my $priv (split_list($privlist)) {
726 if (defined ($valid_privs->{$priv})) {
727 $cfg->{roles}->{$role}->{$priv} = 1;
728 } else {
729 warn "user config - ignore invalid priviledge '$priv'\n";
730 }
731 }
732
733 } elsif ($et eq 'acl') {
734 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
735
736 if (my $path = normalize_path($pathtxt)) {
737 foreach my $role (split_list($rolelist)) {
738
739 if (!verify_rolename($role, 1)) {
740 warn "user config - ignore invalid role name '$role' in acl\n";
741 next;
742 }
743
744 foreach my $ug (split_list($uglist)) {
9b217226 745 if ($ug =~ m/^@(\S+)$/) {
2c3a6c0a
DM
746 my $group = $1;
747 if ($cfg->{groups}->{$group}) { # group exists
748 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
749 } else {
750 warn "user config - ignore invalid acl group '$group'\n";
751 }
5bb4e06a 752 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
2c3a6c0a
DM
753 if ($cfg->{users}->{$ug}) { # user exists
754 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
755 } else {
756 warn "user config - ignore invalid acl member '$ug'\n";
757 }
758 } else {
759 warn "user config - invalid user/group '$ug' in acl\n";
760 }
761 }
762 }
763 } else {
764 warn "user config - ignore invalid path in acl '$pathtxt'\n";
765 }
4bc17477 766 } elsif ($et eq 'pool') {
39c85db8 767 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 768
39c85db8
DM
769 if (!verify_poolname($pool, 1)) {
770 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
771 next;
772 }
4bc17477 773
39c85db8
DM
774 # make sure to add the pool (even if there are no members)
775 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 776
39c85db8 777 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 778
39c85db8
DM
779 foreach my $vmid (split_list($vmlist)) {
780 if ($vmid !~ m/^\d+$/) {
781 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
782 next;
4bc17477 783 }
39c85db8 784 $vmid = int($vmid);
4bc17477 785
39c85db8
DM
786 if ($cfg->{vms}->{$vmid}) {
787 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
788 next;
4bc17477
DM
789 }
790
39c85db8
DM
791 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
792
793 # record vmid ==> pool relation
794 $cfg->{vms}->{$vmid} = $pool;
795 }
796
797 foreach my $storeid (split_list($storelist)) {
798 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
799 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
800 next;
801 }
802 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
4bc17477 803 }
2c3a6c0a
DM
804 } else {
805 warn "user config - ignore config line: $line\n";
806 }
807 }
808
809 userconfig_force_defaults($cfg);
810
811 return $cfg;
812}
813
2c3a6c0a
DM
814sub write_user_config {
815 my ($filename, $cfg) = @_;
816
817 my $data = '';
818
819 foreach my $user (keys %{$cfg->{users}}) {
2c3a6c0a
DM
820 my $d = $cfg->{users}->{$user};
821 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
822 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
823 my $email = $d->{email} || '';
824 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 825 my $expire = int($d->{expire} || 0);
2c3a6c0a
DM
826 my $enable = $d->{enable} ? 1 : 0;
827 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:\n";
828 }
829
830 $data .= "\n";
831
832 foreach my $group (keys %{$cfg->{groups}}) {
833 my $d = $cfg->{groups}->{$group};
834 my $list = join (',', keys %{$d->{users}});
835 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
836 $data .= "group:$group:$list:$comment:\n";
837 }
838
839 $data .= "\n";
840
39c85db8
DM
841 foreach my $pool (keys %{$cfg->{pools}}) {
842 my $d = $cfg->{pools}->{$pool};
4bc17477
DM
843 my $vmlist = join (',', keys %{$d->{vms}});
844 my $storelist = join (',', keys %{$d->{storage}});
845 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 846 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
847 }
848
849 $data .= "\n";
850
2c3a6c0a
DM
851 foreach my $role (keys %{$cfg->{roles}}) {
852 next if $special_roles->{$role};
853
854 my $d = $cfg->{roles}->{$role};
855 my $list = join (',', keys %$d);
856 $data .= "role:$role:$list:\n";
857 }
858
859 $data .= "\n";
860
861 foreach my $path (sort keys %{$cfg->{acl}}) {
862 my $d = $cfg->{acl}->{$path};
863
864 my $ra = {};
865
866 foreach my $group (keys %{$d->{groups}}) {
867 my $l0 = '';
868 my $l1 = '';
869 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
870 my $propagate = $d->{groups}->{$group}->{$role};
871 if ($propagate) {
872 $l1 .= ',' if $l1;
873 $l1 .= $role;
874 } else {
875 $l0 .= ',' if $l0;
876 $l0 .= $role;
877 }
878 }
879 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
880 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
881 }
882
883 foreach my $user (keys %{$d->{users}}) {
884 # no need to save, because root is always 'Administartor'
885 next if $user eq 'root@pam';
886
887 my $l0 = '';
888 my $l1 = '';
889 foreach my $role (sort keys %{$d->{users}->{$user}}) {
890 my $propagate = $d->{users}->{$user}->{$role};
891 if ($propagate) {
892 $l1 .= ',' if $l1;
893 $l1 .= $role;
894 } else {
895 $l0 .= ',' if $l0;
896 $l0 .= $role;
897 }
898 }
899 $ra->{0}->{$l0}->{$user} = 1 if $l0;
900 $ra->{1}->{$l1}->{$user} = 1 if $l1;
901 }
902
903 foreach my $rolelist (sort keys %{$ra->{0}}) {
904 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
905 $data .= "acl:0:$path:$uglist:$rolelist:\n";
906 }
907 foreach my $rolelist (sort keys %{$ra->{1}}) {
908 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
909 $data .= "acl:1:$path:$uglist:$rolelist:\n";
910 }
911 }
912
913 return $data;
914}
915
916sub roles {
917 my ($cfg, $user, $path) = @_;
918
4bc17477
DM
919 # NOTE: we do not consider pools here.
920 # You need to use $rpcenv->roles() instead if you want that.
921
2c3a6c0a
DM
922 return 'Administrator' if $user eq 'root@pam'; # root can do anything
923
924 my $perm = {};
925
926 foreach my $p (sort keys %{$cfg->{acl}}) {
927 my $final = ($path eq $p);
928
929 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
930
931 my $acl = $cfg->{acl}->{$p};
932
933 #print "CHECKACL $path $p\n";
934 #print "ACL $path = " . Dumper ($acl);
935
936 if (my $ri = $acl->{users}->{$user}) {
937 my $new;
938 foreach my $role (keys %$ri) {
939 my $propagate = $ri->{$role};
940 if ($final || $propagate) {
941 #print "APPLY ROLE $p $user $role\n";
942 $new = {} if !$new;
943 $new->{$role} = 1;
944 }
945 }
946 if ($new) {
947 $perm = $new; # overwrite previous settings
948 next; # user privs always override group privs
949 }
950 }
951
952 my $new;
953 foreach my $g (keys %{$acl->{groups}}) {
954 next if !$cfg->{groups}->{$g}->{users}->{$user};
955 if (my $ri = $acl->{groups}->{$g}) {
956 foreach my $role (keys %$ri) {
957 my $propagate = $ri->{$role};
958 if ($final || $propagate) {
959 #print "APPLY ROLE $p \@$g $role\n";
960 $new = {} if !$new;
961 $new->{$role} = 1;
962 }
963 }
964 }
965 }
966 if ($new) {
967 $perm = $new; # overwrite previous settings
968 next;
969 }
2c3a6c0a
DM
970 }
971
4bc17477
DM
972 return ('NoAccess') if defined ($perm->{NoAccess});
973 #return () if defined ($perm->{NoAccess});
2c3a6c0a
DM
974
975 #print "permission $user $path = " . Dumper ($perm);
976
4bc17477 977 my @ra = keys %$perm;
2c3a6c0a
DM
978
979 #print "roles $user $path = " . join (',', @ra) . "\n";
980
981 return @ra;
982}
983
984sub permission {
985 my ($cfg, $user, $path) = @_;
986
5bb4e06a 987 $user = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
988 return {} if !$user;
989
990 my @ra = roles($cfg, $user, $path);
991
992 my $privs = {};
993
994 foreach my $role (@ra) {
995 if (my $privset = $cfg->{roles}->{$role}) {
996 foreach my $p (keys %$privset) {
997 $privs->{$p} = 1;
998 }
999 }
1000 }
1001
1002 #print "priviledges $user $path = " . Dumper ($privs);
1003
1004 return $privs;
1005}
1006
1007sub check_permissions {
1008 my ($username, $path, $privlist) = @_;
1009
1010 $path = normalize_path($path);
1011 my $usercfg = cfs_read_file('user.cfg');
1012 my $perm = permission($usercfg, $username, $path);
1013
1014 foreach my $priv (split_list($privlist)) {
1015 return undef if !$perm->{$priv};
1016 };
1017
1018 return 1;
1019}
1020
018ae3a9
DM
1021sub add_vm_to_pool {
1022 my ($vmid, $pool) = @_;
1023
1024 my $addVMtoPoolFn = sub {
1025 my $usercfg = cfs_read_file("user.cfg");
1026 if (my $data = $usercfg->{pools}->{$pool}) {
1027 $data->{vms}->{$vmid} = 1;
1028 $usercfg->{vms}->{$vmid} = $pool;
1029 cfs_write_file("user.cfg", $usercfg);
1030 }
1031 };
1032
1033 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1034}
1035
1036sub remove_vm_from_pool {
1037 my ($vmid) = @_;
1038
1039 my $delVMfromPoolFn = sub {
1040 my $usercfg = cfs_read_file("user.cfg");
1041 if (my $pool = $usercfg->{vms}->{$vmid}) {
1042 if (my $data = $usercfg->{pools}->{$pool}) {
1043 delete $data->{vms}->{$vmid};
1044 delete $usercfg->{vms}->{$vmid};
1045 cfs_write_file("user.cfg", $usercfg);
1046 }
1047 }
1048 };
1049
1050 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1051}
1052
2c3a6c0a 10531;