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