simplify filter_groups
[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',
543 'Permissions.Modify',
544 ],
545 user => [
546 'VM.Console',
547 'VM.PowerMgmt',
548 ],
549 audit => [
550 'VM.Audit'
551 ],
552 },
553 Sys => {
554 root => [
555 'Sys.PowerMgmt',
37d45deb
DM
556 'Sys.Modify', # edit/change node settings
557 'Sys.UserAdd', # add/delete users
2c3a6c0a
DM
558 ],
559 admin => [
560 'Sys.Console',
561 'Sys.Syslog',
37d45deb 562 'Sys.UserMod', # modify users settings
2c3a6c0a
DM
563 ],
564 user => [],
565 audit => [
566 'Sys.Audit',
567 ],
568 },
569 Datastore => {
570 root => [
571 'Datastore.Allocate',
572 'Permissions.Modify',
573 ],
574 admin => [],
575 user => [
576 'Datastore.AllocateSpace',
577 ],
578 audit => [
579 'Datastore.Audit',
580 ],
581 },
582};
583
584my $valid_privs = {};
585
586my $special_roles = {
587 'NoAccess' => {}, # no priviledges
588 'Administrator' => $valid_privs, # all priviledges
589};
590
591sub create_roles {
592
593 foreach my $cat (keys %$privgroups) {
594 my $cd = $privgroups->{$cat};
595 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
596 @{$cd->{user}}, @{$cd->{audit}}) {
597 $valid_privs->{$p} = 1;
598 }
599 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
600
601 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
602 $special_roles->{"PVEAdmin"}->{$p} = 1;
603 }
604 if (scalar(@{$cd->{user}})) {
605 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
606 $special_roles->{"PVE${cat}User"}->{$p} = 1;
607 }
608 }
609 foreach my $p (@{$cd->{audit}}) {
610 $special_roles->{"PVEAuditor"}->{$p} = 1;
611 }
612 }
613};
614
615create_roles();
616
617my $valid_attributes = {
618 ad => {
619 server1 => '[\w\d]+(.[\w\d]+)*',
620 server2 => '[\w\d]+(.[\w\d]+)*',
621 domain => '\S+',
af4a8a85 622 port => '\d+',
2c3a6c0a
DM
623 secure => '',
624 comment => '.*',
625 },
626 ldap => {
627 server1 => '[\w\d]+(.[\w\d]+)*',
628 server2 => '[\w\d]+(.[\w\d]+)*',
629 base_dn => '\w+=[\w\s]+(,\s*\w+=[\w\s]+)*',
630 user_attr => '\S{2,}',
631 secure => '',
af4a8a85 632 port => '\d+',
2c3a6c0a
DM
633 comment => '.*',
634 }
635};
636
637sub add_role_privs {
638 my ($role, $usercfg, $privs) = @_;
639
640 return if !$privs;
641
642 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
643
644 foreach my $priv (split_list($privs)) {
645 if (defined ($valid_privs->{$priv})) {
646 $usercfg->{roles}->{$role}->{$priv} = 1;
647 } else {
648 die "invalid priviledge '$priv'\n";
649 }
650 }
651}
652
653sub normalize_path {
654 my $path = shift;
655
656 $path =~ s|/+|/|;
657
658 $path =~ s|/$||;
659
660 $path = '/' if !$path;
661
662 return undef if $path !~ m|^[[:alnum:]\-\_\/]+$|;
663
664 return $path;
665}
666
667my $realm_regex = qr/[A-Za-z][A-Za-z0-9\.\-_]+/;
668
669sub pve_verify_realm {
670 my ($realm, $noerr) = @_;
671
672 if ($realm !~ m/^${realm_regex}$/) {
673 return undef if $noerr;
674 die "value does not look like a valid realm\n";
675 }
676 return $realm;
677}
678
679PVE::JSONSchema::register_format('pve-userid', \&verify_username);
680sub verify_username {
681 my ($username, $noerr) = @_;
682
683 $username = '' if !$username;
684 my $len = length($username);
685 if ($len < 3) {
686 die "user name '$username' is too short\n" if !$noerr;
687 return undef;
688 }
689 if ($len > 64) {
690 die "user name '$username' is too long ($len > 64)\n" if !$noerr;
691 return undef;
692 }
693
694 # we only allow a limited set of characters (colon is not allowed,
695 # because we store usernames in colon separated lists)!
696 if ($username =~ m/^([^\s:]+)\@(${realm_regex})$/) {
697 return wantarray ? ($username, $1, $2) : $username;
698 }
699
700 die "value '$username' does not look like a valid user name\n" if !$noerr;
701
702 return undef;
703}
704PVE::JSONSchema::register_standard_option('userid', {
705 description => "User ID",
706 type => 'string', format => 'pve-userid',
707 maxLength => 64,
708});
709
710PVE::JSONSchema::register_standard_option('realm', {
711 description => "Authentication domain ID",
712 type => 'string', format => 'pve-configid',
713 maxLength => 32,
714});
715
716PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
717sub verify_groupname {
718 my ($groupname, $noerr) = @_;
719
720 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
721
722 die "group name '$groupname' contains invalid characters\n" if !$noerr;
723
724 return undef;
725 }
726
727 return $groupname;
728}
729
730PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
731sub verify_rolename {
732 my ($rolename, $noerr) = @_;
733
734 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
735
736 die "role name '$rolename' contains invalid characters\n" if !$noerr;
737
738 return undef;
739 }
740
741 return $rolename;
742}
743
744PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
745sub verify_privname {
746 my ($priv, $noerr) = @_;
747
748 if (!$valid_privs->{$priv}) {
749 die "invalid priviledge '$priv'\n" if !$noerr;
750
751 return undef;
752 }
753
754 return $priv;
755}
756
757sub userconfig_force_defaults {
758 my ($cfg) = @_;
759
760 foreach my $r (keys %$special_roles) {
761 $cfg->{roles}->{$r} = $special_roles->{$r};
762 }
763
764 # fixme: remove 'root' group (not required)?
765
766 # add root user
767 $cfg->{users}->{'root@pam'}->{enable} = 1;
768}
769
770sub parse_user_config {
771 my ($filename, $raw) = @_;
772
773 my $cfg = {};
774
775 userconfig_force_defaults($cfg);
776
777 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
778 my $line = $1;
779
780 next if $line =~ m/^\s*$/; # skip empty lines
781
782 my @data;
783
784 foreach my $d (split (/:/, $line)) {
785 $d =~ s/^\s+//;
786 $d =~ s/\s+$//;
787 push @data, $d
788 }
789
790 my $et = shift @data;
791
792 if ($et eq 'user') {
793 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment) = @data;
794
795 my (undef, undef, $realm) = verify_username($user, 1);
796 if (!$realm) {
797 warn "user config - ignore user '$user' - invalid user name\n";
798 next;
799 }
800
801 $enable = $enable ? 1 : 0;
802
803 $expire = 0 if !$expire;
804
805 if ($expire !~ m/^\d+$/) {
806 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
807 next;
808 }
809 $expire = int($expire);
810
811 #if (!verify_groupname ($group, 1)) {
812 # warn "user config - ignore user '$user' - invalid characters in group name\n";
813 # next;
814 #}
815
816 $cfg->{users}->{$user} = {
817 enable => $enable,
818 # group => $group,
819 };
820 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
821 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
822 $cfg->{users}->{$user}->{email} = $email;
823 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
824 $cfg->{users}->{$user}->{expire} = $expire;
825
826 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
827 #$cfg->{groups}->{$group}->{$user} = 1;
828
829 } elsif ($et eq 'group') {
830 my ($group, $userlist, $comment) = @data;
831
832 if (!verify_groupname($group, 1)) {
833 warn "user config - ignore group '$group' - invalid characters in group name\n";
834 next;
835 }
836
837 # make sure to add the group (even if there are no members)
838 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
839
840 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
841
842 foreach my $user (split_list($userlist)) {
843
844 if (!verify_username($user, 1)) {
845 warn "user config - ignore invalid group member '$user'\n";
846 next;
847 }
848
849 if ($cfg->{users}->{$user}) { # user exists
850 $cfg->{users}->{$user}->{groups}->{$group} = 1;
851 $cfg->{groups}->{$group}->{users}->{$user} = 1;
852 } else {
853 warn "user config - ignore invalid group member '$user'\n";
854 }
855 }
856
857 } elsif ($et eq 'role') {
858 my ($role, $privlist) = @data;
859
860 if (!verify_rolename($role, 1)) {
861 warn "user config - ignore role '$role' - invalid characters in role name\n";
862 next;
863 }
864
865 # make sure to add the role (even if there are no privileges)
866 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
867
868 foreach my $priv (split_list($privlist)) {
869 if (defined ($valid_privs->{$priv})) {
870 $cfg->{roles}->{$role}->{$priv} = 1;
871 } else {
872 warn "user config - ignore invalid priviledge '$priv'\n";
873 }
874 }
875
876 } elsif ($et eq 'acl') {
877 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
878
879 if (my $path = normalize_path($pathtxt)) {
880 foreach my $role (split_list($rolelist)) {
881
882 if (!verify_rolename($role, 1)) {
883 warn "user config - ignore invalid role name '$role' in acl\n";
884 next;
885 }
886
887 foreach my $ug (split_list($uglist)) {
888 if ($ug =~ m/^@(\w+)$/) {
889 my $group = $1;
890 if ($cfg->{groups}->{$group}) { # group exists
891 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
892 } else {
893 warn "user config - ignore invalid acl group '$group'\n";
894 }
895 } elsif (verify_username($ug, 1)) {
896 if ($cfg->{users}->{$ug}) { # user exists
897 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
898 } else {
899 warn "user config - ignore invalid acl member '$ug'\n";
900 }
901 } else {
902 warn "user config - invalid user/group '$ug' in acl\n";
903 }
904 }
905 }
906 } else {
907 warn "user config - ignore invalid path in acl '$pathtxt'\n";
908 }
909 } else {
910 warn "user config - ignore config line: $line\n";
911 }
912 }
913
914 userconfig_force_defaults($cfg);
915
916 return $cfg;
917}
918
919sub parse_shadow_passwd {
920 my ($filename, $raw) = @_;
921
922 my $shadow = {};
923
924 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
925 my $line = $1;
926
927 next if $line =~ m/^\s*$/; # skip empty lines
928
929 if ($line !~ m/^\S+:\S+:$/) {
930 warn "pve shadow password: ignore invalid line $.\n";
931 next;
932 }
933
934 my ($userid, $crypt_pass) = split (/:/, $line);
935 $shadow->{users}->{$userid}->{shadow} = $crypt_pass;
936 }
937
938 return $shadow;
939}
940
941sub write_domains {
942 my ($filename, $cfg) = @_;
943
944 my $data = '';
945
946 my $wrote_default;
947
948 foreach my $realm (sort keys %$cfg) {
949 my $entry = $cfg->{$realm};
950 my $type = lc($entry->{type});
951
952 next if !$type;
953
954 next if ($type eq 'pam') || ($type eq 'pve');
955
956 my $formats = $valid_attributes->{$type};
957 next if !$formats;
958
959 $data .= "$type: $realm\n";
960
961 foreach my $k (sort keys %$entry) {
962 next if $k eq 'type';
963 my $v = $entry->{$k};
964 if ($k eq 'default') {
965 $data .= "\t$k\n" if $v && !$wrote_default;
966 $wrote_default = 1;
967 } elsif (defined($formats->{$k})) {
968 if (!$formats->{$k}) {
0c156363 969 $data .= "\t$k\n" if $v;
2c3a6c0a
DM
970 } elsif ($v =~ m/^$formats->{$k}$/) {
971 $v = PVE::Tools::encode_text($v) if $k eq 'comment';
972 $data .= "\t$k $v\n";
973 } else {
974 die "invalid value '$v' for attribute '$k'\n";
975 }
976 } else {
977 die "invalid attribute '$k' - not supported\n";
978 }
979 }
980
981 $data .= "\n";
982 }
983
984 return $data;
985}
986
987sub parse_domains {
988 my ($filename, $raw) = @_;
989
990 my $cfg = {};
991
992 my $default;
993
994 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
995 my $line = $1;
996
997 next if $line =~ m/^\#/; # skip comment lines
998 next if $line =~ m/^\s*$/; # skip empty lines
999
1000 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
1001 my $realm = $2;
1002 my $type = lc($1);
1003
1004 my $ignore = 0;
1005 my $entry;
1006
1007 my $formats = $valid_attributes->{$type};
1008 if (!$formats) {
1009 $ignore = 1;
1010 warn "ignoring domain '$realm' - (unsupported authentication type '$type')\n";
1011 } elsif (!pve_verify_realm($realm, 1)) {
1012 $ignore = 1;
1013 warn "ignoring domain '$realm' - (illegal characters)\n";
1014 } else {
1015 $entry = { type => $type };
1016 }
1017
1018 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
1019 $line = $1;
1020
1021 next if $line =~ m/^\#/; #skip comment lines
1022 last if $line =~ m/^\s*$/;
1023
1024 next if $ignore; # skip
1025
1026 if ($line =~ m/^\s+(default)\s*$/) {
1027 $default = $realm if !$default;
1028 } elsif ($line =~ m/^\s+(\S+)(\s+(.*\S))?\s*$/) {
1029 my ($k, $v) = (lc($1), $3);
1030 if (defined($formats->{$k})) {
1031 if (!$formats->{$k} && !defined($v)) {
1032 $entry->{$k} = 1;
1033 } elsif ($formats->{$k} && $v =~ m/^$formats->{$k}$/) {
1034 if (!defined($entry->{$k})) {
1035 $v = PVE::Tools::decode_text($v) if $k eq 'comment';
1036 $entry->{$k} = $v;
1037 } else {
1038 warn "ignoring duplicate attribute '$k $v'\n";
1039 }
1040 } else {
1041 warn "ignoring value '$v' for attribute '$k' - invalid format\n";
1042 }
1043 } else {
1044 warn "ignoring attribute '$k' - not supported\n";
1045 }
1046 } else {
1047 warn "ignore config line: $line\n";
1048 }
1049 }
1050
1051 if ($entry->{server2} && !$entry->{server1}) {
1052 $entry->{server1} = $entry->{server2};
1053 delete $entry->{server2};
1054 }
1055
1056 if ($ignore) {
1057 # do nothing
1058 } elsif (!$entry->{server1}) {
1059 warn "ignoring domain '$realm' - missing server attribute\n";
1060 } elsif (($entry->{type} eq "ldap") && !$entry->{user_attr}) {
1061 warn "ignoring domain '$realm' - missing user attribute\n";
1062 } elsif (($entry->{type} eq "ldap") && !$entry->{base_dn}) {
1063 warn "ignoring domain '$realm' - missing base_dn attribute\n";
0c156363
DM
1064 } elsif (($entry->{type} eq "ad") && !$entry->{domain}) {
1065 warn "ignoring domain '$realm' - missing domain attribute\n";
2c3a6c0a
DM
1066 } else {
1067 $cfg->{$realm} = $entry;
1068 }
1069
1070 } else {
1071 warn "ignore config line: $line\n";
1072 }
1073 }
1074
1075 $cfg->{$default}->{default} = 1 if $default;
1076
1077 # add default domains
1078
1079 $cfg->{pve} = {
1080 type => 'builtin',
1081 comment => "Proxmox VE authentication server",
1082 };
1083
1084 $cfg->{pam} = {
1085 type => 'builtin',
1086 comment => "Linux PAM standard authentication",
1087 };
1088
1089 return $cfg;
1090}
1091
1092sub write_shadow_config {
1093 my ($filename, $cfg) = @_;
1094
1095 my $data = '';
1096 foreach my $userid (keys %{$cfg->{users}}) {
1097 my $crypt_pass = $cfg->{users}->{$userid}->{shadow};
1098 $data .= "$userid:$crypt_pass:\n";
1099 }
1100
1101 return $data
1102}
1103
1104sub write_user_config {
1105 my ($filename, $cfg) = @_;
1106
1107 my $data = '';
1108
1109 foreach my $user (keys %{$cfg->{users}}) {
2c3a6c0a
DM
1110 my $d = $cfg->{users}->{$user};
1111 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1112 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1113 my $email = $d->{email} || '';
1114 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 1115 my $expire = int($d->{expire} || 0);
2c3a6c0a
DM
1116 my $enable = $d->{enable} ? 1 : 0;
1117 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:\n";
1118 }
1119
1120 $data .= "\n";
1121
1122 foreach my $group (keys %{$cfg->{groups}}) {
1123 my $d = $cfg->{groups}->{$group};
1124 my $list = join (',', keys %{$d->{users}});
1125 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1126 $data .= "group:$group:$list:$comment:\n";
1127 }
1128
1129 $data .= "\n";
1130
1131 foreach my $role (keys %{$cfg->{roles}}) {
1132 next if $special_roles->{$role};
1133
1134 my $d = $cfg->{roles}->{$role};
1135 my $list = join (',', keys %$d);
1136 $data .= "role:$role:$list:\n";
1137 }
1138
1139 $data .= "\n";
1140
1141 foreach my $path (sort keys %{$cfg->{acl}}) {
1142 my $d = $cfg->{acl}->{$path};
1143
1144 my $ra = {};
1145
1146 foreach my $group (keys %{$d->{groups}}) {
1147 my $l0 = '';
1148 my $l1 = '';
1149 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
1150 my $propagate = $d->{groups}->{$group}->{$role};
1151 if ($propagate) {
1152 $l1 .= ',' if $l1;
1153 $l1 .= $role;
1154 } else {
1155 $l0 .= ',' if $l0;
1156 $l0 .= $role;
1157 }
1158 }
1159 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
1160 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
1161 }
1162
1163 foreach my $user (keys %{$d->{users}}) {
1164 # no need to save, because root is always 'Administartor'
1165 next if $user eq 'root@pam';
1166
1167 my $l0 = '';
1168 my $l1 = '';
1169 foreach my $role (sort keys %{$d->{users}->{$user}}) {
1170 my $propagate = $d->{users}->{$user}->{$role};
1171 if ($propagate) {
1172 $l1 .= ',' if $l1;
1173 $l1 .= $role;
1174 } else {
1175 $l0 .= ',' if $l0;
1176 $l0 .= $role;
1177 }
1178 }
1179 $ra->{0}->{$l0}->{$user} = 1 if $l0;
1180 $ra->{1}->{$l1}->{$user} = 1 if $l1;
1181 }
1182
1183 foreach my $rolelist (sort keys %{$ra->{0}}) {
1184 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
1185 $data .= "acl:0:$path:$uglist:$rolelist:\n";
1186 }
1187 foreach my $rolelist (sort keys %{$ra->{1}}) {
1188 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
1189 $data .= "acl:1:$path:$uglist:$rolelist:\n";
1190 }
1191 }
1192
1193 return $data;
1194}
1195
1196sub roles {
1197 my ($cfg, $user, $path) = @_;
1198
1199 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1200
1201 my $perm = {};
1202
1203 foreach my $p (sort keys %{$cfg->{acl}}) {
1204 my $final = ($path eq $p);
1205
1206 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1207
1208 my $acl = $cfg->{acl}->{$p};
1209
1210 #print "CHECKACL $path $p\n";
1211 #print "ACL $path = " . Dumper ($acl);
1212
1213 if (my $ri = $acl->{users}->{$user}) {
1214 my $new;
1215 foreach my $role (keys %$ri) {
1216 my $propagate = $ri->{$role};
1217 if ($final || $propagate) {
1218 #print "APPLY ROLE $p $user $role\n";
1219 $new = {} if !$new;
1220 $new->{$role} = 1;
1221 }
1222 }
1223 if ($new) {
1224 $perm = $new; # overwrite previous settings
1225 next; # user privs always override group privs
1226 }
1227 }
1228
1229 my $new;
1230 foreach my $g (keys %{$acl->{groups}}) {
1231 next if !$cfg->{groups}->{$g}->{users}->{$user};
1232 if (my $ri = $acl->{groups}->{$g}) {
1233 foreach my $role (keys %$ri) {
1234 my $propagate = $ri->{$role};
1235 if ($final || $propagate) {
1236 #print "APPLY ROLE $p \@$g $role\n";
1237 $new = {} if !$new;
1238 $new->{$role} = 1;
1239 }
1240 }
1241 }
1242 }
1243 if ($new) {
1244 $perm = $new; # overwrite previous settings
1245 next;
1246 }
1247
1248 #die "what herea?";
1249 }
1250
1251 my $res = {};
1252 if (!defined ($perm->{NoAccess})) {
1253 $res = $perm;
1254 }
1255
1256 #print "permission $user $path = " . Dumper ($perm);
1257
1258 my @ra = keys %$res;
1259
1260 #print "roles $user $path = " . join (',', @ra) . "\n";
1261
1262 return @ra;
1263}
1264
1265sub permission {
1266 my ($cfg, $user, $path) = @_;
1267
1268 $user = verify_username($user, 1);
1269 return {} if !$user;
1270
1271 my @ra = roles($cfg, $user, $path);
1272
1273 my $privs = {};
1274
1275 foreach my $role (@ra) {
1276 if (my $privset = $cfg->{roles}->{$role}) {
1277 foreach my $p (keys %$privset) {
1278 $privs->{$p} = 1;
1279 }
1280 }
1281 }
1282
1283 #print "priviledges $user $path = " . Dumper ($privs);
1284
1285 return $privs;
1286}
1287
1288sub check_permissions {
1289 my ($username, $path, $privlist) = @_;
1290
1291 $path = normalize_path($path);
1292 my $usercfg = cfs_read_file('user.cfg');
1293 my $perm = permission($usercfg, $username, $path);
1294
1295 foreach my $priv (split_list($privlist)) {
1296 return undef if !$perm->{$priv};
1297 };
1298
1299 return 1;
1300}
1301
13021;