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