do not allow user names including slash
[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))) {
533219a1 159 if ($plain =~ m/^PVE:(\S+):([A-Z0-9]{8})$/) {
2c3a6c0a 160 my $username = $1;
533219a1 161 my $timestamp = $2;
2c3a6c0a
DM
162 my $ttime = hex($timestamp);
163
164 my $age = time() - $ttime;
165
533219a1
DM
166 if (verify_username($username, 1) &&
167 ($age > -300) && ($age < $ticket_lifetime)) {
2c3a6c0a
DM
168 return wantarray ? ($username, $age) : $username;
169 }
170 }
171 }
172 }
173
174 die "permission denied - invalid ticket\n" if !$noerr;
175
176 return undef;
177}
178
adf8d771
DM
179# VNC tickets
180# - they do not contain the username in plain text
181# - they are restricted to a specific resource path (example: '/vms/100')
182sub assemble_vnc_ticket {
183 my ($username, $path) = @_;
184
185 my $rsa_priv = get_privkey();
186
187 my $timestamp = sprintf("%08X", time());
188
189 my $plain = "PVEVNC:$timestamp";
190
191 $path = normalize_path($path);
192
193 my $full = "$plain:$username:$path";
194
195 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($full), '');
196
197 return $ticket;
198}
199
200sub verify_vnc_ticket {
201 my ($ticket, $username, $path, $noerr) = @_;
202
203 if ($ticket && $ticket =~ m/^(PVEVNC:\S+)::([^:\s]+)$/) {
204 my $plain = $1;
205 my $sig = $2;
206 my $full = "$plain:$username:$path";
207
208 my $rsa_pub = get_pubkey();
209 # Note: sign only match if $username and $path is correct
210 if ($rsa_pub->verify($full, decode_base64($sig))) {
211 if ($plain =~ m/^PVEVNC:([A-Z0-9]{8})$/) {
212 my $ttime = hex($1);
213
214 my $age = time() - $ttime;
215
216 if (($age > -20) && ($age < 40)) {
217 return 1;
218 }
219 }
220 }
221 }
222
223 die "permission denied - invalid vnc ticket\n" if !$noerr;
224
225 return undef;
226}
227
228
2c3a6c0a
DM
229sub authenticate_user_shadow {
230 my ($userid, $password) = @_;
231
232 die "no password\n" if !$password;
233
234 my $shadow_cfg = cfs_read_file($shadowconfigfile);
235
236 if ($shadow_cfg->{users}->{$userid}) {
237 my $encpw = crypt($password, $shadow_cfg->{users}->{$userid}->{shadow});
238 die "invalid credentials\n" if ($encpw ne $shadow_cfg->{users}->{$userid}->{shadow});
239 } else {
240 die "no password set\n";
241 }
242}
243
244sub authenticate_user_pam {
245 my ($userid, $password) = @_;
246
247 # user (www-data) need to be able to read /etc/passwd /etc/shadow
248
249 die "no password\n" if !$password;
250
251 my $pamh = new Authen::PAM ('common-auth', $userid, sub {
252 my @res;
253 while(@_) {
254 my $msg_type = shift;
255 my $msg = shift;
256 push @res, (0, $password);
257 }
258 push @res, 0;
259 return @res;
260 });
261
262 if (!ref ($pamh)) {
263 my $err = $pamh->pam_strerror($pamh);
264 die "error during PAM init: $err";
265 }
266
267 my $res;
268
269 if (($res = $pamh->pam_authenticate(0)) != PAM_SUCCESS) {
270 my $err = $pamh->pam_strerror($res);
271 die "$err\n";
272 }
273
274 if (($res = $pamh->pam_acct_mgmt (0)) != PAM_SUCCESS) {
275 my $err = $pamh->pam_strerror($res);
276 die "$err\n";
277 }
278
279 $pamh = 0; # call destructor
280}
281
282sub authenticate_user_ad {
283
284 my ($entry, $server, $userid, $password) = @_;
285
286 my $default_port = $entry->{secure} ? 636: 389;
287 my $port = $entry->{port} ? $entry->{port} : $default_port;
288 my $scheme = $entry->{secure} ? 'ldaps' : 'ldap';
289 my $conn_string = "$scheme://${server}:$port";
290
291 my $ldap = Net::LDAP->new($server) || die "$@\n";
292
293 $userid = "$userid\@$entry->{domain}"
294 if $userid !~ m/@/ && $entry->{domain};
295
296 my $res = $ldap->bind($userid, password => $password);
297
298 my $code = $res->code();
299 my $err = $res->error;
300
301 $ldap->unbind();
302
303 die "$err\n" if ($code);
304}
305
306sub authenticate_user_ldap {
307
308 my ($entry, $server, $userid, $password) = @_;
309
310 my $default_port = $entry->{secure} ? 636: 389;
311 my $port = $entry->{port} ? $entry->{port} : $default_port;
312 my $scheme = $entry->{secure} ? 'ldaps' : 'ldap';
313 my $conn_string = "$scheme://${server}:$port";
314
315 my $ldap = Net::LDAP->new($conn_string, verify => 'none') || die "$@\n";
316 my $search = $entry->{user_attr} . "=" . $userid;
317 my $result = $ldap->search( base => "$entry->{base_dn}",
318 scope => "sub",
319 filter => "$search",
320 attrs => ['dn']
321 );
322 die "no entries returned\n" if !$result->entries;
323 my @entries = $result->entries;
324 my $res = $ldap->bind($entries[0]->dn, password => $password);
325
326 my $code = $res->code();
327 my $err = $res->error;
328
329 $ldap->unbind();
330
331 die "$err\n" if ($code);
332}
333
334sub authenticate_user_domain {
335 my ($realm, $userid, $password) = @_;
336
337 my $domain_cfg = cfs_read_file($domainconfigfile);
338
339 die "no auth domain specified" if !$realm;
340
341 if ($realm eq 'pam') {
342 authenticate_user_pam($userid, $password);
343 return;
344 }
345
346 eval {
347 if ($realm eq 'pve') {
348 authenticate_user_shadow($userid, $password);
349 } else {
350
351 my $cfg = $domain_cfg->{$realm};
352 die "auth domain '$realm' does not exists\n" if !$cfg;
353
354 if ($cfg->{type} eq 'ad') {
355 eval { authenticate_user_ad($cfg, $cfg->{server1}, $userid, $password); };
356 my $err = $@;
357 return if !$err;
358 die $err if !$cfg->{server2};
359 authenticate_user_ad($cfg, $cfg->{server2}, $userid, $password);
360 } elsif ($cfg->{type} eq 'ldap') {
361 eval { authenticate_user_ldap($cfg, $cfg->{server1}, $userid, $password); };
362 my $err = $@;
363 return if !$err;
364 die $err if !$cfg->{server2};
365 authenticate_user_ldap($cfg, $cfg->{server2}, $userid, $password);
366 } else {
367 die "unknown auth type '$cfg->{type}'\n";
368 }
369 }
370 };
371 if (my $err = $@) {
372 sleep(2); # timeout after failed auth
373 die $err;
374 }
375}
376
37d45deb 377sub check_user_exist {
7070c1ae 378 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 379
7070c1ae 380 $username = verify_username($username, $noerr);
2c3a6c0a
DM
381 return undef if !$username;
382
37d45deb
DM
383 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
384
385 die "no such user ('$username')\n" if !$noerr;
386
387 return undef;
388}
389
390sub check_user_enabled {
391 my ($usercfg, $username, $noerr) = @_;
392
393 my $data = check_user_exist($usercfg, $username, $noerr);
394 return undef if !$data;
395
396 return 1 if $data->{enable};
2c3a6c0a
DM
397
398 return 1 if $username eq 'root@pam'; # root is always enabled
399
37d45deb 400 die "user '$username' is disabled\n" if !$noerr;
7070c1ae
DM
401
402 return undef;
2c3a6c0a
DM
403}
404
405# password should be utf8 encoded
406sub authenticate_user {
407 my ($username, $password) = @_;
408
409 die "no username specified\n" if !$username;
410
411 my ($userid, $realm);
412
413 ($username, $userid, $realm) = verify_username($username);
414
415 my $usercfg = cfs_read_file('user.cfg');
416
7070c1ae
DM
417 eval { check_user_enabled($usercfg, $username); };
418 if (my $err = $@) {
2c3a6c0a 419 sleep(2);
7070c1ae 420 die $err;
2c3a6c0a
DM
421 }
422
423 my $ctime = time();
424 my $expire = $usercfg->{users}->{$username}->{expire};
425
426 if ($expire && ($expire < $ctime)) {
427 sleep(2);
428 die "account expired\n"
429 }
430
431 authenticate_user_domain($realm, $userid, $password);
432
433 return $username;
434}
435
436sub delete_shadow_password {
437 my ($userid) = @_;
438
439 lock_shadow_config(sub {
440 my $shadow_cfg = cfs_read_file($shadowconfigfile);
441 delete ($shadow_cfg->{users}->{$userid})
442 if $shadow_cfg->{users}->{$userid};
443 cfs_write_file($shadowconfigfile, $shadow_cfg);
444 });
445}
446
447sub store_shadow_password {
448 my ($userid, $password) = @_;
449
450 lock_shadow_config(sub {
451 my $shadow_cfg = cfs_read_file($shadowconfigfile);
452 $shadow_cfg->{users}->{$userid}->{shadow} = encrypt_pw($password);
453 cfs_write_file($shadowconfigfile, $shadow_cfg);
454 });
455}
456
457sub encrypt_pw {
458 my ($pw) = @_;
459
460 my $time = substr (Digest::SHA::sha1_base64 (time), 0, 8);
461 return crypt (encode("utf8", $pw), "\$5\$$time\$");
462}
463
464sub store_pam_password {
465 my ($userid, $password) = @_;
466
2de14407 467 my $cmd = ['usermod'];
2c3a6c0a
DM
468
469 my $epw = encrypt_pw($password);
470 push @$cmd, '-p', $epw;
471
472 push @$cmd, $userid;
473
2de14407 474 run_command($cmd, errmsg => 'change password failed');
2c3a6c0a
DM
475}
476
477sub domain_set_password {
478 my ($realm, $userid, $password) = @_;
479
480 die "no auth domain specified" if !$realm;
481
482 if ($realm eq 'pam') {
483 store_pam_password($userid, $password);
484 } elsif ($realm eq 'pve') {
485 store_shadow_password($userid, $password);
486 } else {
487 die "can't set password on auth domain '$realm'\n";
488 }
489}
490
491sub add_user_group {
492
493 my ($username, $usercfg, $group) = @_;
494 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
495 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
496}
497
498sub delete_user_group {
499
500 my ($username, $usercfg) = @_;
501
502 foreach my $group (keys %{$usercfg->{groups}}) {
503
504 delete ($usercfg->{groups}->{$group}->{users}->{$username})
505 if $usercfg->{groups}->{$group}->{users}->{$username};
506 }
507}
508
509sub delete_user_acl {
510
511 my ($username, $usercfg) = @_;
512
513 foreach my $acl (keys %{$usercfg->{acl}}) {
514
515 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
516 if $usercfg->{acl}->{$acl}->{users}->{$username};
517 }
2c3a6c0a 518}
39c85db8 519
2c3a6c0a
DM
520sub delete_group_acl {
521
522 my ($group, $usercfg) = @_;
523
524 foreach my $acl (keys %{$usercfg->{acl}}) {
525
526 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
527 if $usercfg->{acl}->{$acl}->{groups}->{$group};
528 }
39c85db8
DM
529}
530
531sub delete_pool_acl {
532
533 my ($pool, $usercfg) = @_;
2c3a6c0a 534
39c85db8
DM
535 my $path = "/pool/$pool";
536
537 foreach my $aclpath (keys %{$usercfg->{acl}}) {
538 delete ($usercfg->{acl}->{$aclpath})
539 if $usercfg->{acl}->{$aclpath} eq 'path';
540 }
2c3a6c0a
DM
541}
542
543# we automatically create some predefined roles by splitting privs
544# into 3 groups (per category)
545# root: only root is allowed to do that
546# admin: an administrator can to that
547# user: a normak user/customer can to that
548my $privgroups = {
549 VM => {
550 root => [],
551 admin => [
c0fead8c 552 'VM.Config.Disk',
c0fead8c
DM
553 'VM.Config.CPU',
554 'VM.Config.Memory',
555 'VM.Config.Network',
556 'VM.Config.HWType',
557 'VM.Config.Options', # covers all other things
2c3a6c0a
DM
558 'VM.Allocate',
559 'VM.Migrate',
c0fead8c 560 'VM.Monitor',
2c3a6c0a
DM
561 ],
562 user => [
cc7bdf33 563 'VM.Config.CDROM', # change CDROM media
2c3a6c0a 564 'VM.Console',
68d5a86d 565 'VM.Backup',
2c3a6c0a
DM
566 'VM.PowerMgmt',
567 ],
568 audit => [
82b63965 569 'VM.Audit',
2c3a6c0a
DM
570 ],
571 },
572 Sys => {
573 root => [
574 'Sys.PowerMgmt',
37d45deb 575 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
576 ],
577 admin => [
2e376c58 578 'Permissions.Modify',
2c3a6c0a
DM
579 'Sys.Console',
580 'Sys.Syslog',
581 ],
582 user => [],
583 audit => [
584 'Sys.Audit',
585 ],
586 },
587 Datastore => {
2e376c58 588 root => [],
19f60b5e
DM
589 admin => [
590 'Datastore.Allocate',
373cb383 591 'Datastore.AllocateTemplate',
19f60b5e 592 ],
2c3a6c0a
DM
593 user => [
594 'Datastore.AllocateSpace',
595 ],
596 audit => [
597 'Datastore.Audit',
598 ],
599 },
12683df7 600 User => {
82b63965
DM
601 root => [
602 'Realm.Allocate',
603 ],
12683df7
DM
604 admin => [
605 'User.Modify',
82b63965
DM
606 'Group.Allocate', # edit/change group settings
607 'Realm.AllocateUser',
19f60b5e 608 ],
12683df7
DM
609 user => [],
610 audit => [],
611 },
dee1c882
DM
612 Pool => {
613 root => [],
614 admin => [
615 'Pool.Allocate', # create/delete pools
616 ],
617 user => [],
618 audit => [],
619 },
2c3a6c0a
DM
620};
621
622my $valid_privs = {};
623
624my $special_roles = {
625 'NoAccess' => {}, # no priviledges
626 'Administrator' => $valid_privs, # all priviledges
627};
628
629sub create_roles {
630
631 foreach my $cat (keys %$privgroups) {
632 my $cd = $privgroups->{$cat};
633 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
634 @{$cd->{user}}, @{$cd->{audit}}) {
635 $valid_privs->{$p} = 1;
636 }
637 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
638
639 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
640 $special_roles->{"PVEAdmin"}->{$p} = 1;
641 }
642 if (scalar(@{$cd->{user}})) {
643 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
644 $special_roles->{"PVE${cat}User"}->{$p} = 1;
645 }
646 }
647 foreach my $p (@{$cd->{audit}}) {
648 $special_roles->{"PVEAuditor"}->{$p} = 1;
649 }
650 }
651};
652
653create_roles();
654
655my $valid_attributes = {
656 ad => {
657 server1 => '[\w\d]+(.[\w\d]+)*',
658 server2 => '[\w\d]+(.[\w\d]+)*',
659 domain => '\S+',
af4a8a85 660 port => '\d+',
2c3a6c0a
DM
661 secure => '',
662 comment => '.*',
663 },
664 ldap => {
665 server1 => '[\w\d]+(.[\w\d]+)*',
666 server2 => '[\w\d]+(.[\w\d]+)*',
d9483d94 667 base_dn => '\w+=[^,]+(,\s*\w+=[^,]+)*',
2c3a6c0a
DM
668 user_attr => '\S{2,}',
669 secure => '',
af4a8a85 670 port => '\d+',
2c3a6c0a
DM
671 comment => '.*',
672 }
673};
674
675sub add_role_privs {
676 my ($role, $usercfg, $privs) = @_;
677
678 return if !$privs;
679
680 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
681
682 foreach my $priv (split_list($privs)) {
683 if (defined ($valid_privs->{$priv})) {
684 $usercfg->{roles}->{$role}->{$priv} = 1;
685 } else {
686 die "invalid priviledge '$priv'\n";
687 }
688 }
689}
690
691sub normalize_path {
692 my $path = shift;
693
4bc17477 694 $path =~ s|/+|/|g;
2c3a6c0a
DM
695
696 $path =~ s|/$||;
697
698 $path = '/' if !$path;
699
4bc17477
DM
700 $path = "/$path" if $path !~ m|^/|;
701
2c3a6c0a
DM
702 return undef if $path !~ m|^[[:alnum:]\-\_\/]+$|;
703
704 return $path;
705}
706
707my $realm_regex = qr/[A-Za-z][A-Za-z0-9\.\-_]+/;
708
84619607 709PVE::JSONSchema::register_format('pve-realm', \&pve_verify_realm);
2c3a6c0a
DM
710sub pve_verify_realm {
711 my ($realm, $noerr) = @_;
712
713 if ($realm !~ m/^${realm_regex}$/) {
714 return undef if $noerr;
715 die "value does not look like a valid realm\n";
716 }
717 return $realm;
718}
719
720PVE::JSONSchema::register_format('pve-userid', \&verify_username);
721sub verify_username {
722 my ($username, $noerr) = @_;
723
724 $username = '' if !$username;
725 my $len = length($username);
726 if ($len < 3) {
727 die "user name '$username' is too short\n" if !$noerr;
728 return undef;
729 }
730 if ($len > 64) {
731 die "user name '$username' is too long ($len > 64)\n" if !$noerr;
732 return undef;
733 }
734
3030a176
DM
735 # we only allow a limited set of characters
736 # colon is not allowed, because we store usernames in
737 # colon separated lists)!
738 # slash is not allowed because it is used as pve API delimiter
739 # also see "man useradd"
740 if ($username =~ m!^([^\s:/]+)\@(${realm_regex})$!) {
2c3a6c0a
DM
741 return wantarray ? ($username, $1, $2) : $username;
742 }
743
744 die "value '$username' does not look like a valid user name\n" if !$noerr;
745
746 return undef;
747}
748PVE::JSONSchema::register_standard_option('userid', {
749 description => "User ID",
750 type => 'string', format => 'pve-userid',
751 maxLength => 64,
752});
753
754PVE::JSONSchema::register_standard_option('realm', {
755 description => "Authentication domain ID",
84619607 756 type => 'string', format => 'pve-realm',
2c3a6c0a
DM
757 maxLength => 32,
758});
759
760PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
761sub verify_groupname {
762 my ($groupname, $noerr) = @_;
763
764 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
765
766 die "group name '$groupname' contains invalid characters\n" if !$noerr;
767
768 return undef;
769 }
770
771 return $groupname;
772}
773
774PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
775sub verify_rolename {
776 my ($rolename, $noerr) = @_;
777
778 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
779
780 die "role name '$rolename' contains invalid characters\n" if !$noerr;
781
782 return undef;
783 }
784
785 return $rolename;
786}
787
39c85db8
DM
788PVE::JSONSchema::register_format('pve-poolid', \&verify_groupname);
789sub verify_poolname {
790 my ($poolname, $noerr) = @_;
791
792 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
793
794 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
795
796 return undef;
797 }
798
799 return $poolname;
800}
801
2c3a6c0a
DM
802PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
803sub verify_privname {
804 my ($priv, $noerr) = @_;
805
806 if (!$valid_privs->{$priv}) {
807 die "invalid priviledge '$priv'\n" if !$noerr;
808
809 return undef;
810 }
811
812 return $priv;
813}
814
815sub userconfig_force_defaults {
816 my ($cfg) = @_;
817
818 foreach my $r (keys %$special_roles) {
819 $cfg->{roles}->{$r} = $special_roles->{$r};
820 }
821
822 # fixme: remove 'root' group (not required)?
823
824 # add root user
825 $cfg->{users}->{'root@pam'}->{enable} = 1;
826}
827
828sub parse_user_config {
829 my ($filename, $raw) = @_;
830
831 my $cfg = {};
832
833 userconfig_force_defaults($cfg);
834
835 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
836 my $line = $1;
837
838 next if $line =~ m/^\s*$/; # skip empty lines
839
840 my @data;
841
842 foreach my $d (split (/:/, $line)) {
843 $d =~ s/^\s+//;
844 $d =~ s/\s+$//;
845 push @data, $d
846 }
847
848 my $et = shift @data;
849
850 if ($et eq 'user') {
851 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment) = @data;
852
853 my (undef, undef, $realm) = verify_username($user, 1);
854 if (!$realm) {
855 warn "user config - ignore user '$user' - invalid user name\n";
856 next;
857 }
858
859 $enable = $enable ? 1 : 0;
860
861 $expire = 0 if !$expire;
862
863 if ($expire !~ m/^\d+$/) {
864 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
865 next;
866 }
867 $expire = int($expire);
868
869 #if (!verify_groupname ($group, 1)) {
870 # warn "user config - ignore user '$user' - invalid characters in group name\n";
871 # next;
872 #}
873
874 $cfg->{users}->{$user} = {
875 enable => $enable,
876 # group => $group,
877 };
878 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
879 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
880 $cfg->{users}->{$user}->{email} = $email;
881 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
882 $cfg->{users}->{$user}->{expire} = $expire;
883
884 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
885 #$cfg->{groups}->{$group}->{$user} = 1;
886
887 } elsif ($et eq 'group') {
888 my ($group, $userlist, $comment) = @data;
889
890 if (!verify_groupname($group, 1)) {
891 warn "user config - ignore group '$group' - invalid characters in group name\n";
892 next;
893 }
894
895 # make sure to add the group (even if there are no members)
896 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
897
898 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
899
900 foreach my $user (split_list($userlist)) {
901
902 if (!verify_username($user, 1)) {
903 warn "user config - ignore invalid group member '$user'\n";
904 next;
905 }
906
907 if ($cfg->{users}->{$user}) { # user exists
908 $cfg->{users}->{$user}->{groups}->{$group} = 1;
909 $cfg->{groups}->{$group}->{users}->{$user} = 1;
910 } else {
911 warn "user config - ignore invalid group member '$user'\n";
912 }
913 }
914
915 } elsif ($et eq 'role') {
916 my ($role, $privlist) = @data;
917
918 if (!verify_rolename($role, 1)) {
919 warn "user config - ignore role '$role' - invalid characters in role name\n";
920 next;
921 }
922
923 # make sure to add the role (even if there are no privileges)
924 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
925
926 foreach my $priv (split_list($privlist)) {
927 if (defined ($valid_privs->{$priv})) {
928 $cfg->{roles}->{$role}->{$priv} = 1;
929 } else {
930 warn "user config - ignore invalid priviledge '$priv'\n";
931 }
932 }
933
934 } elsif ($et eq 'acl') {
935 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
936
937 if (my $path = normalize_path($pathtxt)) {
938 foreach my $role (split_list($rolelist)) {
939
940 if (!verify_rolename($role, 1)) {
941 warn "user config - ignore invalid role name '$role' in acl\n";
942 next;
943 }
944
945 foreach my $ug (split_list($uglist)) {
9b217226 946 if ($ug =~ m/^@(\S+)$/) {
2c3a6c0a
DM
947 my $group = $1;
948 if ($cfg->{groups}->{$group}) { # group exists
949 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
950 } else {
951 warn "user config - ignore invalid acl group '$group'\n";
952 }
953 } elsif (verify_username($ug, 1)) {
954 if ($cfg->{users}->{$ug}) { # user exists
955 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
956 } else {
957 warn "user config - ignore invalid acl member '$ug'\n";
958 }
959 } else {
960 warn "user config - invalid user/group '$ug' in acl\n";
961 }
962 }
963 }
964 } else {
965 warn "user config - ignore invalid path in acl '$pathtxt'\n";
966 }
4bc17477 967 } elsif ($et eq 'pool') {
39c85db8 968 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 969
39c85db8
DM
970 if (!verify_poolname($pool, 1)) {
971 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
972 next;
973 }
4bc17477 974
39c85db8
DM
975 # make sure to add the pool (even if there are no members)
976 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 977
39c85db8 978 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 979
39c85db8
DM
980 foreach my $vmid (split_list($vmlist)) {
981 if ($vmid !~ m/^\d+$/) {
982 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
983 next;
4bc17477 984 }
39c85db8 985 $vmid = int($vmid);
4bc17477 986
39c85db8
DM
987 if ($cfg->{vms}->{$vmid}) {
988 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
989 next;
4bc17477
DM
990 }
991
39c85db8
DM
992 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
993
994 # record vmid ==> pool relation
995 $cfg->{vms}->{$vmid} = $pool;
996 }
997
998 foreach my $storeid (split_list($storelist)) {
999 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
1000 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
1001 next;
1002 }
1003 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
4bc17477 1004 }
2c3a6c0a
DM
1005 } else {
1006 warn "user config - ignore config line: $line\n";
1007 }
1008 }
1009
1010 userconfig_force_defaults($cfg);
1011
1012 return $cfg;
1013}
1014
1015sub parse_shadow_passwd {
1016 my ($filename, $raw) = @_;
1017
1018 my $shadow = {};
1019
1020 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
1021 my $line = $1;
1022
1023 next if $line =~ m/^\s*$/; # skip empty lines
1024
1025 if ($line !~ m/^\S+:\S+:$/) {
1026 warn "pve shadow password: ignore invalid line $.\n";
1027 next;
1028 }
1029
1030 my ($userid, $crypt_pass) = split (/:/, $line);
1031 $shadow->{users}->{$userid}->{shadow} = $crypt_pass;
1032 }
1033
1034 return $shadow;
1035}
1036
1037sub write_domains {
1038 my ($filename, $cfg) = @_;
1039
1040 my $data = '';
1041
1042 my $wrote_default;
1043
1044 foreach my $realm (sort keys %$cfg) {
1045 my $entry = $cfg->{$realm};
1046 my $type = lc($entry->{type});
1047
1048 next if !$type;
1049
1050 next if ($type eq 'pam') || ($type eq 'pve');
1051
1052 my $formats = $valid_attributes->{$type};
1053 next if !$formats;
1054
1055 $data .= "$type: $realm\n";
1056
1057 foreach my $k (sort keys %$entry) {
1058 next if $k eq 'type';
1059 my $v = $entry->{$k};
1060 if ($k eq 'default') {
1061 $data .= "\t$k\n" if $v && !$wrote_default;
1062 $wrote_default = 1;
1063 } elsif (defined($formats->{$k})) {
1064 if (!$formats->{$k}) {
0c156363 1065 $data .= "\t$k\n" if $v;
2c3a6c0a
DM
1066 } elsif ($v =~ m/^$formats->{$k}$/) {
1067 $v = PVE::Tools::encode_text($v) if $k eq 'comment';
1068 $data .= "\t$k $v\n";
1069 } else {
1070 die "invalid value '$v' for attribute '$k'\n";
1071 }
1072 } else {
1073 die "invalid attribute '$k' - not supported\n";
1074 }
1075 }
1076
1077 $data .= "\n";
1078 }
1079
1080 return $data;
1081}
1082
1083sub parse_domains {
1084 my ($filename, $raw) = @_;
1085
1086 my $cfg = {};
1087
1088 my $default;
1089
1090 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
1091 my $line = $1;
1092
1093 next if $line =~ m/^\#/; # skip comment lines
1094 next if $line =~ m/^\s*$/; # skip empty lines
1095
1096 if ($line =~ m/^(\S+):\s*(\S+)\s*$/) {
1097 my $realm = $2;
1098 my $type = lc($1);
1099
1100 my $ignore = 0;
1101 my $entry;
1102
1103 my $formats = $valid_attributes->{$type};
1104 if (!$formats) {
1105 $ignore = 1;
1106 warn "ignoring domain '$realm' - (unsupported authentication type '$type')\n";
1107 } elsif (!pve_verify_realm($realm, 1)) {
1108 $ignore = 1;
1109 warn "ignoring domain '$realm' - (illegal characters)\n";
1110 } else {
1111 $entry = { type => $type };
1112 }
1113
1114 while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
1115 $line = $1;
1116
1117 next if $line =~ m/^\#/; #skip comment lines
1118 last if $line =~ m/^\s*$/;
1119
1120 next if $ignore; # skip
1121
1122 if ($line =~ m/^\s+(default)\s*$/) {
1123 $default = $realm if !$default;
1124 } elsif ($line =~ m/^\s+(\S+)(\s+(.*\S))?\s*$/) {
1125 my ($k, $v) = (lc($1), $3);
1126 if (defined($formats->{$k})) {
1127 if (!$formats->{$k} && !defined($v)) {
1128 $entry->{$k} = 1;
1129 } elsif ($formats->{$k} && $v =~ m/^$formats->{$k}$/) {
1130 if (!defined($entry->{$k})) {
1131 $v = PVE::Tools::decode_text($v) if $k eq 'comment';
1132 $entry->{$k} = $v;
1133 } else {
1134 warn "ignoring duplicate attribute '$k $v'\n";
1135 }
1136 } else {
1137 warn "ignoring value '$v' for attribute '$k' - invalid format\n";
1138 }
1139 } else {
1140 warn "ignoring attribute '$k' - not supported\n";
1141 }
1142 } else {
1143 warn "ignore config line: $line\n";
1144 }
1145 }
1146
1147 if ($entry->{server2} && !$entry->{server1}) {
1148 $entry->{server1} = $entry->{server2};
1149 delete $entry->{server2};
1150 }
1151
1152 if ($ignore) {
1153 # do nothing
1154 } elsif (!$entry->{server1}) {
1155 warn "ignoring domain '$realm' - missing server attribute\n";
1156 } elsif (($entry->{type} eq "ldap") && !$entry->{user_attr}) {
1157 warn "ignoring domain '$realm' - missing user attribute\n";
1158 } elsif (($entry->{type} eq "ldap") && !$entry->{base_dn}) {
1159 warn "ignoring domain '$realm' - missing base_dn attribute\n";
0c156363
DM
1160 } elsif (($entry->{type} eq "ad") && !$entry->{domain}) {
1161 warn "ignoring domain '$realm' - missing domain attribute\n";
2c3a6c0a
DM
1162 } else {
1163 $cfg->{$realm} = $entry;
1164 }
1165
1166 } else {
1167 warn "ignore config line: $line\n";
1168 }
1169 }
1170
1171 $cfg->{$default}->{default} = 1 if $default;
1172
1173 # add default domains
1174
1175 $cfg->{pve} = {
1176 type => 'builtin',
1177 comment => "Proxmox VE authentication server",
1178 };
1179
1180 $cfg->{pam} = {
1181 type => 'builtin',
1182 comment => "Linux PAM standard authentication",
1183 };
1184
1185 return $cfg;
1186}
1187
1188sub write_shadow_config {
1189 my ($filename, $cfg) = @_;
1190
1191 my $data = '';
1192 foreach my $userid (keys %{$cfg->{users}}) {
1193 my $crypt_pass = $cfg->{users}->{$userid}->{shadow};
1194 $data .= "$userid:$crypt_pass:\n";
1195 }
1196
1197 return $data
1198}
1199
1200sub write_user_config {
1201 my ($filename, $cfg) = @_;
1202
1203 my $data = '';
1204
1205 foreach my $user (keys %{$cfg->{users}}) {
2c3a6c0a
DM
1206 my $d = $cfg->{users}->{$user};
1207 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
1208 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
1209 my $email = $d->{email} || '';
1210 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 1211 my $expire = int($d->{expire} || 0);
2c3a6c0a
DM
1212 my $enable = $d->{enable} ? 1 : 0;
1213 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:\n";
1214 }
1215
1216 $data .= "\n";
1217
1218 foreach my $group (keys %{$cfg->{groups}}) {
1219 my $d = $cfg->{groups}->{$group};
1220 my $list = join (',', keys %{$d->{users}});
1221 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
1222 $data .= "group:$group:$list:$comment:\n";
1223 }
1224
1225 $data .= "\n";
1226
39c85db8
DM
1227 foreach my $pool (keys %{$cfg->{pools}}) {
1228 my $d = $cfg->{pools}->{$pool};
4bc17477
DM
1229 my $vmlist = join (',', keys %{$d->{vms}});
1230 my $storelist = join (',', keys %{$d->{storage}});
1231 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 1232 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
1233 }
1234
1235 $data .= "\n";
1236
2c3a6c0a
DM
1237 foreach my $role (keys %{$cfg->{roles}}) {
1238 next if $special_roles->{$role};
1239
1240 my $d = $cfg->{roles}->{$role};
1241 my $list = join (',', keys %$d);
1242 $data .= "role:$role:$list:\n";
1243 }
1244
1245 $data .= "\n";
1246
1247 foreach my $path (sort keys %{$cfg->{acl}}) {
1248 my $d = $cfg->{acl}->{$path};
1249
1250 my $ra = {};
1251
1252 foreach my $group (keys %{$d->{groups}}) {
1253 my $l0 = '';
1254 my $l1 = '';
1255 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
1256 my $propagate = $d->{groups}->{$group}->{$role};
1257 if ($propagate) {
1258 $l1 .= ',' if $l1;
1259 $l1 .= $role;
1260 } else {
1261 $l0 .= ',' if $l0;
1262 $l0 .= $role;
1263 }
1264 }
1265 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
1266 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
1267 }
1268
1269 foreach my $user (keys %{$d->{users}}) {
1270 # no need to save, because root is always 'Administartor'
1271 next if $user eq 'root@pam';
1272
1273 my $l0 = '';
1274 my $l1 = '';
1275 foreach my $role (sort keys %{$d->{users}->{$user}}) {
1276 my $propagate = $d->{users}->{$user}->{$role};
1277 if ($propagate) {
1278 $l1 .= ',' if $l1;
1279 $l1 .= $role;
1280 } else {
1281 $l0 .= ',' if $l0;
1282 $l0 .= $role;
1283 }
1284 }
1285 $ra->{0}->{$l0}->{$user} = 1 if $l0;
1286 $ra->{1}->{$l1}->{$user} = 1 if $l1;
1287 }
1288
1289 foreach my $rolelist (sort keys %{$ra->{0}}) {
1290 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
1291 $data .= "acl:0:$path:$uglist:$rolelist:\n";
1292 }
1293 foreach my $rolelist (sort keys %{$ra->{1}}) {
1294 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
1295 $data .= "acl:1:$path:$uglist:$rolelist:\n";
1296 }
1297 }
1298
1299 return $data;
1300}
1301
1302sub roles {
1303 my ($cfg, $user, $path) = @_;
1304
4bc17477
DM
1305 # NOTE: we do not consider pools here.
1306 # You need to use $rpcenv->roles() instead if you want that.
1307
2c3a6c0a
DM
1308 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1309
1310 my $perm = {};
1311
1312 foreach my $p (sort keys %{$cfg->{acl}}) {
1313 my $final = ($path eq $p);
1314
1315 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1316
1317 my $acl = $cfg->{acl}->{$p};
1318
1319 #print "CHECKACL $path $p\n";
1320 #print "ACL $path = " . Dumper ($acl);
1321
1322 if (my $ri = $acl->{users}->{$user}) {
1323 my $new;
1324 foreach my $role (keys %$ri) {
1325 my $propagate = $ri->{$role};
1326 if ($final || $propagate) {
1327 #print "APPLY ROLE $p $user $role\n";
1328 $new = {} if !$new;
1329 $new->{$role} = 1;
1330 }
1331 }
1332 if ($new) {
1333 $perm = $new; # overwrite previous settings
1334 next; # user privs always override group privs
1335 }
1336 }
1337
1338 my $new;
1339 foreach my $g (keys %{$acl->{groups}}) {
1340 next if !$cfg->{groups}->{$g}->{users}->{$user};
1341 if (my $ri = $acl->{groups}->{$g}) {
1342 foreach my $role (keys %$ri) {
1343 my $propagate = $ri->{$role};
1344 if ($final || $propagate) {
1345 #print "APPLY ROLE $p \@$g $role\n";
1346 $new = {} if !$new;
1347 $new->{$role} = 1;
1348 }
1349 }
1350 }
1351 }
1352 if ($new) {
1353 $perm = $new; # overwrite previous settings
1354 next;
1355 }
2c3a6c0a
DM
1356 }
1357
4bc17477
DM
1358 return ('NoAccess') if defined ($perm->{NoAccess});
1359 #return () if defined ($perm->{NoAccess});
2c3a6c0a
DM
1360
1361 #print "permission $user $path = " . Dumper ($perm);
1362
4bc17477 1363 my @ra = keys %$perm;
2c3a6c0a
DM
1364
1365 #print "roles $user $path = " . join (',', @ra) . "\n";
1366
1367 return @ra;
1368}
1369
1370sub permission {
1371 my ($cfg, $user, $path) = @_;
1372
1373 $user = verify_username($user, 1);
1374 return {} if !$user;
1375
1376 my @ra = roles($cfg, $user, $path);
1377
1378 my $privs = {};
1379
1380 foreach my $role (@ra) {
1381 if (my $privset = $cfg->{roles}->{$role}) {
1382 foreach my $p (keys %$privset) {
1383 $privs->{$p} = 1;
1384 }
1385 }
1386 }
1387
1388 #print "priviledges $user $path = " . Dumper ($privs);
1389
1390 return $privs;
1391}
1392
1393sub check_permissions {
1394 my ($username, $path, $privlist) = @_;
1395
1396 $path = normalize_path($path);
1397 my $usercfg = cfs_read_file('user.cfg');
1398 my $perm = permission($usercfg, $username, $path);
1399
1400 foreach my $priv (split_list($privlist)) {
1401 return undef if !$perm->{$priv};
1402 };
1403
1404 return 1;
1405}
1406
14071;