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