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