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