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