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