improve parse_user_config, parse_shadow_config
[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
46cfs_register_file('user.cfg',
47 \&parse_user_config,
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;
69sub get_pubkey {
70
71 return $pve_auth_pub_key if $pve_auth_pub_key;
72
73 my $input = PVE::Tools::file_get_contents($authpubkeyfn);
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) {
83 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
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
96 return "$timestamp:$digest";
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
123 my $input = PVE::Tools::file_get_contents($authprivkeyfn);
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
DM
278 return ($vmid, $node, $port);
279 }
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);
295
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
DM
344 return undef if !$username;
345
37d45deb
DM
346 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
347
348 die "no such user ('$username')\n" if !$noerr;
349
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;
7070c1ae
DM
362
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;
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 {
436
437 my ($username, $usercfg, $group) = @_;
438 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
439 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
440}
441
442sub delete_user_group {
443
444 my ($username, $usercfg) = @_;
445
446 foreach my $group (keys %{$usercfg->{groups}}) {
447
448 delete ($usercfg->{groups}->{$group}->{users}->{$username})
449 if $usercfg->{groups}->{$group}->{users}->{$username};
450 }
451}
452
453sub delete_user_acl {
454
455 my ($username, $usercfg) = @_;
456
457 foreach my $acl (keys %{$usercfg->{acl}}) {
458
459 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
460 if $usercfg->{acl}->{$acl}->{users}->{$username};
461 }
2c3a6c0a 462}
39c85db8 463
2c3a6c0a
DM
464sub delete_group_acl {
465
466 my ($group, $usercfg) = @_;
467
468 foreach my $acl (keys %{$usercfg->{acl}}) {
469
470 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
471 if $usercfg->{acl}->{$acl}->{groups}->{$group};
472 }
39c85db8
DM
473}
474
475sub delete_pool_acl {
476
477 my ($pool, $usercfg) = @_;
2c3a6c0a 478
39c85db8
DM
479 my $path = "/pool/$pool";
480
481 foreach my $aclpath (keys %{$usercfg->{acl}}) {
482 delete ($usercfg->{acl}->{$aclpath})
483 if $usercfg->{acl}->{$aclpath} eq 'path';
484 }
2c3a6c0a
DM
485}
486
487# we automatically create some predefined roles by splitting privs
488# into 3 groups (per category)
489# root: only root is allowed to do that
490# admin: an administrator can to that
491# user: a normak user/customer can to that
492my $privgroups = {
493 VM => {
494 root => [],
495 admin => [
c0fead8c 496 'VM.Config.Disk',
c0fead8c
DM
497 'VM.Config.CPU',
498 'VM.Config.Memory',
499 'VM.Config.Network',
500 'VM.Config.HWType',
501 'VM.Config.Options', # covers all other things
2c3a6c0a 502 'VM.Allocate',
7b395f99 503 'VM.Clone',
2c3a6c0a 504 'VM.Migrate',
c0fead8c 505 'VM.Monitor',
e3e6510c 506 'VM.Snapshot',
2c3a6c0a
DM
507 ],
508 user => [
cc7bdf33 509 'VM.Config.CDROM', # change CDROM media
2c3a6c0a 510 'VM.Console',
68d5a86d 511 'VM.Backup',
2c3a6c0a
DM
512 'VM.PowerMgmt',
513 ],
514 audit => [
82b63965 515 'VM.Audit',
2c3a6c0a
DM
516 ],
517 },
518 Sys => {
519 root => [
520 'Sys.PowerMgmt',
37d45deb 521 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
522 ],
523 admin => [
2e376c58 524 'Permissions.Modify',
2c3a6c0a
DM
525 'Sys.Console',
526 'Sys.Syslog',
527 ],
528 user => [],
529 audit => [
530 'Sys.Audit',
531 ],
532 },
533 Datastore => {
2e376c58 534 root => [],
19f60b5e
DM
535 admin => [
536 'Datastore.Allocate',
373cb383 537 'Datastore.AllocateTemplate',
19f60b5e 538 ],
2c3a6c0a
DM
539 user => [
540 'Datastore.AllocateSpace',
541 ],
542 audit => [
543 'Datastore.Audit',
544 ],
545 },
12683df7 546 User => {
82b63965
DM
547 root => [
548 'Realm.Allocate',
549 ],
12683df7
DM
550 admin => [
551 'User.Modify',
82b63965
DM
552 'Group.Allocate', # edit/change group settings
553 'Realm.AllocateUser',
19f60b5e 554 ],
12683df7
DM
555 user => [],
556 audit => [],
557 },
dee1c882
DM
558 Pool => {
559 root => [],
560 admin => [
561 'Pool.Allocate', # create/delete pools
562 ],
563 user => [],
564 audit => [],
565 },
2c3a6c0a
DM
566};
567
568my $valid_privs = {};
569
570my $special_roles = {
571 'NoAccess' => {}, # no priviledges
572 'Administrator' => $valid_privs, # all priviledges
573};
574
575sub create_roles {
576
577 foreach my $cat (keys %$privgroups) {
578 my $cd = $privgroups->{$cat};
579 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
580 @{$cd->{user}}, @{$cd->{audit}}) {
581 $valid_privs->{$p} = 1;
582 }
583 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
584
585 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
586 $special_roles->{"PVEAdmin"}->{$p} = 1;
587 }
588 if (scalar(@{$cd->{user}})) {
589 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
590 $special_roles->{"PVE${cat}User"}->{$p} = 1;
591 }
592 }
593 foreach my $p (@{$cd->{audit}}) {
594 $special_roles->{"PVEAuditor"}->{$p} = 1;
595 }
596 }
ff4b2235 597
7b395f99 598 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
599};
600
601create_roles();
602
2c3a6c0a
DM
603sub add_role_privs {
604 my ($role, $usercfg, $privs) = @_;
605
606 return if !$privs;
607
608 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
609
610 foreach my $priv (split_list($privs)) {
611 if (defined ($valid_privs->{$priv})) {
612 $usercfg->{roles}->{$role}->{$priv} = 1;
613 } else {
614 die "invalid priviledge '$priv'\n";
615 }
616 }
617}
618
619sub normalize_path {
620 my $path = shift;
621
4bc17477 622 $path =~ s|/+|/|g;
2c3a6c0a
DM
623
624 $path =~ s|/$||;
625
626 $path = '/' if !$path;
627
4bc17477
DM
628 $path = "/$path" if $path !~ m|^/|;
629
e4f8fc2e 630 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
2c3a6c0a
DM
631
632 return $path;
633}
634
2c3a6c0a
DM
635
636PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
637sub verify_groupname {
638 my ($groupname, $noerr) = @_;
639
640 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
641
642 die "group name '$groupname' contains invalid characters\n" if !$noerr;
643
644 return undef;
645 }
646
647 return $groupname;
648}
649
650PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
651sub verify_rolename {
652 my ($rolename, $noerr) = @_;
653
654 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
655
656 die "role name '$rolename' contains invalid characters\n" if !$noerr;
657
658 return undef;
659 }
660
661 return $rolename;
662}
663
39c85db8
DM
664PVE::JSONSchema::register_format('pve-poolid', \&verify_groupname);
665sub verify_poolname {
666 my ($poolname, $noerr) = @_;
667
668 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
669
670 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
671
672 return undef;
673 }
674
675 return $poolname;
676}
677
2c3a6c0a
DM
678PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
679sub verify_privname {
680 my ($priv, $noerr) = @_;
681
682 if (!$valid_privs->{$priv}) {
683 die "invalid priviledge '$priv'\n" if !$noerr;
684
685 return undef;
686 }
687
688 return $priv;
689}
690
691sub userconfig_force_defaults {
692 my ($cfg) = @_;
693
694 foreach my $r (keys %$special_roles) {
695 $cfg->{roles}->{$r} = $special_roles->{$r};
696 }
697
7279f31c
WL
698 # add root user if not exists
699 if (!$cfg->{users}->{'root@pam'}) {
700 $cfg->{users}->{'root@pam'}->{enable} = 1;
701 }
2c3a6c0a
DM
702}
703
704sub parse_user_config {
705 my ($filename, $raw) = @_;
706
707 my $cfg = {};
708
709 userconfig_force_defaults($cfg);
710
62af314a 711 while ($raw =~ /^\s*(.+?)\s*$/gm) {
2c3a6c0a 712 my $line = $1;
2c3a6c0a
DM
713 my @data;
714
715 foreach my $d (split (/:/, $line)) {
716 $d =~ s/^\s+//;
717 $d =~ s/\s+$//;
718 push @data, $d
719 }
720
721 my $et = shift @data;
722
723 if ($et eq 'user') {
96f8ebd6 724 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
2c3a6c0a 725
5bb4e06a 726 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
727 if (!$realm) {
728 warn "user config - ignore user '$user' - invalid user name\n";
729 next;
730 }
731
732 $enable = $enable ? 1 : 0;
733
734 $expire = 0 if !$expire;
735
736 if ($expire !~ m/^\d+$/) {
737 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
738 next;
739 }
740 $expire = int($expire);
741
742 #if (!verify_groupname ($group, 1)) {
743 # warn "user config - ignore user '$user' - invalid characters in group name\n";
744 # next;
745 #}
746
747 $cfg->{users}->{$user} = {
748 enable => $enable,
749 # group => $group,
750 };
751 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
752 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
753 $cfg->{users}->{$user}->{email} = $email;
754 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
755 $cfg->{users}->{$user}->{expire} = $expire;
1abc2c0a
DM
756 # keys: allowed yubico key ids or oath secrets (base32 encoded)
757 $cfg->{users}->{$user}->{keys} = $keys if $keys;
2c3a6c0a
DM
758
759 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
760 #$cfg->{groups}->{$group}->{$user} = 1;
761
762 } elsif ($et eq 'group') {
763 my ($group, $userlist, $comment) = @data;
764
765 if (!verify_groupname($group, 1)) {
766 warn "user config - ignore group '$group' - invalid characters in group name\n";
767 next;
768 }
769
770 # make sure to add the group (even if there are no members)
771 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
772
773 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
774
775 foreach my $user (split_list($userlist)) {
776
5bb4e06a 777 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
2c3a6c0a
DM
778 warn "user config - ignore invalid group member '$user'\n";
779 next;
780 }
781
782 if ($cfg->{users}->{$user}) { # user exists
783 $cfg->{users}->{$user}->{groups}->{$group} = 1;
784 $cfg->{groups}->{$group}->{users}->{$user} = 1;
785 } else {
786 warn "user config - ignore invalid group member '$user'\n";
787 }
788 }
789
790 } elsif ($et eq 'role') {
791 my ($role, $privlist) = @data;
792
793 if (!verify_rolename($role, 1)) {
794 warn "user config - ignore role '$role' - invalid characters in role name\n";
795 next;
796 }
797
798 # make sure to add the role (even if there are no privileges)
799 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
800
801 foreach my $priv (split_list($privlist)) {
802 if (defined ($valid_privs->{$priv})) {
803 $cfg->{roles}->{$role}->{$priv} = 1;
804 } else {
805 warn "user config - ignore invalid priviledge '$priv'\n";
806 }
807 }
808
809 } elsif ($et eq 'acl') {
810 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
811
812 if (my $path = normalize_path($pathtxt)) {
813 foreach my $role (split_list($rolelist)) {
814
815 if (!verify_rolename($role, 1)) {
816 warn "user config - ignore invalid role name '$role' in acl\n";
817 next;
818 }
819
820 foreach my $ug (split_list($uglist)) {
9b217226 821 if ($ug =~ m/^@(\S+)$/) {
2c3a6c0a
DM
822 my $group = $1;
823 if ($cfg->{groups}->{$group}) { # group exists
824 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
825 } else {
826 warn "user config - ignore invalid acl group '$group'\n";
827 }
5bb4e06a 828 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
2c3a6c0a
DM
829 if ($cfg->{users}->{$ug}) { # user exists
830 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
831 } else {
832 warn "user config - ignore invalid acl member '$ug'\n";
833 }
834 } else {
835 warn "user config - invalid user/group '$ug' in acl\n";
836 }
837 }
838 }
839 } else {
840 warn "user config - ignore invalid path in acl '$pathtxt'\n";
841 }
4bc17477 842 } elsif ($et eq 'pool') {
39c85db8 843 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 844
39c85db8
DM
845 if (!verify_poolname($pool, 1)) {
846 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
847 next;
848 }
4bc17477 849
39c85db8
DM
850 # make sure to add the pool (even if there are no members)
851 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 852
39c85db8 853 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 854
39c85db8
DM
855 foreach my $vmid (split_list($vmlist)) {
856 if ($vmid !~ m/^\d+$/) {
857 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
858 next;
4bc17477 859 }
39c85db8 860 $vmid = int($vmid);
4bc17477 861
39c85db8
DM
862 if ($cfg->{vms}->{$vmid}) {
863 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
864 next;
4bc17477
DM
865 }
866
39c85db8
DM
867 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
868
869 # record vmid ==> pool relation
870 $cfg->{vms}->{$vmid} = $pool;
871 }
872
873 foreach my $storeid (split_list($storelist)) {
874 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
875 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
876 next;
877 }
878 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
4bc17477 879 }
2c3a6c0a
DM
880 } else {
881 warn "user config - ignore config line: $line\n";
882 }
883 }
884
885 userconfig_force_defaults($cfg);
886
887 return $cfg;
888}
889
2c3a6c0a
DM
890sub write_user_config {
891 my ($filename, $cfg) = @_;
892
893 my $data = '';
894
895 foreach my $user (keys %{$cfg->{users}}) {
2c3a6c0a
DM
896 my $d = $cfg->{users}->{$user};
897 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
898 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
899 my $email = $d->{email} || '';
900 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
5eabc984 901 my $expire = int($d->{expire} || 0);
2c3a6c0a 902 my $enable = $d->{enable} ? 1 : 0;
96f8ebd6
DM
903 my $keys = $d->{keys} ? $d->{keys} : '';
904 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
2c3a6c0a
DM
905 }
906
907 $data .= "\n";
908
909 foreach my $group (keys %{$cfg->{groups}}) {
910 my $d = $cfg->{groups}->{$group};
911 my $list = join (',', keys %{$d->{users}});
912 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
913 $data .= "group:$group:$list:$comment:\n";
914 }
915
916 $data .= "\n";
917
39c85db8
DM
918 foreach my $pool (keys %{$cfg->{pools}}) {
919 my $d = $cfg->{pools}->{$pool};
4bc17477
DM
920 my $vmlist = join (',', keys %{$d->{vms}});
921 my $storelist = join (',', keys %{$d->{storage}});
922 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 923 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
924 }
925
926 $data .= "\n";
927
2c3a6c0a
DM
928 foreach my $role (keys %{$cfg->{roles}}) {
929 next if $special_roles->{$role};
930
931 my $d = $cfg->{roles}->{$role};
932 my $list = join (',', keys %$d);
933 $data .= "role:$role:$list:\n";
934 }
935
936 $data .= "\n";
937
938 foreach my $path (sort keys %{$cfg->{acl}}) {
939 my $d = $cfg->{acl}->{$path};
940
941 my $ra = {};
942
943 foreach my $group (keys %{$d->{groups}}) {
944 my $l0 = '';
945 my $l1 = '';
946 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
947 my $propagate = $d->{groups}->{$group}->{$role};
948 if ($propagate) {
949 $l1 .= ',' if $l1;
950 $l1 .= $role;
951 } else {
952 $l0 .= ',' if $l0;
953 $l0 .= $role;
954 }
955 }
956 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
957 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
958 }
959
960 foreach my $user (keys %{$d->{users}}) {
961 # no need to save, because root is always 'Administartor'
962 next if $user eq 'root@pam';
963
964 my $l0 = '';
965 my $l1 = '';
966 foreach my $role (sort keys %{$d->{users}->{$user}}) {
967 my $propagate = $d->{users}->{$user}->{$role};
968 if ($propagate) {
969 $l1 .= ',' if $l1;
970 $l1 .= $role;
971 } else {
972 $l0 .= ',' if $l0;
973 $l0 .= $role;
974 }
975 }
976 $ra->{0}->{$l0}->{$user} = 1 if $l0;
977 $ra->{1}->{$l1}->{$user} = 1 if $l1;
978 }
979
980 foreach my $rolelist (sort keys %{$ra->{0}}) {
981 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
982 $data .= "acl:0:$path:$uglist:$rolelist:\n";
983 }
984 foreach my $rolelist (sort keys %{$ra->{1}}) {
985 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
986 $data .= "acl:1:$path:$uglist:$rolelist:\n";
987 }
988 }
989
990 return $data;
991}
992
993sub roles {
994 my ($cfg, $user, $path) = @_;
995
4bc17477
DM
996 # NOTE: we do not consider pools here.
997 # You need to use $rpcenv->roles() instead if you want that.
998
2c3a6c0a
DM
999 return 'Administrator' if $user eq 'root@pam'; # root can do anything
1000
1001 my $perm = {};
1002
1003 foreach my $p (sort keys %{$cfg->{acl}}) {
1004 my $final = ($path eq $p);
1005
1006 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1007
1008 my $acl = $cfg->{acl}->{$p};
1009
1010 #print "CHECKACL $path $p\n";
1011 #print "ACL $path = " . Dumper ($acl);
1012
1013 if (my $ri = $acl->{users}->{$user}) {
1014 my $new;
1015 foreach my $role (keys %$ri) {
1016 my $propagate = $ri->{$role};
1017 if ($final || $propagate) {
1018 #print "APPLY ROLE $p $user $role\n";
1019 $new = {} if !$new;
1020 $new->{$role} = 1;
1021 }
1022 }
1023 if ($new) {
1024 $perm = $new; # overwrite previous settings
1025 next; # user privs always override group privs
1026 }
1027 }
1028
1029 my $new;
1030 foreach my $g (keys %{$acl->{groups}}) {
1031 next if !$cfg->{groups}->{$g}->{users}->{$user};
1032 if (my $ri = $acl->{groups}->{$g}) {
1033 foreach my $role (keys %$ri) {
1034 my $propagate = $ri->{$role};
1035 if ($final || $propagate) {
1036 #print "APPLY ROLE $p \@$g $role\n";
1037 $new = {} if !$new;
1038 $new->{$role} = 1;
1039 }
1040 }
1041 }
1042 }
1043 if ($new) {
1044 $perm = $new; # overwrite previous settings
1045 next;
1046 }
2c3a6c0a
DM
1047 }
1048
4bc17477
DM
1049 return ('NoAccess') if defined ($perm->{NoAccess});
1050 #return () if defined ($perm->{NoAccess});
2c3a6c0a
DM
1051
1052 #print "permission $user $path = " . Dumper ($perm);
1053
4bc17477 1054 my @ra = keys %$perm;
2c3a6c0a
DM
1055
1056 #print "roles $user $path = " . join (',', @ra) . "\n";
1057
1058 return @ra;
1059}
1060
1061sub permission {
1062 my ($cfg, $user, $path) = @_;
1063
5bb4e06a 1064 $user = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
1065 return {} if !$user;
1066
1067 my @ra = roles($cfg, $user, $path);
1068
1069 my $privs = {};
1070
1071 foreach my $role (@ra) {
1072 if (my $privset = $cfg->{roles}->{$role}) {
1073 foreach my $p (keys %$privset) {
1074 $privs->{$p} = 1;
1075 }
1076 }
1077 }
1078
1079 #print "priviledges $user $path = " . Dumper ($privs);
1080
1081 return $privs;
1082}
1083
1084sub check_permissions {
1085 my ($username, $path, $privlist) = @_;
1086
1087 $path = normalize_path($path);
1088 my $usercfg = cfs_read_file('user.cfg');
1089 my $perm = permission($usercfg, $username, $path);
1090
1091 foreach my $priv (split_list($privlist)) {
1092 return undef if !$perm->{$priv};
1093 };
1094
1095 return 1;
1096}
1097
018ae3a9
DM
1098sub add_vm_to_pool {
1099 my ($vmid, $pool) = @_;
1100
1101 my $addVMtoPoolFn = sub {
1102 my $usercfg = cfs_read_file("user.cfg");
1103 if (my $data = $usercfg->{pools}->{$pool}) {
1104 $data->{vms}->{$vmid} = 1;
1105 $usercfg->{vms}->{$vmid} = $pool;
1106 cfs_write_file("user.cfg", $usercfg);
1107 }
1108 };
1109
1110 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1111}
1112
1113sub remove_vm_from_pool {
1114 my ($vmid) = @_;
1115
1116 my $delVMfromPoolFn = sub {
1117 my $usercfg = cfs_read_file("user.cfg");
1118 if (my $pool = $usercfg->{vms}->{$vmid}) {
1119 if (my $data = $usercfg->{pools}->{$pool}) {
1120 delete $data->{vms}->{$vmid};
1121 delete $usercfg->{vms}->{$vmid};
1122 cfs_write_file("user.cfg", $usercfg);
1123 }
1124 }
1125 };
1126
1127 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1128}
1129
ab652a80
DM
1130# experimental code for yubico OTP verification
1131
1132sub yubico_compute_param_sig {
1133 my ($param, $api_key) = @_;
1134
1135 my $paramstr = '';
1136 foreach my $key (sort keys %$param) {
1137 $paramstr .= '&' if $paramstr;
1138 $paramstr .= "$key=$param->{$key}";
1139 }
1140
1141 my $sig = uri_escape(encode_base64(Digest::HMAC_SHA1::hmac_sha1($paramstr, decode_base64($api_key || '')), ''));
1142
1143 return ($paramstr, $sig);
1144}
1145
1146sub yubico_verify_otp {
96f8ebd6
DM
1147 my ($otp, $keys, $url, $api_id, $api_key, $proxy) = @_;
1148
1149 die "yubico: missing password\n" if !defined($otp);
1150 die "yubico: missing API ID\n" if !defined($api_id);
1151 die "yubico: missing API KEY\n" if !defined($api_key);
1152 die "yubico: no associated yubico keys\n" if $keys =~ m/^\s+$/;
ab652a80 1153
96f8ebd6 1154 die "yubico: wrong OTP lenght\n" if (length($otp) < 32) || (length($otp) > 48);
ab652a80
DM
1155
1156 # we always use http, because https cert verification always make problem, and
1157 # some proxies does not work with https.
1158
96f8ebd6 1159 $url = 'http://api2.yubico.com/wsapi/2.0/verify' if !defined($url);
ab652a80
DM
1160
1161 my $params = {
1162 nonce => Digest::HMAC_SHA1::hmac_sha1_hex(time(), rand()),
1163 id => $api_id,
1164 otp => uri_escape($otp),
1165 timestamp => 1,
1166 };
1167
1168 my ($paramstr, $sig) = yubico_compute_param_sig($params, $api_key);
1169
1170 $paramstr .= "&h=$sig" if $api_key;
1171
1172 my $req = HTTP::Request->new('GET' => "$url?$paramstr");
1173
1174 my $ua = LWP::UserAgent->new(protocols_allowed => ['http'], timeout => 30);
1175
1176 if ($proxy) {
1177 $ua->proxy(['http'], $proxy);
1178 } else {
1179 $ua->env_proxy;
1180 }
1181
1182 my $response = $ua->request($req);
1183 my $code = $response->code;
1184
1185 if ($code != 200) {
1186 my $msg = $response->message || 'unknown';
1187 die "Invalid response from server: $code $msg\n";
1188 }
1189
1190 my $raw = $response->decoded_content;
1191
1192 my $result = {};
1193 foreach my $kvpair (split(/\n/, $raw)) {
1194 chomp $kvpair;
1195 if($kvpair =~ /^\S+=/) {
1196 my ($k, $v) = split(/=/, $kvpair, 2);
1197 $v =~ s/\s//g;
1198 $result->{$k} = $v;
1199 }
1200 }
1201
1202 my $rsig = $result->{h};
1203 delete $result->{h};
1204
1205 if ($api_key) {
1206 my ($datastr, $vsig) = yubico_compute_param_sig($result, $api_key);
1207 $vsig = uri_unescape($vsig);
96f8ebd6 1208 die "yubico: result signature verification failed\n" if $rsig ne $vsig;
ab652a80
DM
1209 }
1210
96f8ebd6
DM
1211 die "yubico auth failed: $result->{status}\n" if $result->{status} ne 'OK';
1212
1213 my $publicid = $result->{publicid} = substr(lc($result->{otp}), 0, 12);
1214
1215 my $found;
1216 foreach my $k (PVE::Tools::split_list($keys)) {
1217 if ($k eq $publicid) {
1218 $found = 1;
1219 last;
1220 }
1221 }
ab652a80 1222
96f8ebd6 1223 die "yubico auth failed: key does not belong to user\n" if !$found;
ab652a80
DM
1224
1225 return $result;
1226}
1227
1abc2c0a 1228sub oath_verify_otp {
86cd805b 1229 my ($otp, $keys, $step, $digits) = @_;
1abc2c0a
DM
1230
1231 die "oath: missing password\n" if !defined($otp);
1232 die "oath: no associated oath keys\n" if $keys =~ m/^\s+$/;
1233
86cd805b
DM
1234 $step = 30 if !$step;
1235 $digits = 6 if !$digits;
1abc2c0a
DM
1236
1237 my $found;
1238
1239 my $parser = sub {
1240 my $line = shift;
1241
1242 if ($line =~ m/^\d{6}$/) {
1abc2c0a
DM
1243 $found = 1 if $otp eq $line;
1244 }
1245 };
1246
1247 foreach my $k (PVE::Tools::split_list($keys)) {
1248 # Note: we generate 3 values to allow small time drift
1249 my $now = localtime(time() - $step);
86cd805b 1250 my $cmd = ['oathtool', '--totp', '--digits', $digits, '-N', $now, '-s', $step, '-w', '2', '-b', $k];
1abc2c0a
DM
1251 eval { run_command($cmd, outfunc => $parser, errfunc => sub {}); };
1252 last if $found;
1253 }
1254
1255 die "oath auth failed\n" if !$found;
1256}
1257
2c3a6c0a 12581;