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