use User.Allocate instead of User.Add/User.Delete
[pve-access-control.git] / PVE / AccessControl.pm
1 package PVE::AccessControl;
2
3 use strict;
4 use Encode;
5 use Crypt::OpenSSL::Random;
6 use Crypt::OpenSSL::RSA;
7 use MIME::Base64;
8 use Digest::SHA;
9 use Authen::PAM qw(:constants);
10 use Net::LDAP;
11 use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
12 use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
13 use PVE::JSONSchema;
14 use Encode;
15
16 use Data::Dumper; # fixme: remove
17
18 # $authdir must be writable by root only!
19 my $confdir = "/etc/pve";
20 my $authdir = "$confdir/priv";
21 my $authprivkeyfn = "$authdir/authkey.key";
22 my $authpubkeyfn = "$confdir/authkey.pub";
23 my $shadowconfigfile = "priv/shadow.cfg";
24 my $domainconfigfile = "domains.cfg";
25 my $pve_www_key_fn = "$confdir/pve-www.key";
26
27 my $ticket_lifetime = 3600*2; # 2 hours
28
29 Crypt::OpenSSL::RSA->import_random_seed();
30
31 cfs_register_file('user.cfg',
32 \&parse_user_config,
33 \&write_user_config);
34
35 cfs_register_file($shadowconfigfile,
36 \&parse_shadow_passwd,
37 \&write_shadow_config);
38
39 cfs_register_file($domainconfigfile,
40 \&parse_domains,
41 \&write_domains);
42
43
44 sub lock_user_config {
45 my ($code, $errmsg) = @_;
46
47 cfs_lock_file("user.cfg", undef, $code);
48 my $err = $@;
49 if ($err) {
50 $errmsg ? die "$errmsg: $err" : die $err;
51 }
52 }
53
54 sub lock_domain_config {
55 my ($code, $errmsg) = @_;
56
57 cfs_lock_file($domainconfigfile, undef, $code);
58 my $err = $@;
59 if ($err) {
60 $errmsg ? die "$errmsg: $err" : die $err;
61 }
62 }
63
64 sub lock_shadow_config {
65 my ($code, $errmsg) = @_;
66
67 cfs_lock_file($shadowconfigfile, undef, $code);
68 my $err = $@;
69 if ($err) {
70 $errmsg ? die "$errmsg: $err" : die $err;
71 }
72 }
73
74 my $pve_auth_pub_key;
75 sub get_pubkey {
76
77 return $pve_auth_pub_key if $pve_auth_pub_key;
78
79 my $input = PVE::Tools::file_get_contents($authpubkeyfn);
80
81 $pve_auth_pub_key = Crypt::OpenSSL::RSA->new_public_key($input);
82
83 return $pve_auth_pub_key;
84 }
85
86 my $csrf_prevention_secret;
87 my $get_csrfr_secret = sub {
88 if (!$csrf_prevention_secret) {
89 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
90 $csrf_prevention_secret = Digest::SHA::sha1_base64($input);
91 }
92 return $csrf_prevention_secret;
93 };
94
95 sub assemble_csrf_prevention_token {
96 my ($username) = @_;
97
98 my $timestamp = sprintf("%08X", time());
99
100 my $digest = Digest::SHA::sha1_base64("$timestamp:$username", &$get_csrfr_secret());
101
102 return "$timestamp:$digest";
103 }
104
105 sub verify_csrf_prevention_token {
106 my ($username, $token, $noerr) = @_;
107
108 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
109 my $sig = $2;
110 my $timestamp = $1;
111 my $ttime = hex($timestamp);
112
113 my $digest = Digest::SHA::sha1_base64("$timestamp:$username", &$get_csrfr_secret());
114
115 my $age = time() - $ttime;
116 return if ($digest eq $sig) && ($age > -300) && ($age < $ticket_lifetime);
117 }
118
119 die "Permission denied - invalid csrf token\n" if !$noerr;
120
121 return undef;
122 }
123
124 my $pve_auth_priv_key;
125 sub get_privkey {
126
127 return $pve_auth_priv_key if $pve_auth_priv_key;
128
129 my $input = PVE::Tools::file_get_contents($authprivkeyfn);
130
131 $pve_auth_priv_key = Crypt::OpenSSL::RSA->new_private_key($input);
132
133 return $pve_auth_priv_key;
134 }
135
136 sub assemble_ticket {
137 my ($username) = @_;
138
139 my $rsa_priv = get_privkey();
140
141 my $timestamp = sprintf("%08X", time());
142
143 my $plain = "PVE:$username:$timestamp";
144
145 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($plain), '');
146
147 return $ticket;
148 }
149
150 sub verify_ticket {
151 my ($ticket, $noerr) = @_;
152
153 if ($ticket && $ticket =~ m/^(PVE:\S+)::([^:\s]+)$/) {
154 my $plain = $1;
155 my $sig = $2;
156
157 my $rsa_pub = get_pubkey();
158 if ($rsa_pub->verify($plain, decode_base64($sig))) {
159 if ($plain =~ m/^PVE:(([A-Za-z0-9\.\-_]+)(\@([A-Za-z0-9\.\-_]+))?):([A-Z0-9]{8})$/) {
160 my $username = $1;
161 my $timestamp = $5;
162 my $ttime = hex($timestamp);
163
164 my $age = time() - $ttime;
165
166 if (($age > -300) && ($age < $ticket_lifetime)) {
167 return wantarray ? ($username, $age) : $username;
168 }
169 }
170 }
171 }
172
173 die "permission denied - invalid ticket\n" if !$noerr;
174
175 return undef;
176 }
177
178 # VNC tickets
179 # - they do not contain the username in plain text
180 # - they are restricted to a specific resource path (example: '/vms/100')
181 sub assemble_vnc_ticket {
182 my ($username, $path) = @_;
183
184 my $rsa_priv = get_privkey();
185
186 my $timestamp = sprintf("%08X", time());
187
188 my $plain = "PVEVNC:$timestamp";
189
190 $path = normalize_path($path);
191
192 my $full = "$plain:$username:$path";
193
194 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($full), '');
195
196 return $ticket;
197 }
198
199 sub verify_vnc_ticket {
200 my ($ticket, $username, $path, $noerr) = @_;
201
202 if ($ticket && $ticket =~ m/^(PVEVNC:\S+)::([^:\s]+)$/) {
203 my $plain = $1;
204 my $sig = $2;
205 my $full = "$plain:$username:$path";
206
207 my $rsa_pub = get_pubkey();
208 # Note: sign only match if $username and $path is correct
209 if ($rsa_pub->verify($full, decode_base64($sig))) {
210 if ($plain =~ m/^PVEVNC:([A-Z0-9]{8})$/) {
211 my $ttime = hex($1);
212
213 my $age = time() - $ttime;
214
215 if (($age > -20) && ($age < 40)) {
216 return 1;
217 }
218 }
219 }
220 }
221
222 die "permission denied - invalid vnc ticket\n" if !$noerr;
223
224 return undef;
225 }
226
227
228 sub authenticate_user_shadow {
229 my ($userid, $password) = @_;
230
231 die "no password\n" if !$password;
232
233 my $shadow_cfg = cfs_read_file($shadowconfigfile);
234
235 if ($shadow_cfg->{users}->{$userid}) {
236 my $encpw = crypt($password, $shadow_cfg->{users}->{$userid}->{shadow});
237 die "invalid credentials\n" if ($encpw ne $shadow_cfg->{users}->{$userid}->{shadow});
238 } else {
239 die "no password set\n";
240 }
241 }
242
243 sub authenticate_user_pam {
244 my ($userid, $password) = @_;
245
246 # user (www-data) need to be able to read /etc/passwd /etc/shadow
247
248 die "no password\n" if !$password;
249
250 my $pamh = new Authen::PAM ('common-auth', $userid, sub {
251 my @res;
252 while(@_) {
253 my $msg_type = shift;
254 my $msg = shift;
255 push @res, (0, $password);
256 }
257 push @res, 0;
258 return @res;
259 });
260
261 if (!ref ($pamh)) {
262 my $err = $pamh->pam_strerror($pamh);
263 die "error during PAM init: $err";
264 }
265
266 my $res;
267
268 if (($res = $pamh->pam_authenticate(0)) != PAM_SUCCESS) {
269 my $err = $pamh->pam_strerror($res);
270 die "$err\n";
271 }
272
273 if (($res = $pamh->pam_acct_mgmt (0)) != PAM_SUCCESS) {
274 my $err = $pamh->pam_strerror($res);
275 die "$err\n";
276 }
277
278 $pamh = 0; # call destructor
279 }
280
281 sub authenticate_user_ad {
282
283 my ($entry, $server, $userid, $password) = @_;
284
285 my $default_port = $entry->{secure} ? 636: 389;
286 my $port = $entry->{port} ? $entry->{port} : $default_port;
287 my $scheme = $entry->{secure} ? 'ldaps' : 'ldap';
288 my $conn_string = "$scheme://${server}:$port";
289
290 my $ldap = Net::LDAP->new($server) || die "$@\n";
291
292 $userid = "$userid\@$entry->{domain}"
293 if $userid !~ m/@/ && $entry->{domain};
294
295 my $res = $ldap->bind($userid, password => $password);
296
297 my $code = $res->code();
298 my $err = $res->error;
299
300 $ldap->unbind();
301
302 die "$err\n" if ($code);
303 }
304
305 sub authenticate_user_ldap {
306
307 my ($entry, $server, $userid, $password) = @_;
308
309 my $default_port = $entry->{secure} ? 636: 389;
310 my $port = $entry->{port} ? $entry->{port} : $default_port;
311 my $scheme = $entry->{secure} ? 'ldaps' : 'ldap';
312 my $conn_string = "$scheme://${server}:$port";
313
314 my $ldap = Net::LDAP->new($conn_string, verify => 'none') || die "$@\n";
315 my $search = $entry->{user_attr} . "=" . $userid;
316 my $result = $ldap->search( base => "$entry->{base_dn}",
317 scope => "sub",
318 filter => "$search",
319 attrs => ['dn']
320 );
321 die "no entries returned\n" if !$result->entries;
322 my @entries = $result->entries;
323 my $res = $ldap->bind($entries[0]->dn, password => $password);
324
325 my $code = $res->code();
326 my $err = $res->error;
327
328 $ldap->unbind();
329
330 die "$err\n" if ($code);
331 }
332
333 sub authenticate_user_domain {
334 my ($realm, $userid, $password) = @_;
335
336 my $domain_cfg = cfs_read_file($domainconfigfile);
337
338 die "no auth domain specified" if !$realm;
339
340 if ($realm eq 'pam') {
341 authenticate_user_pam($userid, $password);
342 return;
343 }
344
345 eval {
346 if ($realm eq 'pve') {
347 authenticate_user_shadow($userid, $password);
348 } else {
349
350 my $cfg = $domain_cfg->{$realm};
351 die "auth domain '$realm' does not exists\n" if !$cfg;
352
353 if ($cfg->{type} eq 'ad') {
354 eval { authenticate_user_ad($cfg, $cfg->{server1}, $userid, $password); };
355 my $err = $@;
356 return if !$err;
357 die $err if !$cfg->{server2};
358 authenticate_user_ad($cfg, $cfg->{server2}, $userid, $password);
359 } elsif ($cfg->{type} eq 'ldap') {
360 eval { authenticate_user_ldap($cfg, $cfg->{server1}, $userid, $password); };
361 my $err = $@;
362 return if !$err;
363 die $err if !$cfg->{server2};
364 authenticate_user_ldap($cfg, $cfg->{server2}, $userid, $password);
365 } else {
366 die "unknown auth type '$cfg->{type}'\n";
367 }
368 }
369 };
370 if (my $err = $@) {
371 sleep(2); # timeout after failed auth
372 die $err;
373 }
374 }
375
376 sub check_user_exist {
377 my ($usercfg, $username, $noerr) = @_;
378
379 $username = verify_username($username, $noerr);
380 return undef if !$username;
381
382 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
383
384 die "no such user ('$username')\n" if !$noerr;
385
386 return undef;
387 }
388
389 sub check_user_enabled {
390 my ($usercfg, $username, $noerr) = @_;
391
392 my $data = check_user_exist($usercfg, $username, $noerr);
393 return undef if !$data;
394
395 return 1 if $data->{enable};
396
397 return 1 if $username eq 'root@pam'; # root is always enabled
398
399 die "user '$username' is disabled\n" if !$noerr;
400
401 return undef;
402 }
403
404 # password should be utf8 encoded
405 sub authenticate_user {
406 my ($username, $password) = @_;
407
408 die "no username specified\n" if !$username;
409
410 my ($userid, $realm);
411
412 ($username, $userid, $realm) = verify_username($username);
413
414 my $usercfg = cfs_read_file('user.cfg');
415
416 eval { check_user_enabled($usercfg, $username); };
417 if (my $err = $@) {
418 sleep(2);
419 die $err;
420 }
421
422 my $ctime = time();
423 my $expire = $usercfg->{users}->{$username}->{expire};
424
425 if ($expire && ($expire < $ctime)) {
426 sleep(2);
427 die "account expired\n"
428 }
429
430 authenticate_user_domain($realm, $userid, $password);
431
432 return $username;
433 }
434
435 sub delete_shadow_password {
436 my ($userid) = @_;
437
438 lock_shadow_config(sub {
439 my $shadow_cfg = cfs_read_file($shadowconfigfile);
440 delete ($shadow_cfg->{users}->{$userid})
441 if $shadow_cfg->{users}->{$userid};
442 cfs_write_file($shadowconfigfile, $shadow_cfg);
443 });
444 }
445
446 sub store_shadow_password {
447 my ($userid, $password) = @_;
448
449 lock_shadow_config(sub {
450 my $shadow_cfg = cfs_read_file($shadowconfigfile);
451 $shadow_cfg->{users}->{$userid}->{shadow} = encrypt_pw($password);
452 cfs_write_file($shadowconfigfile, $shadow_cfg);
453 });
454 }
455
456 sub encrypt_pw {
457 my ($pw) = @_;
458
459 my $time = substr (Digest::SHA::sha1_base64 (time), 0, 8);
460 return crypt (encode("utf8", $pw), "\$5\$$time\$");
461 }
462
463 sub store_pam_password {
464 my ($userid, $password) = @_;
465
466 my $cmd = ['/usr/sbin/usermod'];
467
468 my $epw = encrypt_pw($password);
469 push @$cmd, '-p', $epw;
470
471 push @$cmd, $userid;
472
473 run_command($cmd);
474 }
475
476 sub domain_set_password {
477 my ($realm, $userid, $password) = @_;
478
479 die "no auth domain specified" if !$realm;
480
481 if ($realm eq 'pam') {
482 store_pam_password($userid, $password);
483 } elsif ($realm eq 'pve') {
484 store_shadow_password($userid, $password);
485 } else {
486 die "can't set password on auth domain '$realm'\n";
487 }
488 }
489
490 sub add_user_group {
491
492 my ($username, $usercfg, $group) = @_;
493 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
494 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
495 }
496
497 sub delete_user_group {
498
499 my ($username, $usercfg) = @_;
500
501 foreach my $group (keys %{$usercfg->{groups}}) {
502
503 delete ($usercfg->{groups}->{$group}->{users}->{$username})
504 if $usercfg->{groups}->{$group}->{users}->{$username};
505 }
506 }
507
508 sub delete_user_acl {
509
510 my ($username, $usercfg) = @_;
511
512 foreach my $acl (keys %{$usercfg->{acl}}) {
513
514 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
515 if $usercfg->{acl}->{$acl}->{users}->{$username};
516 }
517
518 }
519 sub delete_group_acl {
520
521 my ($group, $usercfg) = @_;
522
523 foreach my $acl (keys %{$usercfg->{acl}}) {
524
525 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
526 if $usercfg->{acl}->{$acl}->{groups}->{$group};
527 }
528
529 }
530
531 # we automatically create some predefined roles by splitting privs
532 # into 3 groups (per category)
533 # root: only root is allowed to do that
534 # admin: an administrator can to that
535 # user: a normak user/customer can to that
536 my $privgroups = {
537 VM => {
538 root => [],
539 admin => [
540 'VM.Modify',
541 'VM.Allocate',
542 'VM.Migrate',
543 'Permissions.Modify',
544 ],
545 user => [
546 'VM.Console',
547 'VM.PowerMgmt',
548 ],
549 audit => [
550 'VM.Audit'
551 ],
552 },
553 Sys => {
554 root => [
555 'Sys.PowerMgmt',
556 'Sys.Modify', # edit/change node settings
557 ],
558 admin => [
559 'Sys.Console',
560 'Sys.Syslog',
561 ],
562 user => [],
563 audit => [
564 'Sys.Audit',
565 ],
566 },
567 Datastore => {
568 root => [
569 'Permissions.Modify',
570 ],
571 admin => [
572 'Datastore.Allocate',
573 ],
574 user => [
575 'Datastore.AllocateSpace',
576 ],
577 audit => [
578 'Datastore.Audit',
579 ],
580 },
581 User => {
582 root => [],
583 admin => [
584 'User.Modify',
585 'User.Allocate',
586 ],
587 user => [],
588 audit => [],
589 },
590 };
591
592 my $valid_privs = {};
593
594 my $special_roles = {
595 'NoAccess' => {}, # no priviledges
596 'Administrator' => $valid_privs, # all priviledges
597 };
598
599 sub create_roles {
600
601 foreach my $cat (keys %$privgroups) {
602 my $cd = $privgroups->{$cat};
603 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
604 @{$cd->{user}}, @{$cd->{audit}}) {
605 $valid_privs->{$p} = 1;
606 }
607 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
608
609 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
610 $special_roles->{"PVEAdmin"}->{$p} = 1;
611 }
612 if (scalar(@{$cd->{user}})) {
613 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
614 $special_roles->{"PVE${cat}User"}->{$p} = 1;
615 }
616 }
617 foreach my $p (@{$cd->{audit}}) {
618 $special_roles->{"PVEAuditor"}->{$p} = 1;
619 }
620 }
621 };
622
623 create_roles();
624
625 my $valid_attributes = {
626 ad => {
627 server1 => '[\w\d]+(.[\w\d]+)*',
628 server2 => '[\w\d]+(.[\w\d]+)*',
629 domain => '\S+',
630 port => '\d+',
631 secure => '',
632 comment => '.*',
633 },
634 ldap => {
635 server1 => '[\w\d]+(.[\w\d]+)*',
636 server2 => '[\w\d]+(.[\w\d]+)*',
637 base_dn => '\w+=[\w\s]+(,\s*\w+=[\w\s]+)*',
638 user_attr => '\S{2,}',
639 secure => '',
640 port => '\d+',
641 comment => '.*',
642 }
643 };
644
645 sub add_role_privs {
646 my ($role, $usercfg, $privs) = @_;
647
648 return if !$privs;
649
650 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
651
652 foreach my $priv (split_list($privs)) {
653 if (defined ($valid_privs->{$priv})) {
654 $usercfg->{roles}->{$role}->{$priv} = 1;
655 } else {
656 die "invalid priviledge '$priv'\n";
657 }
658 }
659 }
660
661 sub normalize_path {
662 my $path = shift;
663
664 $path =~ s|/+|/|g;
665
666 $path =~ s|/$||;
667
668 $path = '/' if !$path;
669
670 $path = "/$path" if $path !~ m|^/|;
671
672 return undef if $path !~ m|^[[:alnum:]\-\_\/]+$|;
673
674 return $path;
675 }
676
677 my $realm_regex = qr/[A-Za-z][A-Za-z0-9\.\-_]+/;
678
679 sub pve_verify_realm {
680 my ($realm, $noerr) = @_;
681
682 if ($realm !~ m/^${realm_regex}$/) {
683 return undef if $noerr;
684 die "value does not look like a valid realm\n";
685 }
686 return $realm;
687 }
688
689 PVE::JSONSchema::register_format('pve-userid', \&verify_username);
690 sub verify_username {
691 my ($username, $noerr) = @_;
692
693 $username = '' if !$username;
694 my $len = length($username);
695 if ($len < 3) {
696 die "user name '$username' is too short\n" if !$noerr;
697 return undef;
698 }
699 if ($len > 64) {
700 die "user name '$username' is too long ($len > 64)\n" if !$noerr;
701 return undef;
702 }
703
704 # we only allow a limited set of characters (colon is not allowed,
705 # because we store usernames in colon separated lists)!
706 if ($username =~ m/^([^\s:]+)\@(${realm_regex})$/) {
707 return wantarray ? ($username, $1, $2) : $username;
708 }
709
710 die "value '$username' does not look like a valid user name\n" if !$noerr;
711
712 return undef;
713 }
714 PVE::JSONSchema::register_standard_option('userid', {
715 description => "User ID",
716 type => 'string', format => 'pve-userid',
717 maxLength => 64,
718 });
719
720 PVE::JSONSchema::register_standard_option('realm', {
721 description => "Authentication domain ID",
722 type => 'string', format => 'pve-configid',
723 maxLength => 32,
724 });
725
726 PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
727 sub verify_groupname {
728 my ($groupname, $noerr) = @_;
729
730 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
731
732 die "group name '$groupname' contains invalid characters\n" if !$noerr;
733
734 return undef;
735 }
736
737 return $groupname;
738 }
739
740 PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
741 sub verify_rolename {
742 my ($rolename, $noerr) = @_;
743
744 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
745
746 die "role name '$rolename' contains invalid characters\n" if !$noerr;
747
748 return undef;
749 }
750
751 return $rolename;
752 }
753
754 PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
755 sub verify_privname {
756 my ($priv, $noerr) = @_;
757
758 if (!$valid_privs->{$priv}) {
759 die "invalid priviledge '$priv'\n" if !$noerr;
760
761 return undef;
762 }
763
764 return $priv;
765 }
766
767 sub userconfig_force_defaults {
768 my ($cfg) = @_;
769
770 foreach my $r (keys %$special_roles) {
771 $cfg->{roles}->{$r} = $special_roles->{$r};
772 }
773
774 # fixme: remove 'root' group (not required)?
775
776 # add root user
777 $cfg->{users}->{'root@pam'}->{enable} = 1;
778 }
779
780 sub parse_user_config {
781 my ($filename, $raw) = @_;
782
783 my $cfg = {};
784
785 userconfig_force_defaults($cfg);
786
787 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
788 my $line = $1;
789
790 next if $line =~ m/^\s*$/; # skip empty lines
791
792 my @data;
793
794 foreach my $d (split (/:/, $line)) {
795 $d =~ s/^\s+//;
796 $d =~ s/\s+$//;
797 push @data, $d
798 }
799
800 my $et = shift @data;
801
802 if ($et eq 'user') {
803 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment) = @data;
804
805 my (undef, undef, $realm) = verify_username($user, 1);
806 if (!$realm) {
807 warn "user config - ignore user '$user' - invalid user name\n";
808 next;
809 }
810
811 $enable = $enable ? 1 : 0;
812
813 $expire = 0 if !$expire;
814
815 if ($expire !~ m/^\d+$/) {
816 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
817 next;
818 }
819 $expire = int($expire);
820
821 #if (!verify_groupname ($group, 1)) {
822 # warn "user config - ignore user '$user' - invalid characters in group name\n";
823 # next;
824 #}
825
826 $cfg->{users}->{$user} = {
827 enable => $enable,
828 # group => $group,
829 };
830 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
831 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
832 $cfg->{users}->{$user}->{email} = $email;
833 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
834 $cfg->{users}->{$user}->{expire} = $expire;
835
836 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
837 #$cfg->{groups}->{$group}->{$user} = 1;
838
839 } elsif ($et eq 'group') {
840 my ($group, $userlist, $comment) = @data;
841
842 if (!verify_groupname($group, 1)) {
843 warn "user config - ignore group '$group' - invalid characters in group name\n";
844 next;
845 }
846
847 # make sure to add the group (even if there are no members)
848 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
849
850 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
851
852 foreach my $user (split_list($userlist)) {
853
854 if (!verify_username($user, 1)) {
855 warn "user config - ignore invalid group member '$user'\n";
856 next;
857 }
858
859 if ($cfg->{users}->{$user}) { # user exists
860 $cfg->{users}->{$user}->{groups}->{$group} = 1;
861 $cfg->{groups}->{$group}->{users}->{$user} = 1;
862 } else {
863 warn "user config - ignore invalid group member '$user'\n";
864 }
865 }
866
867 } elsif ($et eq 'role') {
868 my ($role, $privlist) = @data;
869
870 if (!verify_rolename($role, 1)) {
871 warn "user config - ignore role '$role' - invalid characters in role name\n";
872 next;
873 }
874
875 # make sure to add the role (even if there are no privileges)
876 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
877
878 foreach my $priv (split_list($privlist)) {
879 if (defined ($valid_privs->{$priv})) {
880 $cfg->{roles}->{$role}->{$priv} = 1;
881 } else {
882 warn "user config - ignore invalid priviledge '$priv'\n";
883 }
884 }
885
886 } elsif ($et eq 'acl') {
887 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
888
889 if (my $path = normalize_path($pathtxt)) {
890 foreach my $role (split_list($rolelist)) {
891
892 if (!verify_rolename($role, 1)) {
893 warn "user config - ignore invalid role name '$role' in acl\n";
894 next;
895 }
896
897 foreach my $ug (split_list($uglist)) {
898 if ($ug =~ m/^@(\w+)$/) {
899 my $group = $1;
900 if ($cfg->{groups}->{$group}) { # group exists
901 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
902 } else {
903 warn "user config - ignore invalid acl group '$group'\n";
904 }
905 } elsif (verify_username($ug, 1)) {
906 if ($cfg->{users}->{$ug}) { # user exists
907 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
908 } else {
909 warn "user config - ignore invalid acl member '$ug'\n";
910 }
911 } else {
912 warn "user config - invalid user/group '$ug' in acl\n";
913 }
914 }
915 }
916 } else {
917 warn "user config - ignore invalid path in acl '$pathtxt'\n";
918 }
919 } elsif ($et eq 'pool') {
920 my ($pathtxt, $comment, $vmlist, $storelist) = @data;
921
922 if (my $path = normalize_path($pathtxt)) {
923 # make sure to add the pool (even if there are no members)
924 $cfg->{pools}->{$path} = { vms => {}, storage => {} } if !$cfg->{pools}->{$path};
925
926 $cfg->{pools}->{$path}->{comment} = PVE::Tools::decode_text($comment) if $comment;
927
928 foreach my $vmid (split_list($vmlist)) {
929 if ($vmid !~ m/^\d+$/) {
930 warn "user config - ignore invalid vmid '$vmid' in pool '$path'\n";
931 next;
932 }
933 $vmid = int($vmid);
934
935 if ($cfg->{vms}->{$vmid}) {
936 warn "user config - ignore duplicate vmid '$vmid' in pool '$path'\n";
937 next;
938 }
939
940 $cfg->{pools}->{$path}->{vms}->{$vmid} = 1;
941
942 # record vmid ==> pool relation
943 $cfg->{vms}->{$vmid} = $path;
944 }
945
946 foreach my $storeid (split_list($storelist)) {
947 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
948 warn "user config - ignore invalid storage '$storeid' in pool '$path'\n";
949 next;
950 }
951 $cfg->{pools}->{$path}->{storage}->{$storeid} = 1;
952 }
953
954 } else {
955 warn "user config - ignore invalid path in pool'$pathtxt'\n";
956 }
957 } else {
958 warn "user config - ignore config line: $line\n";
959 }
960 }
961
962 userconfig_force_defaults($cfg);
963
964 return $cfg;
965 }
966
967 sub parse_shadow_passwd {
968 my ($filename, $raw) = @_;
969
970 my $shadow = {};
971
972 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
973 my $line = $1;
974
975 next if $line =~ m/^\s*$/; # skip empty lines
976
977 if ($line !~ m/^\S+:\S+:$/) {
978 warn "pve shadow password: ignore invalid line $.\n";
979 next;
980 }
981
982 my ($userid, $crypt_pass) = split (/:/, $line);
983 $shadow->{users}->{$userid}->{shadow} = $crypt_pass;
984 }
985
986 return $shadow;
987 }
988
989 sub write_domains {
990 my ($filename, $cfg) = @_;
991
992 my $data = '';
993
994 my $wrote_default;
995
996 foreach my $realm (sort keys %$cfg) {
997 my $entry = $cfg->{$realm};
998 my $type = lc($entry->{type});
999
1000 next if !$type;
1001
1002 next if ($type eq 'pam') || ($type eq 'pve');
1003
1004 my $formats = $valid_attributes->{$type};
1005 next if !$formats;
1006
1007 $data .= "$type: $realm\n";
1008
1009 foreach my $k (sort keys %$entry) {
1010 next if $k eq 'type';
1011 my $v = $entry->{$k};
1012 if ($k eq 'default') {
1013 $data .= "\t$k\n" if $v && !$wrote_default;
1014 $wrote_default = 1;
1015 } elsif (defined($formats->{$k})) {
1016 if (!$formats->{$k}) {
1017 $data .= "\t$k\n" if $v;
1018 } elsif ($v =~ m/^$formats->{$k}$/) {
1019 $v = PVE::Tools::encode_text($v) if $k eq 'comment';
1020 $data .= "\t$k $v\n";
1021 } else {
1022 die "invalid value '$v' for attribute '$k'\n";
1023 }
1024 } else {
1025 die "invalid attribute '$k' - not supported\n";
1026 }
1027 }
1028
1029 $data .= "\n";
1030 }
1031
1032 return $data;
1033 }
1034
1035 sub parse_domains {
1036 my ($filename, $raw) = @_;
1037
1038 my $cfg = {};
1039
1040 my $default;
1041
1042 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
1043 my $line = $1;
1044
1045 next if $line =~ m/^\#/; # skip comment lines
1046 next if $line =~ m/^\s*$/; # skip empty lines
1047
1048 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
1049 my $realm = $2;
1050 my $type = lc($1);
1051
1052 my $ignore = 0;
1053 my $entry;
1054
1055 my $formats = $valid_attributes->{$type};
1056 if (!$formats) {
1057 $ignore = 1;
1058 warn "ignoring domain '$realm' - (unsupported authentication type '$type')\n";
1059 } elsif (!pve_verify_realm($realm, 1)) {
1060 $ignore = 1;
1061 warn "ignoring domain '$realm' - (illegal characters)\n";
1062 } else {
1063 $entry = { type => $type };
1064 }
1065
1066 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
1067 $line = $1;
1068
1069 next if $line =~ m/^\#/; #skip comment lines
1070 last if $line =~ m/^\s*$/;
1071
1072 next if $ignore; # skip
1073
1074 if ($line =~ m/^\s+(default)\s*$/) {
1075 $default = $realm if !$default;
1076 } elsif ($line =~ m/^\s+(\S+)(\s+(.*\S))?\s*$/) {
1077 my ($k, $v) = (lc($1), $3);
1078 if (defined($formats->{$k})) {
1079 if (!$formats->{$k} && !defined($v)) {
1080 $entry->{$k} = 1;
1081 } elsif ($formats->{$k} && $v =~ m/^$formats->{$k}$/) {
1082 if (!defined($entry->{$k})) {
1083 $v = PVE::Tools::decode_text($v) if $k eq 'comment';
1084 $entry->{$k} = $v;
1085 } else {
1086 warn "ignoring duplicate attribute '$k $v'\n";
1087 }
1088 } else {
1089 warn "ignoring value '$v' for attribute '$k' - invalid format\n";
1090 }
1091 } else {
1092 warn "ignoring attribute '$k' - not supported\n";
1093 }
1094 } else {
1095 warn "ignore config line: $line\n";
1096 }
1097 }
1098
1099 if ($entry->{server2} && !$entry->{server1}) {
1100 $entry->{server1} = $entry->{server2};
1101 delete $entry->{server2};
1102 }
1103
1104 if ($ignore) {
1105 # do nothing
1106 } elsif (!$entry->{server1}) {
1107 warn "ignoring domain '$realm' - missing server attribute\n";
1108 } elsif (($entry->{type} eq "ldap") && !$entry->{user_attr}) {
1109 warn "ignoring domain '$realm' - missing user attribute\n";
1110 } elsif (($entry->{type} eq "ldap") && !$entry->{base_dn}) {
1111 warn "ignoring domain '$realm' - missing base_dn attribute\n";
1112 } elsif (($entry->{type} eq "ad") && !$entry->{domain}) {
1113 warn "ignoring domain '$realm' - missing domain attribute\n";
1114 } else {
1115 $cfg->{$realm} = $entry;
1116 }
1117
1118 } else {
1119 warn "ignore config line: $line\n";
1120 }
1121 }
1122
1123 $cfg->{$default}->{default} = 1 if $default;
1124
1125 # add default domains
1126
1127 $cfg->{pve} = {
1128 type => 'builtin',
1129 comment => "Proxmox VE authentication server",
1130 };
1131
1132 $cfg->{pam} = {
1133 type => 'builtin',
1134 comment => "Linux PAM standard authentication",
1135 };
1136
1137 return $cfg;
1138 }
1139
1140 sub write_shadow_config {
1141 my ($filename, $cfg) = @_;
1142
1143 my $data = '';
1144 foreach my $userid (keys %{$cfg->{users}}) {
1145 my $crypt_pass = $cfg->{users}->{$userid}->{shadow};
1146 $data .= "$userid:$crypt_pass:\n";
1147 }
1148
1149 return $data
1150 }
1151
1152 sub write_user_config {
1153 my ($filename, $cfg) = @_;
1154
1155 my $data = '';
1156
1157 foreach my $user (keys %{$cfg->{users}}) {
1158 my $d = $cfg->{users}->{$user};
1159 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1160 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1161 my $email = $d->{email} || '';
1162 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1163 my $expire = int($d->{expire} || 0);
1164 my $enable = $d->{enable} ? 1 : 0;
1165 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:\n";
1166 }
1167
1168 $data .= "\n";
1169
1170 foreach my $group (keys %{$cfg->{groups}}) {
1171 my $d = $cfg->{groups}->{$group};
1172 my $list = join (',', keys %{$d->{users}});
1173 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1174 $data .= "group:$group:$list:$comment:\n";
1175 }
1176
1177 $data .= "\n";
1178
1179 foreach my $path (keys %{$cfg->{pools}}) {
1180 my $d = $cfg->{pools}->{$path};
1181 my $vmlist = join (',', keys %{$d->{vms}});
1182 my $storelist = join (',', keys %{$d->{storage}});
1183 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1184 $data .= "pool:$path:$comment:$vmlist:$storelist:\n";
1185 }
1186
1187 $data .= "\n";
1188
1189 foreach my $role (keys %{$cfg->{roles}}) {
1190 next if $special_roles->{$role};
1191
1192 my $d = $cfg->{roles}->{$role};
1193 my $list = join (',', keys %$d);
1194 $data .= "role:$role:$list:\n";
1195 }
1196
1197 $data .= "\n";
1198
1199 foreach my $path (sort keys %{$cfg->{acl}}) {
1200 my $d = $cfg->{acl}->{$path};
1201
1202 my $ra = {};
1203
1204 foreach my $group (keys %{$d->{groups}}) {
1205 my $l0 = '';
1206 my $l1 = '';
1207 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
1208 my $propagate = $d->{groups}->{$group}->{$role};
1209 if ($propagate) {
1210 $l1 .= ',' if $l1;
1211 $l1 .= $role;
1212 } else {
1213 $l0 .= ',' if $l0;
1214 $l0 .= $role;
1215 }
1216 }
1217 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
1218 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
1219 }
1220
1221 foreach my $user (keys %{$d->{users}}) {
1222 # no need to save, because root is always 'Administartor'
1223 next if $user eq 'root@pam';
1224
1225 my $l0 = '';
1226 my $l1 = '';
1227 foreach my $role (sort keys %{$d->{users}->{$user}}) {
1228 my $propagate = $d->{users}->{$user}->{$role};
1229 if ($propagate) {
1230 $l1 .= ',' if $l1;
1231 $l1 .= $role;
1232 } else {
1233 $l0 .= ',' if $l0;
1234 $l0 .= $role;
1235 }
1236 }
1237 $ra->{0}->{$l0}->{$user} = 1 if $l0;
1238 $ra->{1}->{$l1}->{$user} = 1 if $l1;
1239 }
1240
1241 foreach my $rolelist (sort keys %{$ra->{0}}) {
1242 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
1243 $data .= "acl:0:$path:$uglist:$rolelist:\n";
1244 }
1245 foreach my $rolelist (sort keys %{$ra->{1}}) {
1246 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
1247 $data .= "acl:1:$path:$uglist:$rolelist:\n";
1248 }
1249 }
1250
1251 return $data;
1252 }
1253
1254 sub roles {
1255 my ($cfg, $user, $path) = @_;
1256
1257 # NOTE: we do not consider pools here.
1258 # You need to use $rpcenv->roles() instead if you want that.
1259
1260 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1261
1262 my $perm = {};
1263
1264 foreach my $p (sort keys %{$cfg->{acl}}) {
1265 my $final = ($path eq $p);
1266
1267 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1268
1269 my $acl = $cfg->{acl}->{$p};
1270
1271 #print "CHECKACL $path $p\n";
1272 #print "ACL $path = " . Dumper ($acl);
1273
1274 if (my $ri = $acl->{users}->{$user}) {
1275 my $new;
1276 foreach my $role (keys %$ri) {
1277 my $propagate = $ri->{$role};
1278 if ($final || $propagate) {
1279 #print "APPLY ROLE $p $user $role\n";
1280 $new = {} if !$new;
1281 $new->{$role} = 1;
1282 }
1283 }
1284 if ($new) {
1285 $perm = $new; # overwrite previous settings
1286 next; # user privs always override group privs
1287 }
1288 }
1289
1290 my $new;
1291 foreach my $g (keys %{$acl->{groups}}) {
1292 next if !$cfg->{groups}->{$g}->{users}->{$user};
1293 if (my $ri = $acl->{groups}->{$g}) {
1294 foreach my $role (keys %$ri) {
1295 my $propagate = $ri->{$role};
1296 if ($final || $propagate) {
1297 #print "APPLY ROLE $p \@$g $role\n";
1298 $new = {} if !$new;
1299 $new->{$role} = 1;
1300 }
1301 }
1302 }
1303 }
1304 if ($new) {
1305 $perm = $new; # overwrite previous settings
1306 next;
1307 }
1308 }
1309
1310 return ('NoAccess') if defined ($perm->{NoAccess});
1311 #return () if defined ($perm->{NoAccess});
1312
1313 #print "permission $user $path = " . Dumper ($perm);
1314
1315 my @ra = keys %$perm;
1316
1317 #print "roles $user $path = " . join (',', @ra) . "\n";
1318
1319 return @ra;
1320 }
1321
1322 sub permission {
1323 my ($cfg, $user, $path) = @_;
1324
1325 $user = verify_username($user, 1);
1326 return {} if !$user;
1327
1328 my @ra = roles($cfg, $user, $path);
1329
1330 my $privs = {};
1331
1332 foreach my $role (@ra) {
1333 if (my $privset = $cfg->{roles}->{$role}) {
1334 foreach my $p (keys %$privset) {
1335 $privs->{$p} = 1;
1336 }
1337 }
1338 }
1339
1340 #print "priviledges $user $path = " . Dumper ($privs);
1341
1342 return $privs;
1343 }
1344
1345 sub check_permissions {
1346 my ($username, $path, $privlist) = @_;
1347
1348 $path = normalize_path($path);
1349 my $usercfg = cfs_read_file('user.cfg');
1350 my $perm = permission($usercfg, $username, $path);
1351
1352 foreach my $priv (split_list($privlist)) {
1353 return undef if !$perm->{$priv};
1354 };
1355
1356 return 1;
1357 }
1358
1359 1;