]> git.proxmox.com Git - pve-access-control.git/blobdiff - PVE/API2/AccessControl.pm
add missing 'use PVE::Auth::Plugin'
[pve-access-control.git] / PVE / API2 / AccessControl.pm
index 677592b2b27a794e36344040b068257eae2bcf4b..9d2da8daaa80e1c53528ccd611e49ecd6f436677 100644 (file)
@@ -19,6 +19,9 @@ use PVE::API2::User;
 use PVE::API2::Group;
 use PVE::API2::Role;
 use PVE::API2::ACL;
+use PVE::Auth::Plugin;
+use PVE::OTP;
+use PVE::Tools;
 
 my $u2f_available = 0;
 eval {
@@ -123,23 +126,32 @@ my $verify_auth = sub {
 my $create_ticket = sub {
     my ($rpcenv, $username, $pw_or_ticket, $otp) = @_;
 
-    my ($ticketuser, $u2fdata);
-    if (($ticketuser = PVE::AccessControl::verify_ticket($pw_or_ticket, 1)) &&
-       ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
+    my ($ticketuser, undef, $tfa_info) = PVE::AccessControl::verify_ticket($pw_or_ticket, 1);
+    if (defined($ticketuser) && ($ticketuser eq 'root@pam' || $ticketuser eq $username)) {
+       if (defined($tfa_info)) {
+           die "incomplete ticket\n";
+       }
        # valid ticket. Note: root@pam can create tickets for other users
     } else {
-       ($username, $u2fdata) = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
+       ($username, $tfa_info) = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
     }
 
     my %extra;
     my $ticket_data = $username;
-    if (defined($u2fdata)) {
-       my $u2f = get_u2f_instance($rpcenv, $u2fdata->@{qw(publicKey keyHandle)});
-       my $challenge = $u2f->auth_challenge()
-           or die "failed to get u2f challenge\n";
-       $challenge = decode_json($challenge);
-       $extra{U2FChallenge} = $challenge;
-       $ticket_data = "u2f!$username!$challenge->{challenge}";
+    if (defined($tfa_info)) {
+       $extra{NeedTFA} = 1;
+       if ($tfa_info->{type} eq 'u2f') {
+           my $u2finfo = $tfa_info->{data};
+           my $u2f = get_u2f_instance($rpcenv, $u2finfo->@{qw(publicKey keyHandle)});
+           my $challenge = $u2f->auth_challenge()
+               or die "failed to get u2f challenge\n";
+           $challenge = decode_json($challenge);
+           $extra{U2FChallenge} = $challenge;
+           $ticket_data = "u2f!$username!$challenge->{challenge}";
+       } else {
+           # General half-login / 'missing 2nd factor' ticket:
+           $ticket_data = "tfa!$username";
+       }
     }
 
     my $ticket = PVE::AccessControl::assemble_ticket($ticket_data);
@@ -300,7 +312,7 @@ __PACKAGE__->register_method ({
        }
 
        $res->{cap} = &$compute_api_permission($rpcenv, $username)
-           if !defined($res->{U2FChallenge});
+           if !defined($res->{NeedTFA});
 
        if (PVE::Corosync::check_conf_exists(1)) {
            if ($rpcenv->check($username, '/', ['Sys.Audit'], 1)) {
@@ -418,12 +430,46 @@ sub get_u2f_instance {
     return $u2f;
 }
 
+sub verify_user_tfa_config {
+    my ($type, $tfa_cfg, $value) = @_;
+
+    if (!defined($type)) {
+       die "missing tfa 'type'\n";
+    }
+
+    if ($type ne 'oath') {
+       die "invalid type for custom tfa authentication\n";
+    }
+
+    my $secret = $tfa_cfg->{keys}
+       or die "missing TOTP secret\n";
+    $tfa_cfg = $tfa_cfg->{config};
+    # Copy the hash to verify that we have no unexpected keys without modifying the original hash.
+    $tfa_cfg = {%$tfa_cfg};
+
+    # We can only verify 1 secret but oath_verify_otp allows multiple:
+    if (scalar(PVE::Tools::split_list($secret)) != 1) {
+       die "only exactly one secret key allowed\n";
+    }
+
+    my $digits = delete($tfa_cfg->{digits}) // 6;
+    my $step = delete($tfa_cfg->{step}) // 30;
+    # Maybe also this?
+    #     my $algorithm = delete($tfa_cfg->{algorithm}) // 'sha1';
+
+    if (length(my $more = join(', ', keys %$tfa_cfg))) {
+       die "unexpected tfa config keys: $more\n";
+    }
+
+    PVE::OTP::oath_verify_otp($value, $secret, $step, $digits);
+}
+
 __PACKAGE__->register_method ({
     name => 'change_tfa',
     path => 'tfa',
     method => 'PUT',
     permissions => {
-       description => 'A user can change their own u2f token.',
+       description => 'A user can change their own u2f or totp token.',
        check => [ 'or',
                   ['userid-param', 'self'],
                   [ 'and',
@@ -454,9 +500,26 @@ __PACKAGE__->register_method ({
            },
            response => {
                optional => 1,
-               description => 'The response to the current registration challenge.',
+               description =>
+                   'Either the the response to the current u2f registration challenge,'
+                   .' or, when adding TOTP, the currently valid TOTP value.',
                type => 'string',
            },
+           key => {
+               optional => 1,
+               description => 'When adding TOTP, the shared secret value.',
+               type => 'string',
+               # This is what pve-common's PVE::OTP::oath_verify_otp accepts.
+               # Should we move this to pve-common's JSONSchema as a named format?
+               pattern => qr/[A-Z2-7=]{16}|[A-Fa-f0-9]{40}/,
+           },
+           config => {
+               optional => 1,
+               description => 'A TFA configuration. This must currently be of type TOTP of not set at all.',
+               type => 'string',
+               format => 'pve-tfa-config',
+               maxLength => 128,
+           },
        }
     },
     returns => { type => 'object' },
@@ -469,6 +532,8 @@ __PACKAGE__->register_method ({
        my $action = delete $param->{action};
        my $response = delete $param->{response};
        my $password = delete($param->{password}) // '';
+       my $key = delete($param->{key});
+       my $config = delete($param->{config});
 
        my ($userid, $ruid, $realm) = PVE::AccessControl::verify_username($param->{userid});
        $rpcenv->check_user_exist($userid);
@@ -491,12 +556,24 @@ __PACKAGE__->register_method ({
            PVE::AccessControl::user_set_tfa($userid, $realm, undef, undef);
            PVE::Cluster::log_msg('info', $authuser, "deleted u2f data for user '$userid'");
        } elsif ($action eq 'new') {
-           my $u2f = get_u2f_instance($rpcenv);
-           my $challenge = $u2f->registration_challenge()
-               or raise("failed to get u2f challenge");
-           $challenge = decode_json($challenge);
-           PVE::AccessControl::user_set_tfa($userid, $realm, 'u2f', $challenge);
-           return $challenge;
+           if (defined($config)) {
+               $config = PVE::Auth::Plugin::parse_tfa_config($config);
+               my $type = delete($config->{type});
+               my $tfa_cfg = {
+                   keys => $key,
+                   config => $config,
+               };
+               verify_user_tfa_config($type, $tfa_cfg, $response);
+               PVE::AccessControl::user_set_tfa($userid, $realm, $type, $tfa_cfg);
+           } else {
+               # The default is U2F:
+               my $u2f = get_u2f_instance($rpcenv);
+               my $challenge = $u2f->registration_challenge()
+                   or raise("failed to get u2f challenge");
+               $challenge = decode_json($challenge);
+               PVE::AccessControl::user_set_tfa($userid, $realm, 'u2f', $challenge);
+               return $challenge;
+           }
        } elsif ($action eq 'confirm') {
            raise_param_exc('response' => "confirm action requires the 'response' parameter to be set")
                if !defined($response);
@@ -513,7 +590,7 @@ __PACKAGE__->register_method ({
            my ($keyHandle, $publicKey) = $u2f->registration_verify($response);
            PVE::AccessControl::user_set_tfa($userid, $realm, 'u2f', {
                keyHandle => $keyHandle,
-               publicKey => encode_base64($publicKey, ''),
+               publicKey => $publicKey, # already base64 encoded
            });
        } else {
            die "invalid action: $action\n";
@@ -549,27 +626,35 @@ __PACKAGE__->register_method({
        my ($param) = @_;
 
        my $rpcenv = PVE::RPCEnvironment::get();
-       my $challenge = $rpcenv->get_u2f_challenge()
-          or raise('no active challenge');
        my $authuser = $rpcenv->get_user();
        my ($username, undef, $realm) = PVE::AccessControl::verify_username($authuser);
 
-       my ($tfa_type, $u2fdata) = PVE::AccessControl::user_get_tfa($username, $realm);
-       if (!defined($tfa_type) || $tfa_type ne 'u2f') {
+       my ($tfa_type, $tfa_data) = PVE::AccessControl::user_get_tfa($username, $realm);
+       if (!defined($tfa_type)) {
            raise('no u2f data available');
        }
 
-       my $keyHandle = $u2fdata->{keyHandle};
-       my $publicKey = $u2fdata->{publicKey};
-       raise("incomplete u2f setup")
-           if !defined($keyHandle) || !defined($publicKey);
+       eval {
+           if ($tfa_type eq 'u2f') {
+               my $challenge = $rpcenv->get_u2f_challenge()
+                  or raise('no active challenge');
+
+               my $keyHandle = $tfa_data->{keyHandle};
+               my $publicKey = $tfa_data->{publicKey};
+               raise("incomplete u2f setup")
+                   if !defined($keyHandle) || !defined($publicKey);
 
-       my $u2f = get_u2f_instance($rpcenv, $publicKey, $keyHandle);
-       $u2f->set_challenge($challenge);
+               my $u2f = get_u2f_instance($rpcenv, $publicKey, $keyHandle);
+               $u2f->set_challenge($challenge);
 
-       eval {
-           my ($counter, $present) = $u2f->auth_verify($param->{response});
-           # Do we want to do anything with these?
+               my ($counter, $present) = $u2f->auth_verify($param->{response});
+               # Do we want to do anything with these?
+           } else {
+               # sanity check before handing off to the verification code:
+               my $keys = $tfa_data->{keys} or die "missing tfa keys\n";
+               my $config = $tfa_data->{config} or die "bad tfa entry\n";
+               PVE::AccessControl::verify_one_time_pw($tfa_type, $authuser, $keys, $config, $param->{response});
+           }
        };
        if (my $err = $@) {
            my $clientip = $rpcenv->get_client_ip() || '';
@@ -577,10 +662,8 @@ __PACKAGE__->register_method({
            die PVE::Exception->new("authentication failure\n", code => 401);
        }
 
-       # create a new ticket for the user:
-       my $ticket_data = "u2f!$authuser!verified";
        return {
-           ticket => PVE::AccessControl::assemble_ticket($ticket_data),
+           ticket => PVE::AccessControl::assemble_ticket($authuser),
            cap => &$compute_api_permission($rpcenv, $authuser),
        }
     }});