54577aa228a14f5269611f9c442175bc35b96a17
[pve-access-control.git] / PVE / AccessControl.pm
1 package PVE::AccessControl;
2
3 use strict;
4 use warnings;
5 use Encode;
6 use Crypt::OpenSSL::Random;
7 use Crypt::OpenSSL::RSA;
8 use Net::SSLeay;
9 use Net::IP;
10 use MIME::Base64;
11 use Digest::SHA;
12 use Digest::HMAC_SHA1;
13 use URI::Escape;
14 use LWP::UserAgent;
15 use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
16 use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
17 use PVE::JSONSchema;
18
19 use PVE::Auth::Plugin;
20 use PVE::Auth::AD;
21 use PVE::Auth::LDAP;
22 use PVE::Auth::PVE;
23 use PVE::Auth::PAM;
24
25 use Data::Dumper; # fixme: remove
26
27 # load and initialize all plugins
28
29 PVE::Auth::AD->register();
30 PVE::Auth::LDAP->register();
31 PVE::Auth::PVE->register();
32 PVE::Auth::PAM->register();
33 PVE::Auth::Plugin->init();
34
35 # $authdir must be writable by root only!
36 my $confdir = "/etc/pve";
37 my $authdir = "$confdir/priv";
38 my $authprivkeyfn = "$authdir/authkey.key";
39 my $authpubkeyfn = "$confdir/authkey.pub";
40 my $pve_www_key_fn = "$confdir/pve-www.key";
41
42 my $ticket_lifetime = 3600*2; # 2 hours
43
44 Crypt::OpenSSL::RSA->import_random_seed();
45
46 cfs_register_file('user.cfg',
47 \&parse_user_config,
48 \&write_user_config);
49
50
51 sub verify_username {
52 PVE::Auth::Plugin::verify_username(@_);
53 }
54
55 sub pve_verify_realm {
56 PVE::Auth::Plugin::pve_verify_realm(@_);
57 }
58
59 sub lock_user_config {
60 my ($code, $errmsg) = @_;
61
62 cfs_lock_file("user.cfg", undef, $code);
63 if (my $err = $@) {
64 $errmsg ? die "$errmsg: $err" : die $err;
65 }
66 }
67
68 my $pve_auth_pub_key;
69 sub 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
80 my $csrf_prevention_secret;
81 my $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
89 sub 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
99 sub 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
118 my $pve_auth_priv_key;
119 sub 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
130 sub 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
144 sub verify_ticket {
145 my ($ticket, $noerr) = @_;
146
147 if ($ticket && $ticket =~ m/^(PVE:\S+)::([^:\s]+)$/) {
148 my $plain = $1;
149 my $sig = $2;
150
151 my $rsa_pub = get_pubkey();
152 if ($rsa_pub->verify($plain, decode_base64($sig))) {
153 if ($plain =~ m/^PVE:(\S+):([A-Z0-9]{8})$/) {
154 my $username = $1;
155 my $timestamp = $2;
156 my $ttime = hex($timestamp);
157
158 my $age = time() - $ttime;
159
160 if (PVE::Auth::Plugin::verify_username($username, 1) &&
161 ($age > -300) && ($age < $ticket_lifetime)) {
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
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')
176 sub 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
194 sub 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
222 sub assemble_spice_ticket {
223 my ($username, $vmid, $node) = @_;
224
225 my $rsa_priv = get_privkey();
226
227 my $timestamp = sprintf("%08x", time());
228
229 my $randomstr = "PVESPICE:$timestamp:$vmid:$node:" . rand(10);
230
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));
236
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
243 # Note: RSA signature are too long (>=256 charaters) and makes problems with remote-viewer
244
245 my $secret = &$get_csrfr_secret();
246 my $plain = "pvespiceproxy:$timestamp:$vmid:" . lc($node);
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)
252
253 my $proxyticket = $plain . "::" . $sig;
254
255 return ($ticket, $proxyticket);
256 }
257
258 sub 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
266 if ($connect_str =~m/^pvespiceproxy:([a-z0-9]{8}):(\d+):(\S+)::([a-z0-9]{40}):(\d+)$/) {
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
274 my $plain = "pvespiceproxy:$timestamp:$vmid:$node";
275 my $sig = unpack("H*", Digest::SHA::sha1($plain, &$get_csrfr_secret()));
276
277 if ($sig eq $hexsig) {
278 return ($vmid, $node, $port);
279 }
280 }
281
282 return undef;
283 }
284
285 sub 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
304 sub 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;
320
321 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
322 my $config = {
323 'secure-attention' => "Ctrl+Alt+Ins",
324 'toggle-fullscreen' => "Shift+F11",
325 'release-cursor' => "Ctrl+Alt+R",
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
340 sub check_user_exist {
341 my ($usercfg, $username, $noerr) = @_;
342
343 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
344 return undef if !$username;
345
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
353 sub 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};
360
361 die "user '$username' is disabled\n" if !$noerr;
362
363 return undef;
364 }
365
366 sub 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);
379 } elsif ($type eq 'oath') {
380 my $keys = $usercfg->{users}->{$username}->{keys};
381 oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
382 } else {
383 die "unknown tfa type '$type'\n";
384 }
385 }
386
387 # password should be utf8 encoded
388 # Note: some pluging delay/sleep if auth fails
389 sub authenticate_user {
390 my ($username, $password, $otp) = @_;
391
392 die "no username specified\n" if !$username;
393
394 my ($ruid, $realm);
395
396 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
397
398 my $usercfg = cfs_read_file('user.cfg');
399
400 check_user_enabled($usercfg, $username);
401
402 my $ctime = time();
403 my $expire = $usercfg->{users}->{$username}->{expire};
404
405 die "account expired\n" if $expire && ($expire < $ctime);
406
407 my $domain_cfg = cfs_read_file('domains.cfg');
408
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);
413
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
419 return $username;
420 }
421
422 sub domain_set_password {
423 my ($realm, $username, $password) = @_;
424
425 die "no auth domain specified" if !$realm;
426
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);
433 }
434
435 sub 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
442 sub 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
453 sub 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 }
462 }
463
464 sub 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 }
473 }
474
475 sub delete_pool_acl {
476
477 my ($pool, $usercfg) = @_;
478
479 my $path = "/pool/$pool";
480
481 delete ($usercfg->{acl}->{$path})
482 }
483
484 # we automatically create some predefined roles by splitting privs
485 # into 3 groups (per category)
486 # root: only root is allowed to do that
487 # admin: an administrator can to that
488 # user: a normak user/customer can to that
489 my $privgroups = {
490 VM => {
491 root => [],
492 admin => [
493 'VM.Config.Disk',
494 'VM.Config.CPU',
495 'VM.Config.Memory',
496 'VM.Config.Network',
497 'VM.Config.HWType',
498 'VM.Config.Options', # covers all other things
499 'VM.Allocate',
500 'VM.Clone',
501 'VM.Migrate',
502 'VM.Monitor',
503 'VM.Snapshot',
504 ],
505 user => [
506 'VM.Config.CDROM', # change CDROM media
507 'VM.Console',
508 'VM.Backup',
509 'VM.PowerMgmt',
510 ],
511 audit => [
512 'VM.Audit',
513 ],
514 },
515 Sys => {
516 root => [
517 'Sys.PowerMgmt',
518 'Sys.Modify', # edit/change node settings
519 ],
520 admin => [
521 'Permissions.Modify',
522 'Sys.Console',
523 'Sys.Syslog',
524 ],
525 user => [],
526 audit => [
527 'Sys.Audit',
528 ],
529 },
530 Datastore => {
531 root => [],
532 admin => [
533 'Datastore.Allocate',
534 'Datastore.AllocateTemplate',
535 ],
536 user => [
537 'Datastore.AllocateSpace',
538 ],
539 audit => [
540 'Datastore.Audit',
541 ],
542 },
543 User => {
544 root => [
545 'Realm.Allocate',
546 ],
547 admin => [
548 'User.Modify',
549 'Group.Allocate', # edit/change group settings
550 'Realm.AllocateUser',
551 ],
552 user => [],
553 audit => [],
554 },
555 Pool => {
556 root => [],
557 admin => [
558 'Pool.Allocate', # create/delete pools
559 ],
560 user => [],
561 audit => [],
562 },
563 };
564
565 my $valid_privs = {};
566
567 my $special_roles = {
568 'NoAccess' => {}, # no priviledges
569 'Administrator' => $valid_privs, # all priviledges
570 };
571
572 sub create_roles {
573
574 foreach my $cat (keys %$privgroups) {
575 my $cd = $privgroups->{$cat};
576 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
577 @{$cd->{user}}, @{$cd->{audit}}) {
578 $valid_privs->{$p} = 1;
579 }
580 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
581
582 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
583 $special_roles->{"PVEAdmin"}->{$p} = 1;
584 }
585 if (scalar(@{$cd->{user}})) {
586 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
587 $special_roles->{"PVE${cat}User"}->{$p} = 1;
588 }
589 }
590 foreach my $p (@{$cd->{audit}}) {
591 $special_roles->{"PVEAuditor"}->{$p} = 1;
592 }
593 }
594
595 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
596 };
597
598 create_roles();
599
600 sub add_role_privs {
601 my ($role, $usercfg, $privs) = @_;
602
603 return if !$privs;
604
605 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
606
607 foreach my $priv (split_list($privs)) {
608 if (defined ($valid_privs->{$priv})) {
609 $usercfg->{roles}->{$role}->{$priv} = 1;
610 } else {
611 die "invalid priviledge '$priv'\n";
612 }
613 }
614 }
615
616 sub normalize_path {
617 my $path = shift;
618
619 $path =~ s|/+|/|g;
620
621 $path =~ s|/$||;
622
623 $path = '/' if !$path;
624
625 $path = "/$path" if $path !~ m|^/|;
626
627 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
628
629 return $path;
630 }
631
632
633 PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
634 sub verify_groupname {
635 my ($groupname, $noerr) = @_;
636
637 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
638
639 die "group name '$groupname' contains invalid characters\n" if !$noerr;
640
641 return undef;
642 }
643
644 return $groupname;
645 }
646
647 PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
648 sub verify_rolename {
649 my ($rolename, $noerr) = @_;
650
651 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
652
653 die "role name '$rolename' contains invalid characters\n" if !$noerr;
654
655 return undef;
656 }
657
658 return $rolename;
659 }
660
661 PVE::JSONSchema::register_format('pve-poolid', \&verify_groupname);
662 sub verify_poolname {
663 my ($poolname, $noerr) = @_;
664
665 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
666
667 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
668
669 return undef;
670 }
671
672 return $poolname;
673 }
674
675 PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
676 sub verify_privname {
677 my ($priv, $noerr) = @_;
678
679 if (!$valid_privs->{$priv}) {
680 die "invalid priviledge '$priv'\n" if !$noerr;
681
682 return undef;
683 }
684
685 return $priv;
686 }
687
688 sub userconfig_force_defaults {
689 my ($cfg) = @_;
690
691 foreach my $r (keys %$special_roles) {
692 $cfg->{roles}->{$r} = $special_roles->{$r};
693 }
694
695 # add root user if not exists
696 if (!$cfg->{users}->{'root@pam'}) {
697 $cfg->{users}->{'root@pam'}->{enable} = 1;
698 }
699 }
700
701 sub parse_user_config {
702 my ($filename, $raw) = @_;
703
704 my $cfg = {};
705
706 userconfig_force_defaults($cfg);
707
708 $raw = '' if !defined($raw);
709 while ($raw =~ /^\s*(.+?)\s*$/gm) {
710 my $line = $1;
711 my @data;
712
713 foreach my $d (split (/:/, $line)) {
714 $d =~ s/^\s+//;
715 $d =~ s/\s+$//;
716 push @data, $d
717 }
718
719 my $et = shift @data;
720
721 if ($et eq 'user') {
722 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
723
724 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
725 if (!$realm) {
726 warn "user config - ignore user '$user' - invalid user name\n";
727 next;
728 }
729
730 $enable = $enable ? 1 : 0;
731
732 $expire = 0 if !$expire;
733
734 if ($expire !~ m/^\d+$/) {
735 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
736 next;
737 }
738 $expire = int($expire);
739
740 #if (!verify_groupname ($group, 1)) {
741 # warn "user config - ignore user '$user' - invalid characters in group name\n";
742 # next;
743 #}
744
745 $cfg->{users}->{$user} = {
746 enable => $enable,
747 # group => $group,
748 };
749 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
750 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
751 $cfg->{users}->{$user}->{email} = $email;
752 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
753 $cfg->{users}->{$user}->{expire} = $expire;
754 # keys: allowed yubico key ids or oath secrets (base32 encoded)
755 $cfg->{users}->{$user}->{keys} = $keys if $keys;
756
757 #$cfg->{users}->{$user}->{groups}->{$group} = 1;
758 #$cfg->{groups}->{$group}->{$user} = 1;
759
760 } elsif ($et eq 'group') {
761 my ($group, $userlist, $comment) = @data;
762
763 if (!verify_groupname($group, 1)) {
764 warn "user config - ignore group '$group' - invalid characters in group name\n";
765 next;
766 }
767
768 # make sure to add the group (even if there are no members)
769 $cfg->{groups}->{$group} = { users => {} } if !$cfg->{groups}->{$group};
770
771 $cfg->{groups}->{$group}->{comment} = PVE::Tools::decode_text($comment) if $comment;
772
773 foreach my $user (split_list($userlist)) {
774
775 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
776 warn "user config - ignore invalid group member '$user'\n";
777 next;
778 }
779
780 if ($cfg->{users}->{$user}) { # user exists
781 $cfg->{users}->{$user}->{groups}->{$group} = 1;
782 $cfg->{groups}->{$group}->{users}->{$user} = 1;
783 } else {
784 warn "user config - ignore invalid group member '$user'\n";
785 }
786 }
787
788 } elsif ($et eq 'role') {
789 my ($role, $privlist) = @data;
790
791 if (!verify_rolename($role, 1)) {
792 warn "user config - ignore role '$role' - invalid characters in role name\n";
793 next;
794 }
795
796 # make sure to add the role (even if there are no privileges)
797 $cfg->{roles}->{$role} = {} if !$cfg->{roles}->{$role};
798
799 foreach my $priv (split_list($privlist)) {
800 if (defined ($valid_privs->{$priv})) {
801 $cfg->{roles}->{$role}->{$priv} = 1;
802 } else {
803 warn "user config - ignore invalid priviledge '$priv'\n";
804 }
805 }
806
807 } elsif ($et eq 'acl') {
808 my ($propagate, $pathtxt, $uglist, $rolelist) = @data;
809
810 if (my $path = normalize_path($pathtxt)) {
811 foreach my $role (split_list($rolelist)) {
812
813 if (!verify_rolename($role, 1)) {
814 warn "user config - ignore invalid role name '$role' in acl\n";
815 next;
816 }
817
818 foreach my $ug (split_list($uglist)) {
819 if ($ug =~ m/^@(\S+)$/) {
820 my $group = $1;
821 if ($cfg->{groups}->{$group}) { # group exists
822 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
823 } else {
824 warn "user config - ignore invalid acl group '$group'\n";
825 }
826 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
827 if ($cfg->{users}->{$ug}) { # user exists
828 $cfg->{acl}->{$path}->{users}->{$ug}->{$role} = $propagate;
829 } else {
830 warn "user config - ignore invalid acl member '$ug'\n";
831 }
832 } else {
833 warn "user config - invalid user/group '$ug' in acl\n";
834 }
835 }
836 }
837 } else {
838 warn "user config - ignore invalid path in acl '$pathtxt'\n";
839 }
840 } elsif ($et eq 'pool') {
841 my ($pool, $comment, $vmlist, $storelist) = @data;
842
843 if (!verify_poolname($pool, 1)) {
844 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
845 next;
846 }
847
848 # make sure to add the pool (even if there are no members)
849 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
850
851 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
852
853 foreach my $vmid (split_list($vmlist)) {
854 if ($vmid !~ m/^\d+$/) {
855 warn "user config - ignore invalid vmid '$vmid' in pool '$pool'\n";
856 next;
857 }
858 $vmid = int($vmid);
859
860 if ($cfg->{vms}->{$vmid}) {
861 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
862 next;
863 }
864
865 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
866
867 # record vmid ==> pool relation
868 $cfg->{vms}->{$vmid} = $pool;
869 }
870
871 foreach my $storeid (split_list($storelist)) {
872 if ($storeid !~ m/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i) {
873 warn "user config - ignore invalid storage '$storeid' in pool '$pool'\n";
874 next;
875 }
876 $cfg->{pools}->{$pool}->{storage}->{$storeid} = 1;
877 }
878 } else {
879 warn "user config - ignore config line: $line\n";
880 }
881 }
882
883 userconfig_force_defaults($cfg);
884
885 return $cfg;
886 }
887
888 sub write_user_config {
889 my ($filename, $cfg) = @_;
890
891 my $data = '';
892
893 foreach my $user (keys %{$cfg->{users}}) {
894 my $d = $cfg->{users}->{$user};
895 my $firstname = $d->{firstname} ? PVE::Tools::encode_text($d->{firstname}) : '';
896 my $lastname = $d->{lastname} ? PVE::Tools::encode_text($d->{lastname}) : '';
897 my $email = $d->{email} || '';
898 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
899 my $expire = int($d->{expire} || 0);
900 my $enable = $d->{enable} ? 1 : 0;
901 my $keys = $d->{keys} ? $d->{keys} : '';
902 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
903 }
904
905 $data .= "\n";
906
907 foreach my $group (keys %{$cfg->{groups}}) {
908 my $d = $cfg->{groups}->{$group};
909 my $list = join (',', keys %{$d->{users}});
910 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
911 $data .= "group:$group:$list:$comment:\n";
912 }
913
914 $data .= "\n";
915
916 foreach my $pool (keys %{$cfg->{pools}}) {
917 my $d = $cfg->{pools}->{$pool};
918 my $vmlist = join (',', keys %{$d->{vms}});
919 my $storelist = join (',', keys %{$d->{storage}});
920 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
921 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
922 }
923
924 $data .= "\n";
925
926 foreach my $role (keys %{$cfg->{roles}}) {
927 next if $special_roles->{$role};
928
929 my $d = $cfg->{roles}->{$role};
930 my $list = join (',', keys %$d);
931 $data .= "role:$role:$list:\n";
932 }
933
934 $data .= "\n";
935
936 foreach my $path (sort keys %{$cfg->{acl}}) {
937 my $d = $cfg->{acl}->{$path};
938
939 my $ra = {};
940
941 foreach my $group (keys %{$d->{groups}}) {
942 my $l0 = '';
943 my $l1 = '';
944 foreach my $role (sort keys %{$d->{groups}->{$group}}) {
945 my $propagate = $d->{groups}->{$group}->{$role};
946 if ($propagate) {
947 $l1 .= ',' if $l1;
948 $l1 .= $role;
949 } else {
950 $l0 .= ',' if $l0;
951 $l0 .= $role;
952 }
953 }
954 $ra->{0}->{$l0}->{"\@$group"} = 1 if $l0;
955 $ra->{1}->{$l1}->{"\@$group"} = 1 if $l1;
956 }
957
958 foreach my $user (keys %{$d->{users}}) {
959 # no need to save, because root is always 'Administartor'
960 next if $user eq 'root@pam';
961
962 my $l0 = '';
963 my $l1 = '';
964 foreach my $role (sort keys %{$d->{users}->{$user}}) {
965 my $propagate = $d->{users}->{$user}->{$role};
966 if ($propagate) {
967 $l1 .= ',' if $l1;
968 $l1 .= $role;
969 } else {
970 $l0 .= ',' if $l0;
971 $l0 .= $role;
972 }
973 }
974 $ra->{0}->{$l0}->{$user} = 1 if $l0;
975 $ra->{1}->{$l1}->{$user} = 1 if $l1;
976 }
977
978 foreach my $rolelist (sort keys %{$ra->{0}}) {
979 my $uglist = join (',', keys %{$ra->{0}->{$rolelist}});
980 $data .= "acl:0:$path:$uglist:$rolelist:\n";
981 }
982 foreach my $rolelist (sort keys %{$ra->{1}}) {
983 my $uglist = join (',', keys %{$ra->{1}->{$rolelist}});
984 $data .= "acl:1:$path:$uglist:$rolelist:\n";
985 }
986 }
987
988 return $data;
989 }
990
991 sub roles {
992 my ($cfg, $user, $path) = @_;
993
994 # NOTE: we do not consider pools here.
995 # You need to use $rpcenv->roles() instead if you want that.
996
997 return 'Administrator' if $user eq 'root@pam'; # root can do anything
998
999 my $perm = {};
1000
1001 foreach my $p (sort keys %{$cfg->{acl}}) {
1002 my $final = ($path eq $p);
1003
1004 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
1005
1006 my $acl = $cfg->{acl}->{$p};
1007
1008 #print "CHECKACL $path $p\n";
1009 #print "ACL $path = " . Dumper ($acl);
1010
1011 if (my $ri = $acl->{users}->{$user}) {
1012 my $new;
1013 foreach my $role (keys %$ri) {
1014 my $propagate = $ri->{$role};
1015 if ($final || $propagate) {
1016 #print "APPLY ROLE $p $user $role\n";
1017 $new = {} if !$new;
1018 $new->{$role} = 1;
1019 }
1020 }
1021 if ($new) {
1022 $perm = $new; # overwrite previous settings
1023 next; # user privs always override group privs
1024 }
1025 }
1026
1027 my $new;
1028 foreach my $g (keys %{$acl->{groups}}) {
1029 next if !$cfg->{groups}->{$g}->{users}->{$user};
1030 if (my $ri = $acl->{groups}->{$g}) {
1031 foreach my $role (keys %$ri) {
1032 my $propagate = $ri->{$role};
1033 if ($final || $propagate) {
1034 #print "APPLY ROLE $p \@$g $role\n";
1035 $new = {} if !$new;
1036 $new->{$role} = 1;
1037 }
1038 }
1039 }
1040 }
1041 if ($new) {
1042 $perm = $new; # overwrite previous settings
1043 next;
1044 }
1045 }
1046
1047 return ('NoAccess') if defined ($perm->{NoAccess});
1048 #return () if defined ($perm->{NoAccess});
1049
1050 #print "permission $user $path = " . Dumper ($perm);
1051
1052 my @ra = keys %$perm;
1053
1054 #print "roles $user $path = " . join (',', @ra) . "\n";
1055
1056 return @ra;
1057 }
1058
1059 sub permission {
1060 my ($cfg, $user, $path) = @_;
1061
1062 $user = PVE::Auth::Plugin::verify_username($user, 1);
1063 return {} if !$user;
1064
1065 my @ra = roles($cfg, $user, $path);
1066
1067 my $privs = {};
1068
1069 foreach my $role (@ra) {
1070 if (my $privset = $cfg->{roles}->{$role}) {
1071 foreach my $p (keys %$privset) {
1072 $privs->{$p} = 1;
1073 }
1074 }
1075 }
1076
1077 #print "priviledges $user $path = " . Dumper ($privs);
1078
1079 return $privs;
1080 }
1081
1082 sub check_permissions {
1083 my ($username, $path, $privlist) = @_;
1084
1085 $path = normalize_path($path);
1086 my $usercfg = cfs_read_file('user.cfg');
1087 my $perm = permission($usercfg, $username, $path);
1088
1089 foreach my $priv (split_list($privlist)) {
1090 return undef if !$perm->{$priv};
1091 };
1092
1093 return 1;
1094 }
1095
1096 sub remove_vm_access {
1097 my ($vmid) = @_;
1098 my $delVMaccessFn = sub {
1099 my $usercfg = cfs_read_file("user.cfg");
1100
1101 if (my $acl = $usercfg->{acl}->{'/vms/'.$vmid}) {
1102 delete $usercfg->{acl}->{'/vms/'.$vmid};
1103 cfs_write_file("user.cfg", $usercfg);
1104 }
1105 if (my $pool = $usercfg->{vms}->{$vmid}) {
1106 if (my $data = $usercfg->{pools}->{$pool}) {
1107 delete $data->{vms}->{$vmid};
1108 delete $usercfg->{vms}->{$vmid};
1109 cfs_write_file("user.cfg", $usercfg);
1110 }
1111 }
1112 };
1113
1114 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1115 }
1116
1117 sub add_vm_to_pool {
1118 my ($vmid, $pool) = @_;
1119
1120 my $addVMtoPoolFn = sub {
1121 my $usercfg = cfs_read_file("user.cfg");
1122 if (my $data = $usercfg->{pools}->{$pool}) {
1123 $data->{vms}->{$vmid} = 1;
1124 $usercfg->{vms}->{$vmid} = $pool;
1125 cfs_write_file("user.cfg", $usercfg);
1126 }
1127 };
1128
1129 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1130 }
1131
1132 sub remove_vm_from_pool {
1133 my ($vmid) = @_;
1134
1135 my $delVMfromPoolFn = sub {
1136 my $usercfg = cfs_read_file("user.cfg");
1137 if (my $pool = $usercfg->{vms}->{$vmid}) {
1138 if (my $data = $usercfg->{pools}->{$pool}) {
1139 delete $data->{vms}->{$vmid};
1140 delete $usercfg->{vms}->{$vmid};
1141 cfs_write_file("user.cfg", $usercfg);
1142 }
1143 }
1144 };
1145
1146 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1147 }
1148
1149 # experimental code for yubico OTP verification
1150
1151 sub yubico_compute_param_sig {
1152 my ($param, $api_key) = @_;
1153
1154 my $paramstr = '';
1155 foreach my $key (sort keys %$param) {
1156 $paramstr .= '&' if $paramstr;
1157 $paramstr .= "$key=$param->{$key}";
1158 }
1159
1160 my $sig = uri_escape(encode_base64(Digest::HMAC_SHA1::hmac_sha1($paramstr, decode_base64($api_key || '')), ''));
1161
1162 return ($paramstr, $sig);
1163 }
1164
1165 sub yubico_verify_otp {
1166 my ($otp, $keys, $url, $api_id, $api_key, $proxy) = @_;
1167
1168 die "yubico: missing password\n" if !defined($otp);
1169 die "yubico: missing API ID\n" if !defined($api_id);
1170 die "yubico: missing API KEY\n" if !defined($api_key);
1171 die "yubico: no associated yubico keys\n" if $keys =~ m/^\s+$/;
1172
1173 die "yubico: wrong OTP lenght\n" if (length($otp) < 32) || (length($otp) > 48);
1174
1175 # we always use http, because https cert verification always make problem, and
1176 # some proxies does not work with https.
1177
1178 $url = 'http://api2.yubico.com/wsapi/2.0/verify' if !defined($url);
1179
1180 my $params = {
1181 nonce => Digest::HMAC_SHA1::hmac_sha1_hex(time(), rand()),
1182 id => $api_id,
1183 otp => uri_escape($otp),
1184 timestamp => 1,
1185 };
1186
1187 my ($paramstr, $sig) = yubico_compute_param_sig($params, $api_key);
1188
1189 $paramstr .= "&h=$sig" if $api_key;
1190
1191 my $req = HTTP::Request->new('GET' => "$url?$paramstr");
1192
1193 my $ua = LWP::UserAgent->new(protocols_allowed => ['http'], timeout => 30);
1194
1195 if ($proxy) {
1196 $ua->proxy(['http'], $proxy);
1197 } else {
1198 $ua->env_proxy;
1199 }
1200
1201 my $response = $ua->request($req);
1202 my $code = $response->code;
1203
1204 if ($code != 200) {
1205 my $msg = $response->message || 'unknown';
1206 die "Invalid response from server: $code $msg\n";
1207 }
1208
1209 my $raw = $response->decoded_content;
1210
1211 my $result = {};
1212 foreach my $kvpair (split(/\n/, $raw)) {
1213 chomp $kvpair;
1214 if($kvpair =~ /^\S+=/) {
1215 my ($k, $v) = split(/=/, $kvpair, 2);
1216 $v =~ s/\s//g;
1217 $result->{$k} = $v;
1218 }
1219 }
1220
1221 my $rsig = $result->{h};
1222 delete $result->{h};
1223
1224 if ($api_key) {
1225 my ($datastr, $vsig) = yubico_compute_param_sig($result, $api_key);
1226 $vsig = uri_unescape($vsig);
1227 die "yubico: result signature verification failed\n" if $rsig ne $vsig;
1228 }
1229
1230 die "yubico auth failed: $result->{status}\n" if $result->{status} ne 'OK';
1231
1232 my $publicid = $result->{publicid} = substr(lc($result->{otp}), 0, 12);
1233
1234 my $found;
1235 foreach my $k (PVE::Tools::split_list($keys)) {
1236 if ($k eq $publicid) {
1237 $found = 1;
1238 last;
1239 }
1240 }
1241
1242 die "yubico auth failed: key does not belong to user\n" if !$found;
1243
1244 return $result;
1245 }
1246
1247 sub oath_verify_otp {
1248 my ($otp, $keys, $step, $digits) = @_;
1249
1250 die "oath: missing password\n" if !defined($otp);
1251 die "oath: no associated oath keys\n" if $keys =~ m/^\s+$/;
1252
1253 $step = 30 if !$step;
1254 $digits = 6 if !$digits;
1255
1256 my $found;
1257
1258 my $parser = sub {
1259 my $line = shift;
1260
1261 if ($line =~ m/^\d{6}$/) {
1262 $found = 1 if $otp eq $line;
1263 }
1264 };
1265
1266 foreach my $k (PVE::Tools::split_list($keys)) {
1267 # Note: we generate 3 values to allow small time drift
1268 my $now = localtime(time() - $step);
1269 my $cmd = ['oathtool', '--totp', '--digits', $digits, '-N', $now, '-s', $step, '-w', '2', '-b', $k];
1270 eval { run_command($cmd, outfunc => $parser, errfunc => sub {}); };
1271 last if $found;
1272 }
1273
1274 die "oath auth failed\n" if !$found;
1275 }
1276
1277 1;