change from dpkg-deb to dpkg-buildpackage
[pve-access-control.git] / PVE / AccessControl.pm
CommitLineData
2c3a6c0a
DM
1package PVE::AccessControl;
2
3use strict;
7c410d63 4use warnings;
2c3a6c0a
DM
5use Encode;
6use Crypt::OpenSSL::Random;
7use Crypt::OpenSSL::RSA;
cee5583b 8use Net::SSLeay;
25167526 9use Net::IP;
2c3a6c0a
DM
10use MIME::Base64;
11use Digest::SHA;
a1f8aaae 12
972859d1 13use PVE::OTP;
a1f8aaae 14use PVE::Ticket;
2c3a6c0a
DM
15use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
16use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
17use PVE::JSONSchema;
5bb4e06a
DM
18
19use PVE::Auth::Plugin;
20use PVE::Auth::AD;
21use PVE::Auth::LDAP;
22use PVE::Auth::PVE;
23use PVE::Auth::PAM;
2c3a6c0a
DM
24
25use Data::Dumper; # fixme: remove
26
5bb4e06a
DM
27# load and initialize all plugins
28
29PVE::Auth::AD->register();
30PVE::Auth::LDAP->register();
31PVE::Auth::PVE->register();
32PVE::Auth::PAM->register();
33PVE::Auth::Plugin->init();
34
2c3a6c0a
DM
35# $authdir must be writable by root only!
36my $confdir = "/etc/pve";
37my $authdir = "$confdir/priv";
38my $authprivkeyfn = "$authdir/authkey.key";
39my $authpubkeyfn = "$confdir/authkey.pub";
2c3a6c0a
DM
40my $pve_www_key_fn = "$confdir/pve-www.key";
41
42my $ticket_lifetime = 3600*2; # 2 hours
43
44Crypt::OpenSSL::RSA->import_random_seed();
45
66931b11
DM
46cfs_register_file('user.cfg',
47 \&parse_user_config,
2c3a6c0a
DM
48 \&write_user_config);
49
2c3a6c0a 50
5bb4e06a
DM
51sub verify_username {
52 PVE::Auth::Plugin::verify_username(@_);
2c3a6c0a
DM
53}
54
5bb4e06a
DM
55sub pve_verify_realm {
56 PVE::Auth::Plugin::pve_verify_realm(@_);
2c3a6c0a
DM
57}
58
5bb4e06a 59sub lock_user_config {
2c3a6c0a
DM
60 my ($code, $errmsg) = @_;
61
5bb4e06a
DM
62 cfs_lock_file("user.cfg", undef, $code);
63 if (my $err = $@) {
2c3a6c0a
DM
64 $errmsg ? die "$errmsg: $err" : die $err;
65 }
66}
67
68my $pve_auth_pub_key;
66931b11 69sub get_pubkey {
2c3a6c0a
DM
70
71 return $pve_auth_pub_key if $pve_auth_pub_key;
72
66931b11 73 my $input = PVE::Tools::file_get_contents($authpubkeyfn);
2c3a6c0a
DM
74
75 $pve_auth_pub_key = Crypt::OpenSSL::RSA->new_public_key($input);
76
77 return $pve_auth_pub_key;
78}
79
80my $csrf_prevention_secret;
81my $get_csrfr_secret = sub {
82 if (!$csrf_prevention_secret) {
66931b11 83 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
2c3a6c0a
DM
84 $csrf_prevention_secret = Digest::SHA::sha1_base64($input);
85 }
86 return $csrf_prevention_secret;
87};
88
89sub assemble_csrf_prevention_token {
90 my ($username) = @_;
91
a1f8aaae 92 my $secret = &$get_csrfr_secret();
2c3a6c0a 93
a1f8aaae 94 return PVE::Ticket::assemble_csrf_prevention_token ($secret, $username);
2c3a6c0a
DM
95}
96
97sub verify_csrf_prevention_token {
98 my ($username, $token, $noerr) = @_;
99
a1f8aaae 100 my $secret = &$get_csrfr_secret();
2c3a6c0a 101
a1f8aaae
DM
102 return PVE::Ticket::verify_csrf_prevention_token(
103 $secret, $username, $token, -300, $ticket_lifetime, $noerr);
2c3a6c0a
DM
104}
105
106my $pve_auth_priv_key;
107sub get_privkey {
108
109 return $pve_auth_priv_key if $pve_auth_priv_key;
110
66931b11 111 my $input = PVE::Tools::file_get_contents($authprivkeyfn);
2c3a6c0a
DM
112
113 $pve_auth_priv_key = Crypt::OpenSSL::RSA->new_private_key($input);
114
115 return $pve_auth_priv_key;
116}
117
118sub assemble_ticket {
119 my ($username) = @_;
120
121 my $rsa_priv = get_privkey();
122
a1f8aaae 123 return PVE::Ticket::assemble_rsa_ticket($rsa_priv, 'PVE', $username);
2c3a6c0a
DM
124}
125
126sub verify_ticket {
127 my ($ticket, $noerr) = @_;
128
a1f8aaae
DM
129 my $rsa_pub = get_pubkey();
130
131 my ($username, $age) = PVE::Ticket::verify_rsa_ticket(
132 $rsa_pub, 'PVE', $ticket, undef, -300, $ticket_lifetime, $noerr);
133
134 return undef if $noerr && !defined($username);
2c3a6c0a 135
a1f8aaae 136 return undef if !PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 137
a1f8aaae 138 return wantarray ? ($username, $age) : $username;
2c3a6c0a
DM
139}
140
adf8d771
DM
141# VNC tickets
142# - they do not contain the username in plain text
143# - they are restricted to a specific resource path (example: '/vms/100')
144sub assemble_vnc_ticket {
145 my ($username, $path) = @_;
146
147 my $rsa_priv = get_privkey();
148
adf8d771
DM
149 $path = normalize_path($path);
150
a1f8aaae 151 my $secret_data = "$username:$path";
adf8d771 152
a1f8aaae
DM
153 return PVE::Ticket::assemble_rsa_ticket(
154 $rsa_priv, 'PVEVNC', undef, $secret_data);
adf8d771
DM
155}
156
157sub verify_vnc_ticket {
158 my ($ticket, $username, $path, $noerr) = @_;
159
a1f8aaae 160 my $rsa_pub = get_pubkey();
adf8d771 161
a1f8aaae 162 my $secret_data = "$username:$path";
adf8d771 163
a1f8aaae
DM
164 return PVE::Ticket::verify_rsa_ticket(
165 $rsa_pub, 'PVEVNC', $ticket, $secret_data, -20, 40, $noerr);
adf8d771
DM
166}
167
23b35225 168sub assemble_spice_ticket {
bf3e6d31 169 my ($username, $vmid, $node) = @_;
23b35225 170
3f62bdbe 171 my $secret = &$get_csrfr_secret();
23b35225 172
a1f8aaae
DM
173 return PVE::Ticket::assemble_spice_ticket(
174 $secret, $username, $vmid, $node);
bf3e6d31
DM
175}
176
a1f8aaae 177
bf3e6d31
DM
178sub verify_spice_connect_url {
179 my ($connect_str) = @_;
180
a1f8aaae 181 my $secret = &$get_csrfr_secret();
bf3e6d31 182
a1f8aaae 183 return PVE::Ticket::verify_spice_connect_url($secret, $connect_str);
23b35225
AD
184}
185
cee5583b
DM
186sub read_x509_subject_spice {
187 my ($filename) = @_;
188
189 # read x509 subject
190 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
44903703
FG
191 die "Could not open $filename using OpenSSL\n"
192 if !$bio;
193
cee5583b
DM
194 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
195 Net::SSLeay::BIO_free($bio);
44903703
FG
196
197 die "Could not parse X509 certificate in $filename\n"
198 if !$x509;
199
cee5583b
DM
200 my $nameobj = Net::SSLeay::X509_get_subject_name($x509);
201 my $subject = Net::SSLeay::X509_NAME_oneline($nameobj);
202 Net::SSLeay::X509_free($x509);
66931b11 203
cee5583b
DM
204 # remote-viewer wants comma as seperator (not '/')
205 $subject =~ s!^/!!;
206 $subject =~ s!/(\w+=)!,$1!g;
207
208 return $subject;
209}
210
211# helper to generate SPICE remote-viewer configuration
212sub remote_viewer_config {
213 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
214
215 if (!$proxy) {
216 my $host = `hostname -f` || PVE::INotify::nodename();
217 chomp $host;
218 $proxy = $host;
219 }
220
221 my ($ticket, $proxyticket) = assemble_spice_ticket($authuser, $vmid, $node);
222
223 my $filename = "/etc/pve/local/pve-ssl.pem";
224 my $subject = read_x509_subject_spice($filename);
225
226 my $cacert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192);
227 $cacert =~ s/\n/\\n/g;
63691fc6 228
25167526 229 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
cee5583b 230 my $config = {
63691fc6
DM
231 'secure-attention' => "Ctrl+Alt+Ins",
232 'toggle-fullscreen' => "Shift+F11",
233 'release-cursor' => "Ctrl+Alt+R",
cee5583b
DM
234 type => 'spice',
235 title => $title,
1075c589 236 host => $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
cee5583b
DM
237 proxy => "http://$proxy:3128",
238 'tls-port' => $port,
239 'host-subject' => $subject,
240 ca => $cacert,
241 password => $ticket,
242 'delete-this-file' => 1,
243 };
244
245 return ($ticket, $proxyticket, $config);
246}
247
37d45deb 248sub check_user_exist {
7070c1ae 249 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 250
5bb4e06a 251 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 252 return undef if !$username;
66931b11 253
37d45deb
DM
254 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
255
256 die "no such user ('$username')\n" if !$noerr;
66931b11 257
37d45deb
DM
258 return undef;
259}
260
261sub check_user_enabled {
262 my ($usercfg, $username, $noerr) = @_;
263
264 my $data = check_user_exist($usercfg, $username, $noerr);
265 return undef if !$data;
266
267 return 1 if $data->{enable};
2c3a6c0a 268
37d45deb 269 die "user '$username' is disabled\n" if !$noerr;
66931b11 270
7070c1ae 271 return undef;
2c3a6c0a
DM
272}
273
96f8ebd6
DM
274sub verify_one_time_pw {
275 my ($usercfg, $username, $tfa_cfg, $otp) = @_;
276
277 my $type = $tfa_cfg->{type};
278
1075c589 279 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
96f8ebd6
DM
280
281 # fixme: proxy support?
282 my $proxy;
283
284 if ($type eq 'yubico') {
285 my $keys = $usercfg->{users}->{$username}->{keys};
972859d1
DM
286 PVE::OTP::yubico_verify_otp($otp, $keys, $tfa_cfg->{url},
287 $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
1abc2c0a
DM
288 } elsif ($type eq 'oath') {
289 my $keys = $usercfg->{users}->{$username}->{keys};
972859d1 290 PVE::OTP::oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
96f8ebd6
DM
291 } else {
292 die "unknown tfa type '$type'\n";
293 }
96f8ebd6
DM
294}
295
2c3a6c0a 296# password should be utf8 encoded
1075c589 297# Note: some plugins delay/sleep if auth fails
2c3a6c0a 298sub authenticate_user {
96f8ebd6 299 my ($username, $password, $otp) = @_;
2c3a6c0a
DM
300
301 die "no username specified\n" if !$username;
66931b11 302
5bb4e06a 303 my ($ruid, $realm);
2c3a6c0a 304
5bb4e06a 305 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
2c3a6c0a
DM
306
307 my $usercfg = cfs_read_file('user.cfg');
308
6126ab75 309 check_user_enabled($usercfg, $username);
2c3a6c0a
DM
310
311 my $ctime = time();
312 my $expire = $usercfg->{users}->{$username}->{expire};
313
6126ab75 314 die "account expired\n" if $expire && ($expire < $ctime);
2c3a6c0a 315
5bb4e06a 316 my $domain_cfg = cfs_read_file('domains.cfg');
2c3a6c0a 317
6126ab75
DM
318 my $cfg = $domain_cfg->{ids}->{$realm};
319 die "auth domain '$realm' does not exists\n" if !$cfg;
320 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
321 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
2c3a6c0a 322
96f8ebd6
DM
323 if ($cfg->{tfa}) {
324 my $tfa_cfg = PVE::Auth::Plugin::parse_tfa_config($cfg->{tfa});
325 verify_one_time_pw($usercfg, $username, $tfa_cfg, $otp);
326 }
327
5bb4e06a 328 return $username;
2c3a6c0a
DM
329}
330
331sub domain_set_password {
5bb4e06a 332 my ($realm, $username, $password) = @_;
2c3a6c0a
DM
333
334 die "no auth domain specified" if !$realm;
335
5bb4e06a
DM
336 my $domain_cfg = cfs_read_file('domains.cfg');
337
338 my $cfg = $domain_cfg->{ids}->{$realm};
1075c589 339 die "auth domain '$realm' does not exist\n" if !$cfg;
5bb4e06a
DM
340 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
341 $plugin->store_password($cfg, $realm, $username, $password);
2c3a6c0a
DM
342}
343
344sub add_user_group {
2c3a6c0a 345 my ($username, $usercfg, $group) = @_;
66931b11 346
2c3a6c0a
DM
347 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
348 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
349}
350
351sub delete_user_group {
2c3a6c0a 352 my ($username, $usercfg) = @_;
66931b11 353
2c3a6c0a
DM
354 foreach my $group (keys %{$usercfg->{groups}}) {
355
66931b11 356 delete ($usercfg->{groups}->{$group}->{users}->{$username})
2c3a6c0a
DM
357 if $usercfg->{groups}->{$group}->{users}->{$username};
358 }
359}
360
361sub delete_user_acl {
2c3a6c0a
DM
362 my ($username, $usercfg) = @_;
363
364 foreach my $acl (keys %{$usercfg->{acl}}) {
365
66931b11 366 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
2c3a6c0a
DM
367 if $usercfg->{acl}->{$acl}->{users}->{$username};
368 }
2c3a6c0a 369}
39c85db8 370
2c3a6c0a 371sub delete_group_acl {
2c3a6c0a
DM
372 my ($group, $usercfg) = @_;
373
374 foreach my $acl (keys %{$usercfg->{acl}}) {
375
66931b11 376 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
2c3a6c0a
DM
377 if $usercfg->{acl}->{$acl}->{groups}->{$group};
378 }
39c85db8
DM
379}
380
381sub delete_pool_acl {
39c85db8 382 my ($pool, $usercfg) = @_;
2c3a6c0a 383
39c85db8
DM
384 my $path = "/pool/$pool";
385
3b4a3f94 386 delete ($usercfg->{acl}->{$path})
2c3a6c0a
DM
387}
388
389# we automatically create some predefined roles by splitting privs
390# into 3 groups (per category)
391# root: only root is allowed to do that
392# admin: an administrator can to that
1075c589 393# user: a normal user/customer can to that
2c3a6c0a
DM
394my $privgroups = {
395 VM => {
396 root => [],
66931b11
DM
397 admin => [
398 'VM.Config.Disk',
399 'VM.Config.CPU',
400 'VM.Config.Memory',
401 'VM.Config.Network',
c0fead8c 402 'VM.Config.HWType',
66931b11
DM
403 'VM.Config.Options', # covers all other things
404 'VM.Allocate',
405 'VM.Clone',
2c3a6c0a 406 'VM.Migrate',
66931b11
DM
407 'VM.Monitor',
408 'VM.Snapshot',
2c3a6c0a
DM
409 ],
410 user => [
cc7bdf33 411 'VM.Config.CDROM', # change CDROM media
66931b11 412 'VM.Console',
68d5a86d 413 'VM.Backup',
2c3a6c0a
DM
414 'VM.PowerMgmt',
415 ],
66931b11 416 audit => [
82b63965 417 'VM.Audit',
2c3a6c0a
DM
418 ],
419 },
420 Sys => {
421 root => [
66931b11 422 'Sys.PowerMgmt',
37d45deb 423 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
424 ],
425 admin => [
2e376c58 426 'Permissions.Modify',
66931b11 427 'Sys.Console',
2c3a6c0a
DM
428 'Sys.Syslog',
429 ],
430 user => [],
431 audit => [
432 'Sys.Audit',
433 ],
434 },
435 Datastore => {
2e376c58 436 root => [],
19f60b5e
DM
437 admin => [
438 'Datastore.Allocate',
373cb383 439 'Datastore.AllocateTemplate',
19f60b5e 440 ],
2c3a6c0a
DM
441 user => [
442 'Datastore.AllocateSpace',
443 ],
444 audit => [
445 'Datastore.Audit',
446 ],
447 },
12683df7 448 User => {
82b63965
DM
449 root => [
450 'Realm.Allocate',
451 ],
12683df7
DM
452 admin => [
453 'User.Modify',
82b63965 454 'Group.Allocate', # edit/change group settings
66931b11 455 'Realm.AllocateUser',
19f60b5e 456 ],
12683df7
DM
457 user => [],
458 audit => [],
459 },
dee1c882
DM
460 Pool => {
461 root => [],
462 admin => [
463 'Pool.Allocate', # create/delete pools
464 ],
465 user => [],
466 audit => [],
467 },
2c3a6c0a
DM
468};
469
470my $valid_privs = {};
471
472my $special_roles = {
1075c589
FG
473 'NoAccess' => {}, # no privileges
474 'Administrator' => $valid_privs, # all privileges
2c3a6c0a
DM
475};
476
477sub create_roles {
478
479 foreach my $cat (keys %$privgroups) {
480 my $cd = $privgroups->{$cat};
66931b11 481 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
2c3a6c0a
DM
482 @{$cd->{user}}, @{$cd->{audit}}) {
483 $valid_privs->{$p} = 1;
484 }
485 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
486
487 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
488 $special_roles->{"PVEAdmin"}->{$p} = 1;
489 }
490 if (scalar(@{$cd->{user}})) {
491 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
492 $special_roles->{"PVE${cat}User"}->{$p} = 1;
493 }
494 }
495 foreach my $p (@{$cd->{audit}}) {
496 $special_roles->{"PVEAuditor"}->{$p} = 1;
497 }
498 }
ff4b2235 499
7b395f99 500 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
501};
502
503create_roles();
504
2c3a6c0a
DM
505sub add_role_privs {
506 my ($role, $usercfg, $privs) = @_;
507
508 return if !$privs;
509
510 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
511
512 foreach my $priv (split_list($privs)) {
513 if (defined ($valid_privs->{$priv})) {
514 $usercfg->{roles}->{$role}->{$priv} = 1;
515 } else {
1075c589 516 die "invalid privilege '$priv'\n";
66931b11
DM
517 }
518 }
2c3a6c0a
DM
519}
520
521sub normalize_path {
522 my $path = shift;
523
4bc17477 524 $path =~ s|/+|/|g;
2c3a6c0a
DM
525
526 $path =~ s|/$||;
527
528 $path = '/' if !$path;
529
4bc17477
DM
530 $path = "/$path" if $path !~ m|^/|;
531
e4f8fc2e 532 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
2c3a6c0a
DM
533
534 return $path;
66931b11 535}
2c3a6c0a 536
2c3a6c0a
DM
537
538PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
539sub verify_groupname {
540 my ($groupname, $noerr) = @_;
541
542 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
543
544 die "group name '$groupname' contains invalid characters\n" if !$noerr;
545
546 return undef;
547 }
66931b11 548
2c3a6c0a
DM
549 return $groupname;
550}
551
552PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
553sub verify_rolename {
554 my ($rolename, $noerr) = @_;
555
556 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
557
558 die "role name '$rolename' contains invalid characters\n" if !$noerr;
559
560 return undef;
561 }
66931b11 562
2c3a6c0a
DM
563 return $rolename;
564}
565
39c85db8
DM
566PVE::JSONSchema::register_format('pve-poolid', \&verify_groupname);
567sub verify_poolname {
568 my ($poolname, $noerr) = @_;
569
570 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
571
572 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
573
574 return undef;
575 }
66931b11 576
39c85db8
DM
577 return $poolname;
578}
579
2c3a6c0a
DM
580PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
581sub verify_privname {
582 my ($priv, $noerr) = @_;
583
584 if (!$valid_privs->{$priv}) {
1075c589 585 die "invalid privilege '$priv'\n" if !$noerr;
2c3a6c0a
DM
586
587 return undef;
588 }
66931b11 589
2c3a6c0a
DM
590 return $priv;
591}
592
593sub userconfig_force_defaults {
594 my ($cfg) = @_;
595
596 foreach my $r (keys %$special_roles) {
597 $cfg->{roles}->{$r} = $special_roles->{$r};
598 }
599
7279f31c
WL
600 # add root user if not exists
601 if (!$cfg->{users}->{'root@pam'}) {
66931b11 602 $cfg->{users}->{'root@pam'}->{enable} = 1;
7279f31c 603 }
2c3a6c0a
DM
604}
605
606sub parse_user_config {
607 my ($filename, $raw) = @_;
608
609 my $cfg = {};
610
611 userconfig_force_defaults($cfg);
612
d6eb6621 613 $raw = '' if !defined($raw);
62af314a 614 while ($raw =~ /^\s*(.+?)\s*$/gm) {
2c3a6c0a 615 my $line = $1;
2c3a6c0a
DM
616 my @data;
617
618 foreach my $d (split (/:/, $line)) {
66931b11 619 $d =~ s/^\s+//;
2c3a6c0a
DM
620 $d =~ s/\s+$//;
621 push @data, $d
622 }
623
624 my $et = shift @data;
625
626 if ($et eq 'user') {
96f8ebd6 627 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
2c3a6c0a 628
5bb4e06a 629 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
630 if (!$realm) {
631 warn "user config - ignore user '$user' - invalid user name\n";
632 next;
633 }
634
635 $enable = $enable ? 1 : 0;
636
637 $expire = 0 if !$expire;
638
639 if ($expire !~ m/^\d+$/) {
640 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
641 next;
642 }
643 $expire = int($expire);
644
645 #if (!verify_groupname ($group, 1)) {
646 # warn "user config - ignore user '$user' - invalid characters in group name\n";
647 # next;
648 #}
649
650 $cfg->{users}->{$user} = {
651 enable => $enable,
652 # group => $group,
653 };
654 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
655 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
656 $cfg->{users}->{$user}->{email} = $email;
657 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
658 $cfg->{users}->{$user}->{expire} = $expire;
1abc2c0a 659 # keys: allowed yubico key ids or oath secrets (base32 encoded)
66931b11 660 $cfg->{users}->{$user}->{keys} = $keys if $keys;
2c3a6c0a
DM
661
662 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
663 #$cfg->{groups}->{$group}->{$user} = 1;
664
665 } elsif ($et eq 'group') {
666 my ($group, $userlist, $comment) = @data;
667
668 if (!verify_groupname($group, 1)) {
669 warn "user config - ignore group '$group' - invalid characters in group name\n";
670 next;
671 }
672
673 # make sure to add the group (even if there are no members)
674 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
675
676 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
677
678 foreach my $user (split_list($userlist)) {
679
5bb4e06a 680 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
2c3a6c0a
DM
681 warn "user config - ignore invalid group member '$user'\n";
682 next;
683 }
684
66931b11 685 if ($cfg->{users}->{$user}) { # user exists
2c3a6c0a
DM
686 $cfg->{users}->{$user}->{groups}->{$group} = 1;
687 $cfg->{groups}->{$group}->{users}->{$user} = 1;
688 } else {
689 warn "user config - ignore invalid group member '$user'\n";
690 }
691 }
692
693 } elsif ($et eq 'role') {
694 my ($role, $privlist) = @data;
66931b11 695
2c3a6c0a
DM
696 if (!verify_rolename($role, 1)) {
697 warn "user config - ignore role '$role' - invalid characters in role name\n";
698 next;
699 }
700
701 # make sure to add the role (even if there are no privileges)
702 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
703
704 foreach my $priv (split_list($privlist)) {
705 if (defined ($valid_privs->{$priv})) {
706 $cfg->{roles}->{$role}->{$priv} = 1;
707 } else {
708 warn "user config - ignore invalid priviledge '$priv'\n";
66931b11 709 }
2c3a6c0a 710 }
66931b11 711
2c3a6c0a
DM
712 } elsif ($et eq 'acl') {
713 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
714
715 if (my $path = normalize_path($pathtxt)) {
716 foreach my $role (split_list($rolelist)) {
66931b11 717
2c3a6c0a
DM
718 if (!verify_rolename($role, 1)) {
719 warn "user config - ignore invalid role name '$role' in acl\n";
720 next;
721 }
722
723 foreach my $ug (split_list($uglist)) {
9b217226 724 if ($ug =~ m/^@(\S+)$/) {
2c3a6c0a 725 my $group = $1;
66931b11 726 if ($cfg->{groups}->{$group}) { # group exists
2c3a6c0a
DM
727 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
728 } else {
729 warn "user config - ignore invalid acl group '$group'\n";
730 }
5bb4e06a 731 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
66931b11 732 if ($cfg->{users}->{$ug}) { # user exists
2c3a6c0a
DM
733 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
734 } else {
735 warn "user config - ignore invalid acl member '$ug'\n";
736 }
737 } else {
738 warn "user config - invalid user/group '$ug' in acl\n";
739 }
740 }
741 }
742 } else {
743 warn "user config - ignore invalid path in acl '$pathtxt'\n";
744 }
4bc17477 745 } elsif ($et eq 'pool') {
39c85db8 746 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 747
39c85db8
DM
748 if (!verify_poolname($pool, 1)) {
749 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
750 next;
751 }
4bc17477 752
39c85db8
DM
753 # make sure to add the pool (even if there are no members)
754 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 755
39c85db8 756 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 757
39c85db8
DM
758 foreach my $vmid (split_list($vmlist)) {
759 if ($vmid !~ m/^\d+$/) {
760 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
761 next;
4bc17477 762 }
39c85db8 763 $vmid = int($vmid);
4bc17477 764
39c85db8
DM
765 if ($cfg->{vms}->{$vmid}) {
766 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
767 next;
4bc17477
DM
768 }
769
39c85db8 770 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
66931b11 771
39c85db8
DM
772 # record vmid ==> pool relation
773 $cfg->{vms}->{$vmid} = $pool;
774 }
775
776 foreach my $storeid (split_list($storelist)) {
777 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
778 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
779 next;
780 }
781 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
4bc17477 782 }
2c3a6c0a
DM
783 } else {
784 warn "user config - ignore config line: $line\n";
785 }
786 }
787
788 userconfig_force_defaults($cfg);
789
790 return $cfg;
791}
792
2c3a6c0a
DM
793sub write_user_config {
794 my ($filename, $cfg) = @_;
795
796 my $data = '';
797
798 foreach my $user (keys %{$cfg->{users}}) {
2c3a6c0a
DM
799 my $d = $cfg->{users}->{$user};
800 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
801 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
802 my $email = $d->{email} || '';
803 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 804 my $expire = int($d->{expire} || 0);
2c3a6c0a 805 my $enable = $d->{enable} ? 1 : 0;
96f8ebd6
DM
806 my $keys = $d->{keys} ? $d->{keys} : '';
807 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
2c3a6c0a
DM
808 }
809
810 $data .= "\n";
811
812 foreach my $group (keys %{$cfg->{groups}}) {
813 my $d = $cfg->{groups}->{$group};
814 my $list = join (',', keys %{$d->{users}});
66931b11 815 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
2c3a6c0a
DM
816 $data .= "group:$group:$list:$comment:\n";
817 }
818
819 $data .= "\n";
820
39c85db8
DM
821 foreach my $pool (keys %{$cfg->{pools}}) {
822 my $d = $cfg->{pools}->{$pool};
4bc17477
DM
823 my $vmlist = join (',', keys %{$d->{vms}});
824 my $storelist = join (',', keys %{$d->{storage}});
66931b11 825 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 826 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
827 }
828
829 $data .= "\n";
830
2c3a6c0a
DM
831 foreach my $role (keys %{$cfg->{roles}}) {
832 next if $special_roles->{$role};
833
834 my $d = $cfg->{roles}->{$role};
835 my $list = join (',', keys %$d);
836 $data .= "role:$role:$list:\n";
837 }
838
839 $data .= "\n";
840
841 foreach my $path (sort keys %{$cfg->{acl}}) {
842 my $d = $cfg->{acl}->{$path};
843
844 my $ra = {};
845
846 foreach my $group (keys %{$d->{groups}}) {
847 my $l0 = '';
848 my $l1 = '';
849 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
850 my $propagate = $d->{groups}->{$group}->{$role};
851 if ($propagate) {
852 $l1 .= ',' if $l1;
853 $l1 .= $role;
854 } else {
855 $l0 .= ',' if $l0;
856 $l0 .= $role;
857 }
858 }
859 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
860 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
861 }
862
863 foreach my $user (keys %{$d->{users}}) {
1075c589 864 # no need to save, because root is always 'Administrator'
66931b11 865 next if $user eq 'root@pam';
2c3a6c0a
DM
866
867 my $l0 = '';
868 my $l1 = '';
869 foreach my $role (sort keys %{$d->{users}->{$user}}) {
870 my $propagate = $d->{users}->{$user}->{$role};
871 if ($propagate) {
872 $l1 .= ',' if $l1;
873 $l1 .= $role;
874 } else {
875 $l0 .= ',' if $l0;
876 $l0 .= $role;
877 }
878 }
879 $ra->{0}->{$l0}->{$user} = 1 if $l0;
880 $ra->{1}->{$l1}->{$user} = 1 if $l1;
881 }
882
883 foreach my $rolelist (sort keys %{$ra->{0}}) {
884 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
885 $data .= "acl:0:$path:$uglist:$rolelist:\n";
886 }
887 foreach my $rolelist (sort keys %{$ra->{1}}) {
888 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
889 $data .= "acl:1:$path:$uglist:$rolelist:\n";
890 }
891 }
892
893 return $data;
894}
895
896sub roles {
897 my ($cfg, $user, $path) = @_;
898
66931b11 899 # NOTE: we do not consider pools here.
4bc17477
DM
900 # You need to use $rpcenv->roles() instead if you want that.
901
2c3a6c0a
DM
902 return 'Administrator' if $user eq 'root@pam'; # root can do anything
903
904 my $perm = {};
905
906 foreach my $p (sort keys %{$cfg->{acl}}) {
907 my $final = ($path eq $p);
908
909 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
910
911 my $acl = $cfg->{acl}->{$p};
912
913 #print "CHECKACL $path $p\n";
914 #print "ACL $path = " . Dumper ($acl);
915
916 if (my $ri = $acl->{users}->{$user}) {
917 my $new;
918 foreach my $role (keys %$ri) {
919 my $propagate = $ri->{$role};
920 if ($final || $propagate) {
921 #print "APPLY ROLE $p $user $role\n";
922 $new = {} if !$new;
923 $new->{$role} = 1;
924 }
925 }
926 if ($new) {
927 $perm = $new; # overwrite previous settings
928 next; # user privs always override group privs
929 }
930 }
931
932 my $new;
933 foreach my $g (keys %{$acl->{groups}}) {
934 next if !$cfg->{groups}->{$g}->{users}->{$user};
935 if (my $ri = $acl->{groups}->{$g}) {
936 foreach my $role (keys %$ri) {
937 my $propagate = $ri->{$role};
938 if ($final || $propagate) {
939 #print "APPLY ROLE $p \@$g $role\n";
940 $new = {} if !$new;
941 $new->{$role} = 1;
942 }
943 }
944 }
945 }
946 if ($new) {
947 $perm = $new; # overwrite previous settings
948 next;
949 }
2c3a6c0a
DM
950 }
951
4bc17477
DM
952 return ('NoAccess') if defined ($perm->{NoAccess});
953 #return () if defined ($perm->{NoAccess});
66931b11 954
2c3a6c0a
DM
955 #print "permission $user $path = " . Dumper ($perm);
956
4bc17477 957 my @ra = keys %$perm;
2c3a6c0a
DM
958
959 #print "roles $user $path = " . join (',', @ra) . "\n";
960
961 return @ra;
962}
66931b11 963
2c3a6c0a
DM
964sub permission {
965 my ($cfg, $user, $path) = @_;
966
5bb4e06a 967 $user = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
968 return {} if !$user;
969
970 my @ra = roles($cfg, $user, $path);
66931b11 971
2c3a6c0a
DM
972 my $privs = {};
973
974 foreach my $role (@ra) {
975 if (my $privset = $cfg->{roles}->{$role}) {
976 foreach my $p (keys %$privset) {
977 $privs->{$p} = 1;
978 }
979 }
980 }
981
982 #print "priviledges $user $path = " . Dumper ($privs);
983
984 return $privs;
985}
986
987sub check_permissions {
988 my ($username, $path, $privlist) = @_;
989
990 $path = normalize_path($path);
991 my $usercfg = cfs_read_file('user.cfg');
992 my $perm = permission($usercfg, $username, $path);
993
994 foreach my $priv (split_list($privlist)) {
995 return undef if !$perm->{$priv};
996 };
997
998 return 1;
999}
1000
3b4a3f94
AG
1001sub remove_vm_access {
1002 my ($vmid) = @_;
1003 my $delVMaccessFn = sub {
1004 my $usercfg = cfs_read_file("user.cfg");
57a70473 1005 my $modified;
3b4a3f94 1006
57a70473
DM
1007 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1008 delete $usercfg->{acl}->{"/vms/$vmid"};
1009 $modified = 1;
3b4a3f94
AG
1010 }
1011 if (my $pool = $usercfg->{vms}->{$vmid}) {
1012 if (my $data = $usercfg->{pools}->{$pool}) {
1013 delete $data->{vms}->{$vmid};
1014 delete $usercfg->{vms}->{$vmid};
57a70473 1015 $modified = 1;
3b4a3f94
AG
1016 }
1017 }
57a70473 1018 cfs_write_file("user.cfg", $usercfg) if $modified;
3b4a3f94
AG
1019 };
1020
1021 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1022}
1023
60844761
AG
1024sub remove_storage_access {
1025 my ($storeid) = @_;
1026
1027 my $deleteStorageAccessFn = sub {
1028 my $usercfg = cfs_read_file("user.cfg");
1029 my $modified;
1030
1031 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1032 delete $usercfg->{acl}->{"/storage/$storeid"};
1033 $modified = 1;
1034 }
1035 foreach my $pool (keys %{$usercfg->{pools}}) {
1036 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1037 $modified = 1;
1038 }
1039 cfs_write_file("user.cfg", $usercfg) if $modified;
1040 };
1041
1042 lock_user_config($deleteStorageAccessFn,
1043 "access permissions cleanup for storage $storeid failed");
1044}
1045
018ae3a9
DM
1046sub add_vm_to_pool {
1047 my ($vmid, $pool) = @_;
1048
1049 my $addVMtoPoolFn = sub {
1050 my $usercfg = cfs_read_file("user.cfg");
1051 if (my $data = $usercfg->{pools}->{$pool}) {
1052 $data->{vms}->{$vmid} = 1;
1053 $usercfg->{vms}->{$vmid} = $pool;
1054 cfs_write_file("user.cfg", $usercfg);
1055 }
1056 };
1057
1058 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1059}
1060
1061sub remove_vm_from_pool {
1062 my ($vmid) = @_;
66931b11 1063
018ae3a9
DM
1064 my $delVMfromPoolFn = sub {
1065 my $usercfg = cfs_read_file("user.cfg");
1066 if (my $pool = $usercfg->{vms}->{$vmid}) {
1067 if (my $data = $usercfg->{pools}->{$pool}) {
1068 delete $data->{vms}->{$vmid};
1069 delete $usercfg->{vms}->{$vmid};
1070 cfs_write_file("user.cfg", $usercfg);
1071 }
1072 }
1073 };
1074
1075 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1076}
1077
3e5bfdf6
DM
1078# bash completion helpers
1079
1080sub complete_username {
1081
1082 my $user_cfg = cfs_read_file('user.cfg');
1083
1084 return [ keys %{$user_cfg->{users}} ];
1085}
1086
1087sub complete_group {
1088
1089 my $user_cfg = cfs_read_file('user.cfg');
1090
1091 return [ keys %{$user_cfg->{groups}} ];
1092}
1093
1094sub complete_realm {
1095
1096 my $domain_cfg = cfs_read_file('domains.cfg');
1097
1098 return [ keys %{$domain_cfg->{ids}} ];
1099}
1100
2c3a6c0a 11011;