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