bump version to 4.0-22
[pve-access-control.git] / PVE / AccessControl.pm
CommitLineData
2c3a6c0a
DM
1package PVE::AccessControl;
2
3use strict;
7c410d63 4use warnings;
2c3a6c0a
DM
5use Encode;
6use Crypt::OpenSSL::Random;
7use Crypt::OpenSSL::RSA;
cee5583b 8use Net::SSLeay;
25167526 9use Net::IP;
2c3a6c0a 10use MIME::Base64;
03e2a71e 11use MIME::Base32; #libmime-base32-perl
2c3a6c0a 12use Digest::SHA;
ab652a80
DM
13use URI::Escape;
14use LWP::UserAgent;
2c3a6c0a
DM
15use PVE::Tools qw(run_command lock_file file_get_contents split_list safe_print);
16use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
17use PVE::JSONSchema;
5bb4e06a
DM
18
19use PVE::Auth::Plugin;
20use PVE::Auth::AD;
21use PVE::Auth::LDAP;
22use PVE::Auth::PVE;
23use PVE::Auth::PAM;
2c3a6c0a
DM
24
25use Data::Dumper; # fixme: remove
26
5bb4e06a
DM
27# load and initialize all plugins
28
29PVE::Auth::AD->register();
30PVE::Auth::LDAP->register();
31PVE::Auth::PVE->register();
32PVE::Auth::PAM->register();
33PVE::Auth::Plugin->init();
34
2c3a6c0a
DM
35# $authdir must be writable by root only!
36my $confdir = "/etc/pve";
37my $authdir = "$confdir/priv";
38my $authprivkeyfn = "$authdir/authkey.key";
39my $authpubkeyfn = "$confdir/authkey.pub";
2c3a6c0a
DM
40my $pve_www_key_fn = "$confdir/pve-www.key";
41
42my $ticket_lifetime = 3600*2; # 2 hours
43
44Crypt::OpenSSL::RSA->import_random_seed();
45
66931b11
DM
46cfs_register_file('user.cfg',
47 \&parse_user_config,
2c3a6c0a
DM
48 \&write_user_config);
49
2c3a6c0a 50
5bb4e06a
DM
51sub verify_username {
52 PVE::Auth::Plugin::verify_username(@_);
2c3a6c0a
DM
53}
54
5bb4e06a
DM
55sub pve_verify_realm {
56 PVE::Auth::Plugin::pve_verify_realm(@_);
2c3a6c0a
DM
57}
58
5bb4e06a 59sub lock_user_config {
2c3a6c0a
DM
60 my ($code, $errmsg) = @_;
61
5bb4e06a
DM
62 cfs_lock_file("user.cfg", undef, $code);
63 if (my $err = $@) {
2c3a6c0a
DM
64 $errmsg ? die "$errmsg: $err" : die $err;
65 }
66}
67
68my $pve_auth_pub_key;
66931b11 69sub get_pubkey {
2c3a6c0a
DM
70
71 return $pve_auth_pub_key if $pve_auth_pub_key;
72
66931b11 73 my $input = PVE::Tools::file_get_contents($authpubkeyfn);
2c3a6c0a
DM
74
75 $pve_auth_pub_key = Crypt::OpenSSL::RSA->new_public_key($input);
76
77 return $pve_auth_pub_key;
78}
79
80my $csrf_prevention_secret;
81my $get_csrfr_secret = sub {
82 if (!$csrf_prevention_secret) {
66931b11 83 my $input = PVE::Tools::file_get_contents($pve_www_key_fn);
2c3a6c0a
DM
84 $csrf_prevention_secret = Digest::SHA::sha1_base64($input);
85 }
86 return $csrf_prevention_secret;
87};
88
89sub assemble_csrf_prevention_token {
90 my ($username) = @_;
91
92 my $timestamp = sprintf("%08X", time());
93
94 my $digest = Digest::SHA::sha1_base64("$timestamp:$username", &$get_csrfr_secret());
95
66931b11 96 return "$timestamp:$digest";
2c3a6c0a
DM
97}
98
99sub verify_csrf_prevention_token {
100 my ($username, $token, $noerr) = @_;
101
102 if ($token =~ m/^([A-Z0-9]{8}):(\S+)$/) {
103 my $sig = $2;
104 my $timestamp = $1;
105 my $ttime = hex($timestamp);
106
107 my $digest = Digest::SHA::sha1_base64("$timestamp:$username", &$get_csrfr_secret());
108
109 my $age = time() - $ttime;
110 return if ($digest eq $sig) && ($age > -300) && ($age < $ticket_lifetime);
111 }
112
113 die "Permission denied - invalid csrf token\n" if !$noerr;
114
115 return undef;
116}
117
118my $pve_auth_priv_key;
119sub get_privkey {
120
121 return $pve_auth_priv_key if $pve_auth_priv_key;
122
66931b11 123 my $input = PVE::Tools::file_get_contents($authprivkeyfn);
2c3a6c0a
DM
124
125 $pve_auth_priv_key = Crypt::OpenSSL::RSA->new_private_key($input);
126
127 return $pve_auth_priv_key;
128}
129
130sub assemble_ticket {
131 my ($username) = @_;
132
133 my $rsa_priv = get_privkey();
134
135 my $timestamp = sprintf("%08X", time());
136
137 my $plain = "PVE:$username:$timestamp";
138
139 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($plain), '');
140
141 return $ticket;
142}
143
144sub verify_ticket {
145 my ($ticket, $noerr) = @_;
146
adf8d771 147 if ($ticket && $ticket =~ m/^(PVE:\S+)::([^:\s]+)$/) {
2c3a6c0a
DM
148 my $plain = $1;
149 my $sig = $2;
150
151 my $rsa_pub = get_pubkey();
152 if ($rsa_pub->verify($plain, decode_base64($sig))) {
533219a1 153 if ($plain =~ m/^PVE:(\S+):([A-Z0-9]{8})$/) {
2c3a6c0a 154 my $username = $1;
533219a1 155 my $timestamp = $2;
2c3a6c0a
DM
156 my $ttime = hex($timestamp);
157
158 my $age = time() - $ttime;
159
5bb4e06a 160 if (PVE::Auth::Plugin::verify_username($username, 1) &&
533219a1 161 ($age > -300) && ($age < $ticket_lifetime)) {
2c3a6c0a
DM
162 return wantarray ? ($username, $age) : $username;
163 }
164 }
165 }
166 }
167
168 die "permission denied - invalid ticket\n" if !$noerr;
169
170 return undef;
171}
172
adf8d771
DM
173# VNC tickets
174# - they do not contain the username in plain text
175# - they are restricted to a specific resource path (example: '/vms/100')
176sub assemble_vnc_ticket {
177 my ($username, $path) = @_;
178
179 my $rsa_priv = get_privkey();
180
181 my $timestamp = sprintf("%08X", time());
182
183 my $plain = "PVEVNC:$timestamp";
184
185 $path = normalize_path($path);
186
187 my $full = "$plain:$username:$path";
188
189 my $ticket = $plain . "::" . encode_base64($rsa_priv->sign($full), '');
190
191 return $ticket;
192}
193
194sub verify_vnc_ticket {
195 my ($ticket, $username, $path, $noerr) = @_;
196
197 if ($ticket && $ticket =~ m/^(PVEVNC:\S+)::([^:\s]+)$/) {
198 my $plain = $1;
199 my $sig = $2;
200 my $full = "$plain:$username:$path";
201
202 my $rsa_pub = get_pubkey();
203 # Note: sign only match if $username and $path is correct
204 if ($rsa_pub->verify($full, decode_base64($sig))) {
205 if ($plain =~ m/^PVEVNC:([A-Z0-9]{8})$/) {
206 my $ttime = hex($1);
207
208 my $age = time() - $ttime;
209
210 if (($age > -20) && ($age < 40)) {
211 return 1;
212 }
213 }
214 }
215 }
216
217 die "permission denied - invalid vnc ticket\n" if !$noerr;
218
219 return undef;
220}
221
23b35225 222sub assemble_spice_ticket {
bf3e6d31 223 my ($username, $vmid, $node) = @_;
23b35225
AD
224
225 my $rsa_priv = get_privkey();
226
bf3e6d31 227 my $timestamp = sprintf("%08x", time());
23b35225 228
bf3e6d31 229 my $randomstr = "PVESPICE:$timestamp:$vmid:$node:" . rand(10);
23b35225 230
1075c589 231 # this should be used as one-time password
bf3e6d31
DM
232 # max length is 60 chars (spice limit)
233 # we pass this to qemu set_pasword and limit lifetime there
234 # keep this secret
235 my $ticket = Digest::SHA::sha1_hex($rsa_priv->sign($randomstr));
23b35225 236
bf3e6d31 237 # Note: spice proxy connects with HTTP, so $proxyticket is exposed to public
1075c589 238 # we use a signature/timestamp to make sure nobody can fake such a ticket
bf3e6d31
DM
239 # an attacker can use this $proxyticket, but he will fail because $ticket is
240 # private.
1075c589 241 # The proxy needs to be able to extract/verify the ticket
bf3e6d31 242 # Note: data needs to be lower case only, because virt-viewer needs that
1075c589 243 # Note: RSA signature are too long (>=256 charaters) and make problems with remote-viewer
3f62bdbe
DM
244
245 my $secret = &$get_csrfr_secret();
cb442f35 246 my $plain = "pvespiceproxy:$timestamp:$vmid:" . lc($node);
3f62bdbe
DM
247
248 # produces 40 characters
249 my $sig = unpack("H*", Digest::SHA::sha1($plain, &$get_csrfr_secret()));
250
251 #my $sig = unpack("H*", $rsa_priv->sign($plain)); # this produce too long strings (512)
23b35225 252
bf3e6d31 253 my $proxyticket = $plain . "::" . $sig;
83d1f13e 254
bf3e6d31
DM
255 return ($ticket, $proxyticket);
256}
257
258sub verify_spice_connect_url {
259 my ($connect_str) = @_;
260
261 # Note: we pass the spice ticket as 'host', so the
262 # spice viewer connects with "$ticket:$port"
263
264 return undef if !$connect_str;
265
3f62bdbe 266 if ($connect_str =~m/^pvespiceproxy:([a-z0-9]{8}):(\d+):(\S+)::([a-z0-9]{40}):(\d+)$/) {
bf3e6d31
DM
267 my ($timestamp, $vmid, $node, $hexsig, $port) = ($1, $2, $3, $4, $5, $6);
268 my $ttime = hex($timestamp);
269 my $age = time() - $ttime;
270
271 # use very limited lifetime - is this enough?
272 return undef if !(($age > -20) && ($age < 40));
273
bf3e6d31 274 my $plain = "pvespiceproxy:$timestamp:$vmid:$node";
3f62bdbe 275 my $sig = unpack("H*", Digest::SHA::sha1($plain, &$get_csrfr_secret()));
bf3e6d31 276
3f62bdbe 277 if ($sig eq $hexsig) {
bf3e6d31 278 return ($vmid, $node, $port);
66931b11 279 }
bf3e6d31
DM
280 }
281
282 return undef;
23b35225
AD
283}
284
cee5583b
DM
285sub read_x509_subject_spice {
286 my ($filename) = @_;
287
288 # read x509 subject
289 my $bio = Net::SSLeay::BIO_new_file($filename, 'r');
44903703
FG
290 die "Could not open $filename using OpenSSL\n"
291 if !$bio;
292
cee5583b
DM
293 my $x509 = Net::SSLeay::PEM_read_bio_X509($bio);
294 Net::SSLeay::BIO_free($bio);
44903703
FG
295
296 die "Could not parse X509 certificate in $filename\n"
297 if !$x509;
298
cee5583b
DM
299 my $nameobj = Net::SSLeay::X509_get_subject_name($x509);
300 my $subject = Net::SSLeay::X509_NAME_oneline($nameobj);
301 Net::SSLeay::X509_free($x509);
66931b11 302
cee5583b
DM
303 # remote-viewer wants comma as seperator (not '/')
304 $subject =~ s!^/!!;
305 $subject =~ s!/(\w+=)!,$1!g;
306
307 return $subject;
308}
309
310# helper to generate SPICE remote-viewer configuration
311sub remote_viewer_config {
312 my ($authuser, $vmid, $node, $proxy, $title, $port) = @_;
313
314 if (!$proxy) {
315 my $host = `hostname -f` || PVE::INotify::nodename();
316 chomp $host;
317 $proxy = $host;
318 }
319
320 my ($ticket, $proxyticket) = assemble_spice_ticket($authuser, $vmid, $node);
321
322 my $filename = "/etc/pve/local/pve-ssl.pem";
323 my $subject = read_x509_subject_spice($filename);
324
325 my $cacert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192);
326 $cacert =~ s/\n/\\n/g;
63691fc6 327
25167526 328 $proxy = "[$proxy]" if Net::IP::ip_is_ipv6($proxy);
cee5583b 329 my $config = {
63691fc6
DM
330 'secure-attention' => "Ctrl+Alt+Ins",
331 'toggle-fullscreen' => "Shift+F11",
332 'release-cursor' => "Ctrl+Alt+R",
cee5583b
DM
333 type => 'spice',
334 title => $title,
1075c589 335 host => $proxyticket, # this breaks tls hostname verification, so we need to use 'host-subject'
cee5583b
DM
336 proxy => "http://$proxy:3128",
337 'tls-port' => $port,
338 'host-subject' => $subject,
339 ca => $cacert,
340 password => $ticket,
341 'delete-this-file' => 1,
342 };
343
344 return ($ticket, $proxyticket, $config);
345}
346
37d45deb 347sub check_user_exist {
7070c1ae 348 my ($usercfg, $username, $noerr) = @_;
2c3a6c0a 349
5bb4e06a 350 $username = PVE::Auth::Plugin::verify_username($username, $noerr);
2c3a6c0a 351 return undef if !$username;
66931b11 352
37d45deb
DM
353 return $usercfg->{users}->{$username} if $usercfg && $usercfg->{users}->{$username};
354
355 die "no such user ('$username')\n" if !$noerr;
66931b11 356
37d45deb
DM
357 return undef;
358}
359
360sub check_user_enabled {
361 my ($usercfg, $username, $noerr) = @_;
362
363 my $data = check_user_exist($usercfg, $username, $noerr);
364 return undef if !$data;
365
366 return 1 if $data->{enable};
2c3a6c0a 367
37d45deb 368 die "user '$username' is disabled\n" if !$noerr;
66931b11 369
7070c1ae 370 return undef;
2c3a6c0a
DM
371}
372
96f8ebd6
DM
373sub verify_one_time_pw {
374 my ($usercfg, $username, $tfa_cfg, $otp) = @_;
375
376 my $type = $tfa_cfg->{type};
377
1075c589 378 die "missing one time password for two-factor authentication '$type'\n" if !$otp;
96f8ebd6
DM
379
380 # fixme: proxy support?
381 my $proxy;
382
383 if ($type eq 'yubico') {
384 my $keys = $usercfg->{users}->{$username}->{keys};
385 yubico_verify_otp($otp, $keys, $tfa_cfg->{url}, $tfa_cfg->{id}, $tfa_cfg->{key}, $proxy);
1abc2c0a
DM
386 } elsif ($type eq 'oath') {
387 my $keys = $usercfg->{users}->{$username}->{keys};
86cd805b 388 oath_verify_otp($otp, $keys, $tfa_cfg->{step}, $tfa_cfg->{digits});
96f8ebd6
DM
389 } else {
390 die "unknown tfa type '$type'\n";
391 }
96f8ebd6
DM
392}
393
2c3a6c0a 394# password should be utf8 encoded
1075c589 395# Note: some plugins delay/sleep if auth fails
2c3a6c0a 396sub authenticate_user {
96f8ebd6 397 my ($username, $password, $otp) = @_;
2c3a6c0a
DM
398
399 die "no username specified\n" if !$username;
66931b11 400
5bb4e06a 401 my ($ruid, $realm);
2c3a6c0a 402
5bb4e06a 403 ($username, $ruid, $realm) = PVE::Auth::Plugin::verify_username($username);
2c3a6c0a
DM
404
405 my $usercfg = cfs_read_file('user.cfg');
406
6126ab75 407 check_user_enabled($usercfg, $username);
2c3a6c0a
DM
408
409 my $ctime = time();
410 my $expire = $usercfg->{users}->{$username}->{expire};
411
6126ab75 412 die "account expired\n" if $expire && ($expire < $ctime);
2c3a6c0a 413
5bb4e06a 414 my $domain_cfg = cfs_read_file('domains.cfg');
2c3a6c0a 415
6126ab75
DM
416 my $cfg = $domain_cfg->{ids}->{$realm};
417 die "auth domain '$realm' does not exists\n" if !$cfg;
418 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
419 $plugin->authenticate_user($cfg, $realm, $ruid, $password);
2c3a6c0a 420
96f8ebd6
DM
421 if ($cfg->{tfa}) {
422 my $tfa_cfg = PVE::Auth::Plugin::parse_tfa_config($cfg->{tfa});
423 verify_one_time_pw($usercfg, $username, $tfa_cfg, $otp);
424 }
425
5bb4e06a 426 return $username;
2c3a6c0a
DM
427}
428
429sub domain_set_password {
5bb4e06a 430 my ($realm, $username, $password) = @_;
2c3a6c0a
DM
431
432 die "no auth domain specified" if !$realm;
433
5bb4e06a
DM
434 my $domain_cfg = cfs_read_file('domains.cfg');
435
436 my $cfg = $domain_cfg->{ids}->{$realm};
1075c589 437 die "auth domain '$realm' does not exist\n" if !$cfg;
5bb4e06a
DM
438 my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
439 $plugin->store_password($cfg, $realm, $username, $password);
2c3a6c0a
DM
440}
441
442sub add_user_group {
2c3a6c0a 443 my ($username, $usercfg, $group) = @_;
66931b11 444
2c3a6c0a
DM
445 $usercfg->{users}->{$username}->{groups}->{$group} = 1;
446 $usercfg->{groups}->{$group}->{users}->{$username} = 1;
447}
448
449sub delete_user_group {
2c3a6c0a 450 my ($username, $usercfg) = @_;
66931b11 451
2c3a6c0a
DM
452 foreach my $group (keys %{$usercfg->{groups}}) {
453
66931b11 454 delete ($usercfg->{groups}->{$group}->{users}->{$username})
2c3a6c0a
DM
455 if $usercfg->{groups}->{$group}->{users}->{$username};
456 }
457}
458
459sub delete_user_acl {
2c3a6c0a
DM
460 my ($username, $usercfg) = @_;
461
462 foreach my $acl (keys %{$usercfg->{acl}}) {
463
66931b11 464 delete ($usercfg->{acl}->{$acl}->{users}->{$username})
2c3a6c0a
DM
465 if $usercfg->{acl}->{$acl}->{users}->{$username};
466 }
2c3a6c0a 467}
39c85db8 468
2c3a6c0a 469sub delete_group_acl {
2c3a6c0a
DM
470 my ($group, $usercfg) = @_;
471
472 foreach my $acl (keys %{$usercfg->{acl}}) {
473
66931b11 474 delete ($usercfg->{acl}->{$acl}->{groups}->{$group})
2c3a6c0a
DM
475 if $usercfg->{acl}->{$acl}->{groups}->{$group};
476 }
39c85db8
DM
477}
478
479sub delete_pool_acl {
39c85db8 480 my ($pool, $usercfg) = @_;
2c3a6c0a 481
39c85db8
DM
482 my $path = "/pool/$pool";
483
3b4a3f94 484 delete ($usercfg->{acl}->{$path})
2c3a6c0a
DM
485}
486
487# we automatically create some predefined roles by splitting privs
488# into 3 groups (per category)
489# root: only root is allowed to do that
490# admin: an administrator can to that
1075c589 491# user: a normal user/customer can to that
2c3a6c0a
DM
492my $privgroups = {
493 VM => {
494 root => [],
66931b11
DM
495 admin => [
496 'VM.Config.Disk',
497 'VM.Config.CPU',
498 'VM.Config.Memory',
499 'VM.Config.Network',
c0fead8c 500 'VM.Config.HWType',
66931b11
DM
501 'VM.Config.Options', # covers all other things
502 'VM.Allocate',
503 'VM.Clone',
2c3a6c0a 504 'VM.Migrate',
66931b11
DM
505 'VM.Monitor',
506 'VM.Snapshot',
2c3a6c0a
DM
507 ],
508 user => [
cc7bdf33 509 'VM.Config.CDROM', # change CDROM media
66931b11 510 'VM.Console',
68d5a86d 511 'VM.Backup',
2c3a6c0a
DM
512 'VM.PowerMgmt',
513 ],
66931b11 514 audit => [
82b63965 515 'VM.Audit',
2c3a6c0a
DM
516 ],
517 },
518 Sys => {
519 root => [
66931b11 520 'Sys.PowerMgmt',
37d45deb 521 'Sys.Modify', # edit/change node settings
2c3a6c0a
DM
522 ],
523 admin => [
2e376c58 524 'Permissions.Modify',
66931b11 525 'Sys.Console',
2c3a6c0a
DM
526 'Sys.Syslog',
527 ],
528 user => [],
529 audit => [
530 'Sys.Audit',
531 ],
532 },
533 Datastore => {
2e376c58 534 root => [],
19f60b5e
DM
535 admin => [
536 'Datastore.Allocate',
373cb383 537 'Datastore.AllocateTemplate',
19f60b5e 538 ],
2c3a6c0a
DM
539 user => [
540 'Datastore.AllocateSpace',
541 ],
542 audit => [
543 'Datastore.Audit',
544 ],
545 },
12683df7 546 User => {
82b63965
DM
547 root => [
548 'Realm.Allocate',
549 ],
12683df7
DM
550 admin => [
551 'User.Modify',
82b63965 552 'Group.Allocate', # edit/change group settings
66931b11 553 'Realm.AllocateUser',
19f60b5e 554 ],
12683df7
DM
555 user => [],
556 audit => [],
557 },
dee1c882
DM
558 Pool => {
559 root => [],
560 admin => [
561 'Pool.Allocate', # create/delete pools
562 ],
563 user => [],
564 audit => [],
565 },
2c3a6c0a
DM
566};
567
568my $valid_privs = {};
569
570my $special_roles = {
1075c589
FG
571 'NoAccess' => {}, # no privileges
572 'Administrator' => $valid_privs, # all privileges
2c3a6c0a
DM
573};
574
575sub create_roles {
576
577 foreach my $cat (keys %$privgroups) {
578 my $cd = $privgroups->{$cat};
66931b11 579 foreach my $p (@{$cd->{root}}, @{$cd->{admin}},
2c3a6c0a
DM
580 @{$cd->{user}}, @{$cd->{audit}}) {
581 $valid_privs->{$p} = 1;
582 }
583 foreach my $p (@{$cd->{admin}}, @{$cd->{user}}, @{$cd->{audit}}) {
584
585 $special_roles->{"PVE${cat}Admin"}->{$p} = 1;
586 $special_roles->{"PVEAdmin"}->{$p} = 1;
587 }
588 if (scalar(@{$cd->{user}})) {
589 foreach my $p (@{$cd->{user}}, @{$cd->{audit}}) {
590 $special_roles->{"PVE${cat}User"}->{$p} = 1;
591 }
592 }
593 foreach my $p (@{$cd->{audit}}) {
594 $special_roles->{"PVEAuditor"}->{$p} = 1;
595 }
596 }
ff4b2235 597
7b395f99 598 $special_roles->{"PVETemplateUser"} = { 'VM.Clone' => 1, 'VM.Audit' => 1 };
2c3a6c0a
DM
599};
600
601create_roles();
602
2c3a6c0a
DM
603sub add_role_privs {
604 my ($role, $usercfg, $privs) = @_;
605
606 return if !$privs;
607
608 die "role '$role' does not exist\n" if !$usercfg->{roles}->{$role};
609
610 foreach my $priv (split_list($privs)) {
611 if (defined ($valid_privs->{$priv})) {
612 $usercfg->{roles}->{$role}->{$priv} = 1;
613 } else {
1075c589 614 die "invalid privilege '$priv'\n";
66931b11
DM
615 }
616 }
2c3a6c0a
DM
617}
618
619sub normalize_path {
620 my $path = shift;
621
4bc17477 622 $path =~ s|/+|/|g;
2c3a6c0a
DM
623
624 $path =~ s|/$||;
625
626 $path = '/' if !$path;
627
4bc17477
DM
628 $path = "/$path" if $path !~ m|^/|;
629
e4f8fc2e 630 return undef if $path !~ m|^[[:alnum:]\.\-\_\/]+$|;
2c3a6c0a
DM
631
632 return $path;
66931b11 633}
2c3a6c0a 634
2c3a6c0a
DM
635
636PVE::JSONSchema::register_format('pve-groupid', \&verify_groupname);
637sub verify_groupname {
638 my ($groupname, $noerr) = @_;
639
640 if ($groupname !~ m/^[A-Za-z0-9\.\-_]+$/) {
641
642 die "group name '$groupname' contains invalid characters\n" if !$noerr;
643
644 return undef;
645 }
66931b11 646
2c3a6c0a
DM
647 return $groupname;
648}
649
650PVE::JSONSchema::register_format('pve-roleid', \&verify_rolename);
651sub verify_rolename {
652 my ($rolename, $noerr) = @_;
653
654 if ($rolename !~ m/^[A-Za-z0-9\.\-_]+$/) {
655
656 die "role name '$rolename' contains invalid characters\n" if !$noerr;
657
658 return undef;
659 }
66931b11 660
2c3a6c0a
DM
661 return $rolename;
662}
663
39c85db8
DM
664PVE::JSONSchema::register_format('pve-poolid', \&verify_groupname);
665sub verify_poolname {
666 my ($poolname, $noerr) = @_;
667
668 if ($poolname !~ m/^[A-Za-z0-9\.\-_]+$/) {
669
670 die "pool name '$poolname' contains invalid characters\n" if !$noerr;
671
672 return undef;
673 }
66931b11 674
39c85db8
DM
675 return $poolname;
676}
677
2c3a6c0a
DM
678PVE::JSONSchema::register_format('pve-priv', \&verify_privname);
679sub verify_privname {
680 my ($priv, $noerr) = @_;
681
682 if (!$valid_privs->{$priv}) {
1075c589 683 die "invalid privilege '$priv'\n" if !$noerr;
2c3a6c0a
DM
684
685 return undef;
686 }
66931b11 687
2c3a6c0a
DM
688 return $priv;
689}
690
691sub userconfig_force_defaults {
692 my ($cfg) = @_;
693
694 foreach my $r (keys %$special_roles) {
695 $cfg->{roles}->{$r} = $special_roles->{$r};
696 }
697
7279f31c
WL
698 # add root user if not exists
699 if (!$cfg->{users}->{'root@pam'}) {
66931b11 700 $cfg->{users}->{'root@pam'}->{enable} = 1;
7279f31c 701 }
2c3a6c0a
DM
702}
703
704sub parse_user_config {
705 my ($filename, $raw) = @_;
706
707 my $cfg = {};
708
709 userconfig_force_defaults($cfg);
710
d6eb6621 711 $raw = '' if !defined($raw);
62af314a 712 while ($raw =~ /^\s*(.+?)\s*$/gm) {
2c3a6c0a 713 my $line = $1;
2c3a6c0a
DM
714 my @data;
715
716 foreach my $d (split (/:/, $line)) {
66931b11 717 $d =~ s/^\s+//;
2c3a6c0a
DM
718 $d =~ s/\s+$//;
719 push @data, $d
720 }
721
722 my $et = shift @data;
723
724 if ($et eq 'user') {
96f8ebd6 725 my ($user, $enable, $expire, $firstname, $lastname, $email, $comment, $keys) = @data;
2c3a6c0a 726
5bb4e06a 727 my (undef, undef, $realm) = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
728 if (!$realm) {
729 warn "user config - ignore user '$user' - invalid user name\n";
730 next;
731 }
732
733 $enable = $enable ? 1 : 0;
734
735 $expire = 0 if !$expire;
736
737 if ($expire !~ m/^\d+$/) {
738 warn "user config - ignore user '$user' - (illegal characters in expire '$expire')\n";
739 next;
740 }
741 $expire = int($expire);
742
743 #if (!verify_groupname ($group, 1)) {
744 # warn "user config - ignore user '$user' - invalid characters in group name\n";
745 # next;
746 #}
747
748 $cfg->{users}->{$user} = {
749 enable => $enable,
750 # group => $group,
751 };
752 $cfg->{users}->{$user}->{firstname} = PVE::Tools::decode_text($firstname) if $firstname;
753 $cfg->{users}->{$user}->{lastname} = PVE::Tools::decode_text($lastname) if $lastname;
754 $cfg->{users}->{$user}->{email} = $email;
755 $cfg->{users}->{$user}->{comment} = PVE::Tools::decode_text($comment) if $comment;
756 $cfg->{users}->{$user}->{expire} = $expire;
1abc2c0a 757 # keys: allowed yubico key ids or oath secrets (base32 encoded)
66931b11 758 $cfg->{users}->{$user}->{keys} = $keys if $keys;
2c3a6c0a
DM
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
5bb4e06a 778 if (!PVE::Auth::Plugin::verify_username($user, 1)) {
2c3a6c0a
DM
779 warn "user config - ignore invalid group member '$user'\n";
780 next;
781 }
782
66931b11 783 if ($cfg->{users}->{$user}) { # user exists
2c3a6c0a
DM
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;
66931b11 793
2c3a6c0a
DM
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";
66931b11 807 }
2c3a6c0a 808 }
66931b11 809
2c3a6c0a
DM
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)) {
66931b11 815
2c3a6c0a
DM
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)) {
9b217226 822 if ($ug =~ m/^@(\S+)$/) {
2c3a6c0a 823 my $group = $1;
66931b11 824 if ($cfg->{groups}->{$group}) { # group exists
2c3a6c0a
DM
825 $cfg->{acl}->{$path}->{groups}->{$group}->{$role} = $propagate;
826 } else {
827 warn "user config - ignore invalid acl group '$group'\n";
828 }
5bb4e06a 829 } elsif (PVE::Auth::Plugin::verify_username($ug, 1)) {
66931b11 830 if ($cfg->{users}->{$ug}) { # user exists
2c3a6c0a
DM
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 }
4bc17477 843 } elsif ($et eq 'pool') {
39c85db8 844 my ($pool, $comment, $vmlist, $storelist) = @data;
4bc17477 845
39c85db8
DM
846 if (!verify_poolname($pool, 1)) {
847 warn "user config - ignore pool '$pool' - invalid characters in pool name\n";
848 next;
849 }
4bc17477 850
39c85db8
DM
851 # make sure to add the pool (even if there are no members)
852 $cfg->{pools}->{$pool} = { vms => {}, storage => {} } if !$cfg->{pools}->{$pool};
4bc17477 853
39c85db8 854 $cfg->{pools}->{$pool}->{comment} = PVE::Tools::decode_text($comment) if $comment;
4bc17477 855
39c85db8
DM
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;
4bc17477 860 }
39c85db8 861 $vmid = int($vmid);
4bc17477 862
39c85db8
DM
863 if ($cfg->{vms}->{$vmid}) {
864 warn "user config - ignore duplicate vmid '$vmid' in pool '$pool'\n";
865 next;
4bc17477
DM
866 }
867
39c85db8 868 $cfg->{pools}->{$pool}->{vms}->{$vmid} = 1;
66931b11 869
39c85db8
DM
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;
4bc17477 880 }
2c3a6c0a
DM
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
2c3a6c0a
DM
891sub write_user_config {
892 my ($filename, $cfg) = @_;
893
894 my $data = '';
895
896 foreach my $user (keys %{$cfg->{users}}) {
2c3a6c0a
DM
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}) : '';
5eabc984 902 my $expire = int($d->{expire} || 0);
2c3a6c0a 903 my $enable = $d->{enable} ? 1 : 0;
96f8ebd6
DM
904 my $keys = $d->{keys} ? $d->{keys} : '';
905 $data .= "user:$user:$enable:$expire:$firstname:$lastname:$email:$comment:$keys:\n";
2c3a6c0a
DM
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}});
66931b11 913 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
2c3a6c0a
DM
914 $data .= "group:$group:$list:$comment:\n";
915 }
916
917 $data .= "\n";
918
39c85db8
DM
919 foreach my $pool (keys %{$cfg->{pools}}) {
920 my $d = $cfg->{pools}->{$pool};
4bc17477
DM
921 my $vmlist = join (',', keys %{$d->{vms}});
922 my $storelist = join (',', keys %{$d->{storage}});
66931b11 923 my $comment = $d->{comment} ? PVE::Tools::encode_text($d->{comment}) : '';
39c85db8 924 $data .= "pool:$pool:$comment:$vmlist:$storelist:\n";
4bc17477
DM
925 }
926
927 $data .= "\n";
928
2c3a6c0a
DM
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}}) {
1075c589 962 # no need to save, because root is always 'Administrator'
66931b11 963 next if $user eq 'root@pam';
2c3a6c0a
DM
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
994sub roles {
995 my ($cfg, $user, $path) = @_;
996
66931b11 997 # NOTE: we do not consider pools here.
4bc17477
DM
998 # You need to use $rpcenv->roles() instead if you want that.
999
2c3a6c0a
DM
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 }
2c3a6c0a
DM
1048 }
1049
4bc17477
DM
1050 return ('NoAccess') if defined ($perm->{NoAccess});
1051 #return () if defined ($perm->{NoAccess});
66931b11 1052
2c3a6c0a
DM
1053 #print "permission $user $path = " . Dumper ($perm);
1054
4bc17477 1055 my @ra = keys %$perm;
2c3a6c0a
DM
1056
1057 #print "roles $user $path = " . join (',', @ra) . "\n";
1058
1059 return @ra;
1060}
66931b11 1061
2c3a6c0a
DM
1062sub permission {
1063 my ($cfg, $user, $path) = @_;
1064
5bb4e06a 1065 $user = PVE::Auth::Plugin::verify_username($user, 1);
2c3a6c0a
DM
1066 return {} if !$user;
1067
1068 my @ra = roles($cfg, $user, $path);
66931b11 1069
2c3a6c0a
DM
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
1085sub 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
3b4a3f94
AG
1099sub remove_vm_access {
1100 my ($vmid) = @_;
1101 my $delVMaccessFn = sub {
1102 my $usercfg = cfs_read_file("user.cfg");
57a70473 1103 my $modified;
3b4a3f94 1104
57a70473
DM
1105 if (my $acl = $usercfg->{acl}->{"/vms/$vmid"}) {
1106 delete $usercfg->{acl}->{"/vms/$vmid"};
1107 $modified = 1;
3b4a3f94
AG
1108 }
1109 if (my $pool = $usercfg->{vms}->{$vmid}) {
1110 if (my $data = $usercfg->{pools}->{$pool}) {
1111 delete $data->{vms}->{$vmid};
1112 delete $usercfg->{vms}->{$vmid};
57a70473 1113 $modified = 1;
3b4a3f94
AG
1114 }
1115 }
57a70473 1116 cfs_write_file("user.cfg", $usercfg) if $modified;
3b4a3f94
AG
1117 };
1118
1119 lock_user_config($delVMaccessFn, "access permissions cleanup for VM $vmid failed");
1120}
1121
60844761
AG
1122sub remove_storage_access {
1123 my ($storeid) = @_;
1124
1125 my $deleteStorageAccessFn = sub {
1126 my $usercfg = cfs_read_file("user.cfg");
1127 my $modified;
1128
1129 if (my $storage = $usercfg->{acl}->{"/storage/$storeid"}) {
1130 delete $usercfg->{acl}->{"/storage/$storeid"};
1131 $modified = 1;
1132 }
1133 foreach my $pool (keys %{$usercfg->{pools}}) {
1134 delete $usercfg->{pools}->{$pool}->{storage}->{$storeid};
1135 $modified = 1;
1136 }
1137 cfs_write_file("user.cfg", $usercfg) if $modified;
1138 };
1139
1140 lock_user_config($deleteStorageAccessFn,
1141 "access permissions cleanup for storage $storeid failed");
1142}
1143
018ae3a9
DM
1144sub add_vm_to_pool {
1145 my ($vmid, $pool) = @_;
1146
1147 my $addVMtoPoolFn = sub {
1148 my $usercfg = cfs_read_file("user.cfg");
1149 if (my $data = $usercfg->{pools}->{$pool}) {
1150 $data->{vms}->{$vmid} = 1;
1151 $usercfg->{vms}->{$vmid} = $pool;
1152 cfs_write_file("user.cfg", $usercfg);
1153 }
1154 };
1155
1156 lock_user_config($addVMtoPoolFn, "can't add VM $vmid to pool '$pool'");
1157}
1158
1159sub remove_vm_from_pool {
1160 my ($vmid) = @_;
66931b11 1161
018ae3a9
DM
1162 my $delVMfromPoolFn = sub {
1163 my $usercfg = cfs_read_file("user.cfg");
1164 if (my $pool = $usercfg->{vms}->{$vmid}) {
1165 if (my $data = $usercfg->{pools}->{$pool}) {
1166 delete $data->{vms}->{$vmid};
1167 delete $usercfg->{vms}->{$vmid};
1168 cfs_write_file("user.cfg", $usercfg);
1169 }
1170 }
1171 };
1172
1173 lock_user_config($delVMfromPoolFn, "pool cleanup for VM $vmid failed");
1174}
1175
9d52f6f2
WB
1176# hotp/totp code
1177
1178sub hotp($$;$) {
1179 my ($binsecret, $number, $digits) = @_;
1180
1181 $digits = 6 if !defined($digits);
1182
1183 my $bincounter = pack('Q>', $number);
1184 my $hmac = Digest::SHA::hmac_sha1($bincounter, $binsecret);
1185
1186 my $offset = unpack('C', substr($hmac,19) & pack('C', 0x0F));
1187 my $part = substr($hmac, $offset, 4);
1188 my $otp = unpack('N', $part);
1189 my $value = ($otp & 0x7fffffff) % (10**$digits);
1190 return sprintf("%0${digits}d", $value);
1191}
1192
ab652a80
DM
1193# experimental code for yubico OTP verification
1194
1195sub yubico_compute_param_sig {
1196 my ($param, $api_key) = @_;
1197
1198 my $paramstr = '';
1199 foreach my $key (sort keys %$param) {
1200 $paramstr .= '&' if $paramstr;
1201 $paramstr .= "$key=$param->{$key}";
1202 }
1203
b10d0e26
WB
1204 # hmac_sha1_base64 does not add '=' padding characters, so we use encode_base64
1205 my $sig = uri_escape(encode_base64(Digest::SHA::hmac_sha1($paramstr, decode_base64($api_key || '')), ''));
ab652a80
DM
1206
1207 return ($paramstr, $sig);
1208}
1209
1210sub yubico_verify_otp {
96f8ebd6
DM
1211 my ($otp, $keys, $url, $api_id, $api_key, $proxy) = @_;
1212
1213 die "yubico: missing password\n" if !defined($otp);
1214 die "yubico: missing API ID\n" if !defined($api_id);
1215 die "yubico: missing API KEY\n" if !defined($api_key);
66931b11 1216 die "yubico: no associated yubico keys\n" if $keys =~ m/^\s+$/;
ab652a80 1217
1075c589 1218 die "yubico: wrong OTP length\n" if (length($otp) < 32) || (length($otp) > 48);
ab652a80 1219
96f8ebd6 1220 $url = 'http://api2.yubico.com/wsapi/2.0/verify' if !defined($url);
66931b11 1221
ab652a80 1222 my $params = {
b10d0e26 1223 nonce => Digest::SHA::hmac_sha1_hex(time(), rand()),
ab652a80
DM
1224 id => $api_id,
1225 otp => uri_escape($otp),
1226 timestamp => 1,
1227 };
1228
1229 my ($paramstr, $sig) = yubico_compute_param_sig($params, $api_key);
1230
1231 $paramstr .= "&h=$sig" if $api_key;
1232
1233 my $req = HTTP::Request->new('GET' => "$url?$paramstr");
1234
ba6c2e66 1235 my $ua = LWP::UserAgent->new(protocols_allowed => ['http', 'https'], timeout => 30);
ab652a80
DM
1236
1237 if ($proxy) {
ba6c2e66 1238 $ua->proxy(['http', 'https'], $proxy);
ab652a80
DM
1239 } else {
1240 $ua->env_proxy;
1241 }
1242
1243 my $response = $ua->request($req);
1244 my $code = $response->code;
1245
1246 if ($code != 200) {
1247 my $msg = $response->message || 'unknown';
1248 die "Invalid response from server: $code $msg\n";
1249 }
1250
1251 my $raw = $response->decoded_content;
1252
1253 my $result = {};
1254 foreach my $kvpair (split(/\n/, $raw)) {
1255 chomp $kvpair;
1256 if($kvpair =~ /^\S+=/) {
1257 my ($k, $v) = split(/=/, $kvpair, 2);
1258 $v =~ s/\s//g;
1259 $result->{$k} = $v;
1260 }
1261 }
1262
1263 my $rsig = $result->{h};
1264 delete $result->{h};
1265
1266 if ($api_key) {
1267 my ($datastr, $vsig) = yubico_compute_param_sig($result, $api_key);
1268 $vsig = uri_unescape($vsig);
96f8ebd6 1269 die "yubico: result signature verification failed\n" if $rsig ne $vsig;
ab652a80
DM
1270 }
1271
96f8ebd6
DM
1272 die "yubico auth failed: $result->{status}\n" if $result->{status} ne 'OK';
1273
1274 my $publicid = $result->{publicid} = substr(lc($result->{otp}), 0, 12);
1275
1276 my $found;
1277 foreach my $k (PVE::Tools::split_list($keys)) {
1278 if ($k eq $publicid) {
1279 $found = 1;
1280 last;
1281 }
1282 }
ab652a80 1283
96f8ebd6 1284 die "yubico auth failed: key does not belong to user\n" if !$found;
ab652a80
DM
1285
1286 return $result;
1287}
1288
1abc2c0a 1289sub oath_verify_otp {
86cd805b 1290 my ($otp, $keys, $step, $digits) = @_;
1abc2c0a
DM
1291
1292 die "oath: missing password\n" if !defined($otp);
66931b11 1293 die "oath: no associated oath keys\n" if $keys =~ m/^\s+$/;
1abc2c0a 1294
86cd805b
DM
1295 $step = 30 if !$step;
1296 $digits = 6 if !$digits;
1abc2c0a
DM
1297
1298 my $found;
1abc2c0a
DM
1299 foreach my $k (PVE::Tools::split_list($keys)) {
1300 # Note: we generate 3 values to allow small time drift
9d52f6f2 1301 my $binkey;
5426494b 1302 if ($k =~ /^[A-Z2-7=]{16}$/) {
9d52f6f2
WB
1303 $binkey = MIME::Base32::decode_rfc3548($k);
1304 } elsif ($k =~ /^[A-Fa-f0-9]{40}$/) {
1305 $binkey = pack('H*', $k);
1306 } else {
1307 die "unrecognized key format, must be hex or base32 encoded\n";
1308 }
1309
1310 # force integer division for time/step
1311 use integer;
1312 my $now = time()/$step - 1;
1313 $found = 1 if $otp eq hotp($binkey, $now+0, $digits);
1314 $found = 1 if $otp eq hotp($binkey, $now+1, $digits);
1315 $found = 1 if $otp eq hotp($binkey, $now+2, $digits);
1abc2c0a
DM
1316 last if $found;
1317 }
1318
1319 die "oath auth failed\n" if !$found;
1320}
1321
3e5bfdf6
DM
1322# bash completion helpers
1323
1324sub complete_username {
1325
1326 my $user_cfg = cfs_read_file('user.cfg');
1327
1328 return [ keys %{$user_cfg->{users}} ];
1329}
1330
1331sub complete_group {
1332
1333 my $user_cfg = cfs_read_file('user.cfg');
1334
1335 return [ keys %{$user_cfg->{groups}} ];
1336}
1337
1338sub complete_realm {
1339
1340 my $domain_cfg = cfs_read_file('domains.cfg');
1341
1342 return [ keys %{$domain_cfg->{ids}} ];
1343}
1344
2c3a6c0a 13451;