white space cleanup
[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;
ab652a80
DM
12use Digest::HMAC_SHA1;
13use URI::Escape;
14use LWP::UserAgent;
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
92 my $timestamp = sprintf("%08X", time());
93
94 my $digest = Digest::SHA::sha1_base64("$timestamp:$username", &$get_csrfr_secret());
95
66931b11 96 return "$timestamp:$digest";
2c3a6c0a
DM
97}
98
99sub verify_csrf_prevention_token {
100 my ($username, $token, $noerr) = @_;
101
102 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
103 my $sig = $2;
104 my $timestamp = $1;
105 my $ttime = hex($timestamp);
106
107 my $digest = Digest::SHA::sha1_base64("$timestamp:$username", &$get_csrfr_secret());
108
109 my $age = time() - $ttime;
110 return if ($digest eq $sig) && ($age > -300) && ($age < $ticket_lifetime);
111 }
112
113 die "Permission denied - invalid csrf token\n" if !$noerr;
114
115 return undef;
116}
117
118my $pve_auth_priv_key;
119sub get_privkey {
120
121 return $pve_auth_priv_key if $pve_auth_priv_key;
122
66931b11 123 my $input = PVE::Tools::file_get_contents($authprivkeyfn);
2c3a6c0a
DM
124
125 $pve_auth_priv_key = Crypt::OpenSSL::RSA->new_private_key($input);
126
127 return $pve_auth_priv_key;
128}
129
130sub assemble_ticket {
131 my ($username) = @_;
132
133 my $rsa_priv = get_privkey();
134
135 my $timestamp = sprintf("%08X", time());
136
137 my $plain = "PVE:$username:$timestamp";
138
139 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($plain), '');
140
141 return $ticket;
142}
143
144sub verify_ticket {
145 my ($ticket, $noerr) = @_;
146
adf8d771 147 if ($ticket && $ticket =~ m/^(PVE:\S+)::([^:\s]+)$/) {
2c3a6c0a
DM
148 my $plain = $1;
149 my $sig = $2;
150
151 my $rsa_pub = get_pubkey();
152 if ($rsa_pub->verify($plain, decode_base64($sig))) {
533219a1 153 if ($plain =~ m/^PVE:(\S+):([A-Z0-9]{8})$/) {
2c3a6c0a 154 my $username = $1;
533219a1 155 my $timestamp = $2;
2c3a6c0a
DM
156 my $ttime = hex($timestamp);
157
158 my $age = time() - $ttime;
159
5bb4e06a 160 if (PVE::Auth::Plugin::verify_username($username, 1) &&
533219a1 161 ($age > -300) && ($age < $ticket_lifetime)) {
2c3a6c0a
DM
162 return wantarray ? ($username, $age) : $username;
163 }
164 }
165 }
166 }
167
168 die "permission denied - invalid ticket\n" if !$noerr;
169
170 return undef;
171}
172
adf8d771
DM
173# VNC tickets
174# - they do not contain the username in plain text
175# - they are restricted to a specific resource path (example: '/vms/100')
176sub assemble_vnc_ticket {
177 my ($username, $path) = @_;
178
179 my $rsa_priv = get_privkey();
180
181 my $timestamp = sprintf("%08X", time());
182
183 my $plain = "PVEVNC:$timestamp";
184
185 $path = normalize_path($path);
186
187 my $full = "$plain:$username:$path";
188
189 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($full), '');
190
191 return $ticket;
192}
193
194sub verify_vnc_ticket {
195 my ($ticket, $username, $path, $noerr) = @_;
196
197 if ($ticket && $ticket =~ m/^(PVEVNC:\S+)::([^:\s]+)$/) {
198 my $plain = $1;
199 my $sig = $2;
200 my $full = "$plain:$username:$path";
201
202 my $rsa_pub = get_pubkey();
203 # Note: sign only match if $username and $path is correct
204 if ($rsa_pub->verify($full, decode_base64($sig))) {
205 if ($plain =~ m/^PVEVNC:([A-Z0-9]{8})$/) {
206 my $ttime = hex($1);
207
208 my $age = time() - $ttime;
209
210 if (($age > -20) && ($age < 40)) {
211 return 1;
212 }
213 }
214 }
215 }
216
217 die "permission denied - invalid vnc ticket\n" if !$noerr;
218
219 return undef;
220}
221
23b35225 222sub assemble_spice_ticket {
bf3e6d31 223 my ($username, $vmid, $node) = @_;
23b35225
AD
224
225 my $rsa_priv = get_privkey();
226
bf3e6d31 227 my $timestamp = sprintf("%08x", time());
23b35225 228
bf3e6d31 229 my $randomstr = "PVESPICE:$timestamp:$vmid:$node:" . rand(10);
23b35225 230
bf3e6d31
DM
231 # this should be uses as one-time password
232 # max length is 60 chars (spice limit)
233 # we pass this to qemu set_pasword and limit lifetime there
234 # keep this secret
235 my $ticket = Digest::SHA::sha1_hex($rsa_priv->sign($randomstr));
23b35225 236
bf3e6d31
DM
237 # Note: spice proxy connects with HTTP, so $proxyticket is exposed to public
238 # we use a signature/timestamp to make sure nobody can fake such ticket
239 # an attacker can use this $proxyticket, but he will fail because $ticket is
240 # private.
241 # The proxy need to be able to extract/verify the ticket
242 # Note: data needs to be lower case only, because virt-viewer needs that
3f62bdbe
DM
243 # Note: RSA signature are too long (>=256 charaters) and makes problems with remote-viewer
244
245 my $secret = &$get_csrfr_secret();
cb442f35 246 my $plain = "pvespiceproxy:$timestamp:$vmid:" . lc($node);
3f62bdbe
DM
247
248 # produces 40 characters
249 my $sig = unpack("H*", Digest::SHA::sha1($plain, &$get_csrfr_secret()));
250
251 #my $sig = unpack("H*", $rsa_priv->sign($plain)); # this produce too long strings (512)
23b35225 252
bf3e6d31 253 my $proxyticket = $plain . "::" . $sig;
83d1f13e 254
bf3e6d31
DM
255 return ($ticket, $proxyticket);
256}
257
258sub verify_spice_connect_url {
259 my ($connect_str) = @_;
260
261 # Note: we pass the spice ticket as 'host', so the
262 # spice viewer connects with "$ticket:$port"
263
264 return undef if !$connect_str;
265
3f62bdbe 266 if ($connect_str =~m/^pvespiceproxy:([a-z0-9]{8}):(\d+):(\S+)::([a-z0-9]{40}):(\d+)$/) {
bf3e6d31
DM
267 my ($timestamp, $vmid, $node, $hexsig, $port) = ($1, $2, $3, $4, $5, $6);
268 my $ttime = hex($timestamp);
269 my $age = time() - $ttime;
270
271 # use very limited lifetime - is this enough?
272 return undef if !(($age > -20) && ($age < 40));
273
bf3e6d31 274 my $plain = "pvespiceproxy:$timestamp:$vmid:$node";
3f62bdbe 275 my $sig = unpack("H*", Digest::SHA::sha1($plain, &$get_csrfr_secret()));
bf3e6d31 276
3f62bdbe 277 if ($sig eq $hexsig) {
bf3e6d31 278 return ($vmid, $node, $port);
66931b11 279 }
bf3e6d31
DM
280 }
281
282 return undef;
23b35225
AD
283}
284
cee5583b
DM
285sub read_x509_subject_spice {
286 my ($filename) = @_;
287
288 # read x509 subject
289 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
290 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
291 Net::SSLeay::BIO_free($bio);
292 my $nameobj = Net::SSLeay::X509_get_subject_name($x509);
293 my $subject = Net::SSLeay::X509_NAME_oneline($nameobj);
294 Net::SSLeay::X509_free($x509);
66931b11 295
cee5583b
DM
296 # remote-viewer wants comma as seperator (not '/')
297 $subject =~ s!^/!!;
298 $subject =~ s!/(\w+=)!,$1!g;
299
300 return $subject;
301}
302
303# helper to generate SPICE remote-viewer configuration
304sub remote_viewer_config {
305 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
306
307 if (!$proxy) {
308 my $host = `hostname -f` || PVE::INotify::nodename();
309 chomp $host;
310 $proxy = $host;
311 }
312
313 my ($ticket, $proxyticket) = assemble_spice_ticket($authuser, $vmid, $node);
314
315 my $filename = "/etc/pve/local/pve-ssl.pem";
316 my $subject = read_x509_subject_spice($filename);
317
318 my $cacert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192);
319 $cacert =~ s/\n/\\n/g;
63691fc6 320
25167526 321 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
cee5583b 322 my $config = {
63691fc6
DM
323 'secure-attention' => "Ctrl+Alt+Ins",
324 'toggle-fullscreen' => "Shift+F11",
325 'release-cursor' => "Ctrl+Alt+R",
cee5583b
DM
326 type => 'spice',
327 title => $title,
328 host => $proxyticket, # this break tls hostname verification, so we need to use 'host-subject'
329 proxy => "http://$proxy:3128",
330 'tls-port' => $port,
331 'host-subject' => $subject,
332 ca => $cacert,
333 password => $ticket,
334 'delete-this-file' => 1,
335 };
336
337 return ($ticket, $proxyticket, $config);
338}
339
37d45deb 340sub check_user_exist {
7070c1ae 341 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 342
5bb4e06a 343 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 344 return undef if !$username;
66931b11 345
37d45deb
DM
346 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
347
348 die "no such user ('$username')\n" if !$noerr;
66931b11 349
37d45deb
DM
350 return undef;
351}
352
353sub check_user_enabled {
354 my ($usercfg, $username, $noerr) = @_;
355
356 my $data = check_user_exist($usercfg, $username, $noerr);
357 return undef if !$data;
358
359 return 1 if $data->{enable};
2c3a6c0a 360
37d45deb 361 die "user '$username' is disabled\n" if !$noerr;
66931b11 362
7070c1ae 363 return undef;
2c3a6c0a
DM
364}
365
96f8ebd6
DM
366sub verify_one_time_pw {
367 my ($usercfg, $username, $tfa_cfg, $otp) = @_;
368
369 my $type = $tfa_cfg->{type};
370
371 die "missing one time password for Factor-two authentication '$type'\n" if !$otp;
372
373 # fixme: proxy support?
374 my $proxy;
375
376 if ($type eq 'yubico') {
377 my $keys = $usercfg->{users}->{$username}->{keys};
378 yubico_verify_otp($otp, $keys, $tfa_cfg->{url}, $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
1abc2c0a
DM
379 } elsif ($type eq 'oath') {
380 my $keys = $usercfg->{users}->{$username}->{keys};
86cd805b 381 oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
96f8ebd6
DM
382 } else {
383 die "unknown tfa type '$type'\n";
384 }
96f8ebd6
DM
385}
386
2c3a6c0a 387# password should be utf8 encoded
6126ab75 388# Note: some pluging delay/sleep if auth fails
2c3a6c0a 389sub authenticate_user {
96f8ebd6 390 my ($username, $password, $otp) = @_;
2c3a6c0a
DM
391
392 die "no username specified\n" if !$username;
66931b11 393
5bb4e06a 394 my ($ruid, $realm);
2c3a6c0a 395
5bb4e06a 396 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
2c3a6c0a
DM
397
398 my $usercfg = cfs_read_file('user.cfg');
399
6126ab75 400 check_user_enabled($usercfg, $username);
2c3a6c0a
DM
401
402 my $ctime = time();
403 my $expire = $usercfg->{users}->{$username}->{expire};
404
6126ab75 405 die "account expired\n" if $expire && ($expire < $ctime);
2c3a6c0a 406
5bb4e06a 407 my $domain_cfg = cfs_read_file('domains.cfg');
2c3a6c0a 408
6126ab75
DM
409 my $cfg = $domain_cfg->{ids}->{$realm};
410 die "auth domain '$realm' does not exists\n" if !$cfg;
411 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
412 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
2c3a6c0a 413
96f8ebd6
DM
414 if ($cfg->{tfa}) {
415 my $tfa_cfg = PVE::Auth::Plugin::parse_tfa_config($cfg->{tfa});
416 verify_one_time_pw($usercfg, $username, $tfa_cfg, $otp);
417 }
418
5bb4e06a 419 return $username;
2c3a6c0a
DM
420}
421
422sub domain_set_password {
5bb4e06a 423 my ($realm, $username, $password) = @_;
2c3a6c0a
DM
424
425 die "no auth domain specified" if !$realm;
426
5bb4e06a
DM
427 my $domain_cfg = cfs_read_file('domains.cfg');
428
429 my $cfg = $domain_cfg->{ids}->{$realm};
430 die "auth domain '$realm' does not exists\n" if !$cfg;
431 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
432 $plugin->store_password($cfg, $realm, $username, $password);
2c3a6c0a
DM
433}
434
435sub add_user_group {
2c3a6c0a 436 my ($username, $usercfg, $group) = @_;
66931b11 437
2c3a6c0a
DM
438 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
439 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
440}
441
442sub delete_user_group {
2c3a6c0a 443 my ($username, $usercfg) = @_;
66931b11 444
2c3a6c0a
DM
445 foreach my $group (keys %{$usercfg->{groups}}) {
446
66931b11 447 delete ($usercfg->{groups}->{$group}->{users}->{$username})
2c3a6c0a
DM
448 if $usercfg->{groups}->{$group}->{users}->{$username};
449 }
450}
451
452sub delete_user_acl {
2c3a6c0a
DM
453 my ($username, $usercfg) = @_;
454
455 foreach my $acl (keys %{$usercfg->{acl}}) {
456
66931b11 457 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
2c3a6c0a
DM
458 if $usercfg->{acl}->{$acl}->{users}->{$username};
459 }
2c3a6c0a 460}
39c85db8 461
2c3a6c0a 462sub delete_group_acl {
2c3a6c0a
DM
463 my ($group, $usercfg) = @_;
464
465 foreach my $acl (keys %{$usercfg->{acl}}) {
466
66931b11 467 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
2c3a6c0a
DM
468 if $usercfg->{acl}->{$acl}->{groups}->{$group};
469 }
39c85db8
DM
470}
471
472sub delete_pool_acl {
39c85db8 473 my ($pool, $usercfg) = @_;
2c3a6c0a 474
39c85db8
DM
475 my $path = "/pool/$pool";
476
3b4a3f94 477 delete ($usercfg->{acl}->{$path})
2c3a6c0a
DM
478}
479
480# we automatically create some predefined roles by splitting privs
481# into 3 groups (per category)
482# root: only root is allowed to do that
483# admin: an administrator can to that
484# user: a normak user/customer can to that
485my $privgroups = {
486 VM => {
487 root => [],
66931b11
DM
488 admin => [
489 'VM.Config.Disk',
490 'VM.Config.CPU',
491 'VM.Config.Memory',
492 'VM.Config.Network',
c0fead8c 493 'VM.Config.HWType',
66931b11
DM
494 'VM.Config.Options', # covers all other things
495 'VM.Allocate',
496 'VM.Clone',
2c3a6c0a 497 'VM.Migrate',
66931b11
DM
498 'VM.Monitor',
499 'VM.Snapshot',
2c3a6c0a
DM
500 ],
501 user => [
cc7bdf33 502 'VM.Config.CDROM', # change CDROM media
66931b11 503 'VM.Console',
68d5a86d 504 'VM.Backup',
2c3a6c0a
DM
505 'VM.PowerMgmt',
506 ],
66931b11 507 audit => [
82b63965 508 'VM.Audit',
2c3a6c0a
DM
509 ],
510 },
511 Sys => {
512 root => [
66931b11 513 'Sys.PowerMgmt',
37d45deb 514 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
515 ],
516 admin => [
2e376c58 517 'Permissions.Modify',
66931b11 518 'Sys.Console',
2c3a6c0a
DM
519 'Sys.Syslog',
520 ],
521 user => [],
522 audit => [
523 'Sys.Audit',
524 ],
525 },
526 Datastore => {
2e376c58 527 root => [],
19f60b5e
DM
528 admin => [
529 'Datastore.Allocate',
373cb383 530 'Datastore.AllocateTemplate',
19f60b5e 531 ],
2c3a6c0a
DM
532 user => [
533 'Datastore.AllocateSpace',
534 ],
535 audit => [
536 'Datastore.Audit',
537 ],
538 },
12683df7 539 User => {
82b63965
DM
540 root => [
541 'Realm.Allocate',
542 ],
12683df7
DM
543 admin => [
544 'User.Modify',
82b63965 545 'Group.Allocate', # edit/change group settings
66931b11 546 'Realm.AllocateUser',
19f60b5e 547 ],
12683df7
DM
548 user => [],
549 audit => [],
550 },
dee1c882
DM
551 Pool => {
552 root => [],
553 admin => [
554 'Pool.Allocate', # create/delete pools
555 ],
556 user => [],
557 audit => [],
558 },
2c3a6c0a
DM
559};
560
561my $valid_privs = {};
562
563my $special_roles = {
564 'NoAccess' => {}, # no priviledges
565 'Administrator' => $valid_privs, # all priviledges
566};
567
568sub create_roles {
569
570 foreach my $cat (keys %$privgroups) {
571 my $cd = $privgroups->{$cat};
66931b11 572 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
2c3a6c0a
DM
573 @{$cd->{user}}, @{$cd->{audit}}) {
574 $valid_privs->{$p} = 1;
575 }
576 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
577
578 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
579 $special_roles->{"PVEAdmin"}->{$p} = 1;
580 }
581 if (scalar(@{$cd->{user}})) {
582 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
583 $special_roles->{"PVE${cat}User"}->{$p} = 1;
584 }
585 }
586 foreach my $p (@{$cd->{audit}}) {
587 $special_roles->{"PVEAuditor"}->{$p} = 1;
588 }
589 }
ff4b2235 590
7b395f99 591 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
592};
593
594create_roles();
595
2c3a6c0a
DM
596sub add_role_privs {
597 my ($role, $usercfg, $privs) = @_;
598
599 return if !$privs;
600
601 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
602
603 foreach my $priv (split_list($privs)) {
604 if (defined ($valid_privs->{$priv})) {
605 $usercfg->{roles}->{$role}->{$priv} = 1;
606 } else {
607 die "invalid priviledge '$priv'\n";
66931b11
DM
608 }
609 }
2c3a6c0a
DM
610}
611
612sub normalize_path {
613 my $path = shift;
614
4bc17477 615 $path =~ s|/+|/|g;
2c3a6c0a
DM
616
617 $path =~ s|/$||;
618
619 $path = '/' if !$path;
620
4bc17477
DM
621 $path = "/$path" if $path !~ m|^/|;
622
e4f8fc2e 623 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
2c3a6c0a
DM
624
625 return $path;
66931b11 626}
2c3a6c0a 627
2c3a6c0a
DM
628
629PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
630sub verify_groupname {
631 my ($groupname, $noerr) = @_;
632
633 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
634
635 die "group name '$groupname' contains invalid characters\n" if !$noerr;
636
637 return undef;
638 }
66931b11 639
2c3a6c0a
DM
640 return $groupname;
641}
642
643PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
644sub verify_rolename {
645 my ($rolename, $noerr) = @_;
646
647 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
648
649 die "role name '$rolename' contains invalid characters\n" if !$noerr;
650
651 return undef;
652 }
66931b11 653
2c3a6c0a
DM
654 return $rolename;
655}
656
39c85db8
DM
657PVE::JSONSchema::register_format('pve-poolid', \&verify_groupname);
658sub verify_poolname {
659 my ($poolname, $noerr) = @_;
660
661 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
662
663 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
664
665 return undef;
666 }
66931b11 667
39c85db8
DM
668 return $poolname;
669}
670
2c3a6c0a
DM
671PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
672sub verify_privname {
673 my ($priv, $noerr) = @_;
674
675 if (!$valid_privs->{$priv}) {
676 die "invalid priviledge '$priv'\n" if !$noerr;
677
678 return undef;
679 }
66931b11 680
2c3a6c0a
DM
681 return $priv;
682}
683
684sub userconfig_force_defaults {
685 my ($cfg) = @_;
686
687 foreach my $r (keys %$special_roles) {
688 $cfg->{roles}->{$r} = $special_roles->{$r};
689 }
690
7279f31c
WL
691 # add root user if not exists
692 if (!$cfg->{users}->{'root@pam'}) {
66931b11 693 $cfg->{users}->{'root@pam'}->{enable} = 1;
7279f31c 694 }
2c3a6c0a
DM
695}
696
697sub parse_user_config {
698 my ($filename, $raw) = @_;
699
700 my $cfg = {};
701
702 userconfig_force_defaults($cfg);
703
d6eb6621 704 $raw = '' if !defined($raw);
62af314a 705 while ($raw =~ /^\s*(.+?)\s*$/gm) {
2c3a6c0a 706 my $line = $1;
2c3a6c0a
DM
707 my @data;
708
709 foreach my $d (split (/:/, $line)) {
66931b11 710 $d =~ s/^\s+//;
2c3a6c0a
DM
711 $d =~ s/\s+$//;
712 push @data, $d
713 }
714
715 my $et = shift @data;
716
717 if ($et eq 'user') {
96f8ebd6 718 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
2c3a6c0a 719
5bb4e06a 720 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
721 if (!$realm) {
722 warn "user config - ignore user '$user' - invalid user name\n";
723 next;
724 }
725
726 $enable = $enable ? 1 : 0;
727
728 $expire = 0 if !$expire;
729
730 if ($expire !~ m/^\d+$/) {
731 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
732 next;
733 }
734 $expire = int($expire);
735
736 #if (!verify_groupname ($group, 1)) {
737 # warn "user config - ignore user '$user' - invalid characters in group name\n";
738 # next;
739 #}
740
741 $cfg->{users}->{$user} = {
742 enable => $enable,
743 # group => $group,
744 };
745 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
746 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
747 $cfg->{users}->{$user}->{email} = $email;
748 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
749 $cfg->{users}->{$user}->{expire} = $expire;
1abc2c0a 750 # keys: allowed yubico key ids or oath secrets (base32 encoded)
66931b11 751 $cfg->{users}->{$user}->{keys} = $keys if $keys;
2c3a6c0a
DM
752
753 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
754 #$cfg->{groups}->{$group}->{$user} = 1;
755
756 } elsif ($et eq 'group') {
757 my ($group, $userlist, $comment) = @data;
758
759 if (!verify_groupname($group, 1)) {
760 warn "user config - ignore group '$group' - invalid characters in group name\n";
761 next;
762 }
763
764 # make sure to add the group (even if there are no members)
765 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
766
767 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
768
769 foreach my $user (split_list($userlist)) {
770
5bb4e06a 771 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
2c3a6c0a
DM
772 warn "user config - ignore invalid group member '$user'\n";
773 next;
774 }
775
66931b11 776 if ($cfg->{users}->{$user}) { # user exists
2c3a6c0a
DM
777 $cfg->{users}->{$user}->{groups}->{$group} = 1;
778 $cfg->{groups}->{$group}->{users}->{$user} = 1;
779 } else {
780 warn "user config - ignore invalid group member '$user'\n";
781 }
782 }
783
784 } elsif ($et eq 'role') {
785 my ($role, $privlist) = @data;
66931b11 786
2c3a6c0a
DM
787 if (!verify_rolename($role, 1)) {
788 warn "user config - ignore role '$role' - invalid characters in role name\n";
789 next;
790 }
791
792 # make sure to add the role (even if there are no privileges)
793 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
794
795 foreach my $priv (split_list($privlist)) {
796 if (defined ($valid_privs->{$priv})) {
797 $cfg->{roles}->{$role}->{$priv} = 1;
798 } else {
799 warn "user config - ignore invalid priviledge '$priv'\n";
66931b11 800 }
2c3a6c0a 801 }
66931b11 802
2c3a6c0a
DM
803 } elsif ($et eq 'acl') {
804 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
805
806 if (my $path = normalize_path($pathtxt)) {
807 foreach my $role (split_list($rolelist)) {
66931b11 808
2c3a6c0a
DM
809 if (!verify_rolename($role, 1)) {
810 warn "user config - ignore invalid role name '$role' in acl\n";
811 next;
812 }
813
814 foreach my $ug (split_list($uglist)) {
9b217226 815 if ($ug =~ m/^@(\S+)$/) {
2c3a6c0a 816 my $group = $1;
66931b11 817 if ($cfg->{groups}->{$group}) { # group exists
2c3a6c0a
DM
818 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
819 } else {
820 warn "user config - ignore invalid acl group '$group'\n";
821 }
5bb4e06a 822 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
66931b11 823 if ($cfg->{users}->{$ug}) { # user exists
2c3a6c0a
DM
824 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
825 } else {
826 warn "user config - ignore invalid acl member '$ug'\n";
827 }
828 } else {
829 warn "user config - invalid user/group '$ug' in acl\n";
830 }
831 }
832 }
833 } else {
834 warn "user config - ignore invalid path in acl '$pathtxt'\n";
835 }
4bc17477 836 } elsif ($et eq 'pool') {
39c85db8 837 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 838
39c85db8
DM
839 if (!verify_poolname($pool, 1)) {
840 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
841 next;
842 }
4bc17477 843
39c85db8
DM
844 # make sure to add the pool (even if there are no members)
845 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 846
39c85db8 847 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 848
39c85db8
DM
849 foreach my $vmid (split_list($vmlist)) {
850 if ($vmid !~ m/^\d+$/) {
851 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
852 next;
4bc17477 853 }
39c85db8 854 $vmid = int($vmid);
4bc17477 855
39c85db8
DM
856 if ($cfg->{vms}->{$vmid}) {
857 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
858 next;
4bc17477
DM
859 }
860
39c85db8 861 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
66931b11 862
39c85db8
DM
863 # record vmid ==> pool relation
864 $cfg->{vms}->{$vmid} = $pool;
865 }
866
867 foreach my $storeid (split_list($storelist)) {
868 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
869 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
870 next;
871 }
872 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
4bc17477 873 }
2c3a6c0a
DM
874 } else {
875 warn "user config - ignore config line: $line\n";
876 }
877 }
878
879 userconfig_force_defaults($cfg);
880
881 return $cfg;
882}
883
2c3a6c0a
DM
884sub write_user_config {
885 my ($filename, $cfg) = @_;
886
887 my $data = '';
888
889 foreach my $user (keys %{$cfg->{users}}) {
2c3a6c0a
DM
890 my $d = $cfg->{users}->{$user};
891 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
892 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
893 my $email = $d->{email} || '';
894 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 895 my $expire = int($d->{expire} || 0);
2c3a6c0a 896 my $enable = $d->{enable} ? 1 : 0;
96f8ebd6
DM
897 my $keys = $d->{keys} ? $d->{keys} : '';
898 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
2c3a6c0a
DM
899 }
900
901 $data .= "\n";
902
903 foreach my $group (keys %{$cfg->{groups}}) {
904 my $d = $cfg->{groups}->{$group};
905 my $list = join (',', keys %{$d->{users}});
66931b11 906 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
2c3a6c0a
DM
907 $data .= "group:$group:$list:$comment:\n";
908 }
909
910 $data .= "\n";
911
39c85db8
DM
912 foreach my $pool (keys %{$cfg->{pools}}) {
913 my $d = $cfg->{pools}->{$pool};
4bc17477
DM
914 my $vmlist = join (',', keys %{$d->{vms}});
915 my $storelist = join (',', keys %{$d->{storage}});
66931b11 916 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 917 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
918 }
919
920 $data .= "\n";
921
2c3a6c0a
DM
922 foreach my $role (keys %{$cfg->{roles}}) {
923 next if $special_roles->{$role};
924
925 my $d = $cfg->{roles}->{$role};
926 my $list = join (',', keys %$d);
927 $data .= "role:$role:$list:\n";
928 }
929
930 $data .= "\n";
931
932 foreach my $path (sort keys %{$cfg->{acl}}) {
933 my $d = $cfg->{acl}->{$path};
934
935 my $ra = {};
936
937 foreach my $group (keys %{$d->{groups}}) {
938 my $l0 = '';
939 my $l1 = '';
940 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
941 my $propagate = $d->{groups}->{$group}->{$role};
942 if ($propagate) {
943 $l1 .= ',' if $l1;
944 $l1 .= $role;
945 } else {
946 $l0 .= ',' if $l0;
947 $l0 .= $role;
948 }
949 }
950 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
951 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
952 }
953
954 foreach my $user (keys %{$d->{users}}) {
955 # no need to save, because root is always 'Administartor'
66931b11 956 next if $user eq 'root@pam';
2c3a6c0a
DM
957
958 my $l0 = '';
959 my $l1 = '';
960 foreach my $role (sort keys %{$d->{users}->{$user}}) {
961 my $propagate = $d->{users}->{$user}->{$role};
962 if ($propagate) {
963 $l1 .= ',' if $l1;
964 $l1 .= $role;
965 } else {
966 $l0 .= ',' if $l0;
967 $l0 .= $role;
968 }
969 }
970 $ra->{0}->{$l0}->{$user} = 1 if $l0;
971 $ra->{1}->{$l1}->{$user} = 1 if $l1;
972 }
973
974 foreach my $rolelist (sort keys %{$ra->{0}}) {
975 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
976 $data .= "acl:0:$path:$uglist:$rolelist:\n";
977 }
978 foreach my $rolelist (sort keys %{$ra->{1}}) {
979 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
980 $data .= "acl:1:$path:$uglist:$rolelist:\n";
981 }
982 }
983
984 return $data;
985}
986
987sub roles {
988 my ($cfg, $user, $path) = @_;
989
66931b11 990 # NOTE: we do not consider pools here.
4bc17477
DM
991 # You need to use $rpcenv->roles() instead if you want that.
992
2c3a6c0a
DM
993 return 'Administrator' if $user eq 'root@pam'; # root can do anything
994
995 my $perm = {};
996
997 foreach my $p (sort keys %{$cfg->{acl}}) {
998 my $final = ($path eq $p);
999
1000 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1001
1002 my $acl = $cfg->{acl}->{$p};
1003
1004 #print "CHECKACL $path $p\n";
1005 #print "ACL $path = " . Dumper ($acl);
1006
1007 if (my $ri = $acl->{users}->{$user}) {
1008 my $new;
1009 foreach my $role (keys %$ri) {
1010 my $propagate = $ri->{$role};
1011 if ($final || $propagate) {
1012 #print "APPLY ROLE $p $user $role\n";
1013 $new = {} if !$new;
1014 $new->{$role} = 1;
1015 }
1016 }
1017 if ($new) {
1018 $perm = $new; # overwrite previous settings
1019 next; # user privs always override group privs
1020 }
1021 }
1022
1023 my $new;
1024 foreach my $g (keys %{$acl->{groups}}) {
1025 next if !$cfg->{groups}->{$g}->{users}->{$user};
1026 if (my $ri = $acl->{groups}->{$g}) {
1027 foreach my $role (keys %$ri) {
1028 my $propagate = $ri->{$role};
1029 if ($final || $propagate) {
1030 #print "APPLY ROLE $p \@$g $role\n";
1031 $new = {} if !$new;
1032 $new->{$role} = 1;
1033 }
1034 }
1035 }
1036 }
1037 if ($new) {
1038 $perm = $new; # overwrite previous settings
1039 next;
1040 }
2c3a6c0a
DM
1041 }
1042
4bc17477
DM
1043 return ('NoAccess') if defined ($perm->{NoAccess});
1044 #return () if defined ($perm->{NoAccess});
66931b11 1045
2c3a6c0a
DM
1046 #print "permission $user $path = " . Dumper ($perm);
1047
4bc17477 1048 my @ra = keys %$perm;
2c3a6c0a
DM
1049
1050 #print "roles $user $path = " . join (',', @ra) . "\n";
1051
1052 return @ra;
1053}
66931b11 1054
2c3a6c0a
DM
1055sub permission {
1056 my ($cfg, $user, $path) = @_;
1057
5bb4e06a 1058 $user = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
1059 return {} if !$user;
1060
1061 my @ra = roles($cfg, $user, $path);
66931b11 1062
2c3a6c0a
DM
1063 my $privs = {};
1064
1065 foreach my $role (@ra) {
1066 if (my $privset = $cfg->{roles}->{$role}) {
1067 foreach my $p (keys %$privset) {
1068 $privs->{$p} = 1;
1069 }
1070 }
1071 }
1072
1073 #print "priviledges $user $path = " . Dumper ($privs);
1074
1075 return $privs;
1076}
1077
1078sub check_permissions {
1079 my ($username, $path, $privlist) = @_;
1080
1081 $path = normalize_path($path);
1082 my $usercfg = cfs_read_file('user.cfg');
1083 my $perm = permission($usercfg, $username, $path);
1084
1085 foreach my $priv (split_list($privlist)) {
1086 return undef if !$perm->{$priv};
1087 };
1088
1089 return 1;
1090}
1091
3b4a3f94
AG
1092sub remove_vm_access {
1093 my ($vmid) = @_;
1094 my $delVMaccessFn = sub {
1095 my $usercfg = cfs_read_file("user.cfg");
1096
1097 if (my $acl = $usercfg->{acl}->{'/vms/'.$vmid}) {
1098 delete $usercfg->{acl}->{'/vms/'.$vmid};
1099 cfs_write_file("user.cfg", $usercfg);
1100 }
1101 if (my $pool = $usercfg->{vms}->{$vmid}) {
1102 if (my $data = $usercfg->{pools}->{$pool}) {
1103 delete $data->{vms}->{$vmid};
1104 delete $usercfg->{vms}->{$vmid};
1105 cfs_write_file("user.cfg", $usercfg);
1106 }
1107 }
1108 };
1109
1110 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1111}
1112
018ae3a9
DM
1113sub add_vm_to_pool {
1114 my ($vmid, $pool) = @_;
1115
1116 my $addVMtoPoolFn = sub {
1117 my $usercfg = cfs_read_file("user.cfg");
1118 if (my $data = $usercfg->{pools}->{$pool}) {
1119 $data->{vms}->{$vmid} = 1;
1120 $usercfg->{vms}->{$vmid} = $pool;
1121 cfs_write_file("user.cfg", $usercfg);
1122 }
1123 };
1124
1125 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1126}
1127
1128sub remove_vm_from_pool {
1129 my ($vmid) = @_;
66931b11 1130
018ae3a9
DM
1131 my $delVMfromPoolFn = sub {
1132 my $usercfg = cfs_read_file("user.cfg");
1133 if (my $pool = $usercfg->{vms}->{$vmid}) {
1134 if (my $data = $usercfg->{pools}->{$pool}) {
1135 delete $data->{vms}->{$vmid};
1136 delete $usercfg->{vms}->{$vmid};
1137 cfs_write_file("user.cfg", $usercfg);
1138 }
1139 }
1140 };
1141
1142 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1143}
1144
ab652a80
DM
1145# experimental code for yubico OTP verification
1146
1147sub yubico_compute_param_sig {
1148 my ($param, $api_key) = @_;
1149
1150 my $paramstr = '';
1151 foreach my $key (sort keys %$param) {
1152 $paramstr .= '&' if $paramstr;
1153 $paramstr .= "$key=$param->{$key}";
1154 }
1155
1156 my $sig = uri_escape(encode_base64(Digest::HMAC_SHA1::hmac_sha1($paramstr, decode_base64($api_key || '')), ''));
1157
1158 return ($paramstr, $sig);
1159}
1160
1161sub yubico_verify_otp {
96f8ebd6
DM
1162 my ($otp, $keys, $url, $api_id, $api_key, $proxy) = @_;
1163
1164 die "yubico: missing password\n" if !defined($otp);
1165 die "yubico: missing API ID\n" if !defined($api_id);
1166 die "yubico: missing API KEY\n" if !defined($api_key);
66931b11 1167 die "yubico: no associated yubico keys\n" if $keys =~ m/^\s+$/;
ab652a80 1168
96f8ebd6 1169 die "yubico: wrong OTP lenght\n" if (length($otp) < 32) || (length($otp) > 48);
ab652a80
DM
1170
1171 # we always use http, because https cert verification always make problem, and
1172 # some proxies does not work with https.
1173
96f8ebd6 1174 $url = 'http://api2.yubico.com/wsapi/2.0/verify' if !defined($url);
66931b11 1175
ab652a80
DM
1176 my $params = {
1177 nonce => Digest::HMAC_SHA1::hmac_sha1_hex(time(), rand()),
1178 id => $api_id,
1179 otp => uri_escape($otp),
1180 timestamp => 1,
1181 };
1182
1183 my ($paramstr, $sig) = yubico_compute_param_sig($params, $api_key);
1184
1185 $paramstr .= "&h=$sig" if $api_key;
1186
1187 my $req = HTTP::Request->new('GET' => "$url?$paramstr");
1188
1189 my $ua = LWP::UserAgent->new(protocols_allowed => ['http'], timeout => 30);
1190
1191 if ($proxy) {
1192 $ua->proxy(['http'], $proxy);
1193 } else {
1194 $ua->env_proxy;
1195 }
1196
1197 my $response = $ua->request($req);
1198 my $code = $response->code;
1199
1200 if ($code != 200) {
1201 my $msg = $response->message || 'unknown';
1202 die "Invalid response from server: $code $msg\n";
1203 }
1204
1205 my $raw = $response->decoded_content;
1206
1207 my $result = {};
1208 foreach my $kvpair (split(/\n/, $raw)) {
1209 chomp $kvpair;
1210 if($kvpair =~ /^\S+=/) {
1211 my ($k, $v) = split(/=/, $kvpair, 2);
1212 $v =~ s/\s//g;
1213 $result->{$k} = $v;
1214 }
1215 }
1216
1217 my $rsig = $result->{h};
1218 delete $result->{h};
1219
1220 if ($api_key) {
1221 my ($datastr, $vsig) = yubico_compute_param_sig($result, $api_key);
1222 $vsig = uri_unescape($vsig);
96f8ebd6 1223 die "yubico: result signature verification failed\n" if $rsig ne $vsig;
ab652a80
DM
1224 }
1225
96f8ebd6
DM
1226 die "yubico auth failed: $result->{status}\n" if $result->{status} ne 'OK';
1227
1228 my $publicid = $result->{publicid} = substr(lc($result->{otp}), 0, 12);
1229
1230 my $found;
1231 foreach my $k (PVE::Tools::split_list($keys)) {
1232 if ($k eq $publicid) {
1233 $found = 1;
1234 last;
1235 }
1236 }
ab652a80 1237
96f8ebd6 1238 die "yubico auth failed: key does not belong to user\n" if !$found;
ab652a80
DM
1239
1240 return $result;
1241}
1242
1abc2c0a 1243sub oath_verify_otp {
86cd805b 1244 my ($otp, $keys, $step, $digits) = @_;
1abc2c0a
DM
1245
1246 die "oath: missing password\n" if !defined($otp);
66931b11 1247 die "oath: no associated oath keys\n" if $keys =~ m/^\s+$/;
1abc2c0a 1248
86cd805b
DM
1249 $step = 30 if !$step;
1250 $digits = 6 if !$digits;
1abc2c0a
DM
1251
1252 my $found;
1253
1254 my $parser = sub {
1255 my $line = shift;
1256
1257 if ($line =~ m/^\d{6}$/) {
1abc2c0a
DM
1258 $found = 1 if $otp eq $line;
1259 }
1260 };
1261
1262 foreach my $k (PVE::Tools::split_list($keys)) {
1263 # Note: we generate 3 values to allow small time drift
1264 my $now = localtime(time() - $step);
86cd805b 1265 my $cmd = ['oathtool', '--totp', '--digits', $digits, '-N', $now, '-s', $step, '-w', '2', '-b', $k];
1abc2c0a
DM
1266 eval { run_command($cmd, outfunc => $parser, errfunc => sub {}); };
1267 last if $found;
1268 }
1269
1270 die "oath auth failed\n" if !$found;
1271}
1272
2c3a6c0a 12731;