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