]> git.proxmox.com Git - pve-access-control.git/blobdiff - src/PVE/API2/AccessControl.pm
move TFA api path into its own module
[pve-access-control.git] / src / PVE / API2 / AccessControl.pm
index a77694b7561d64f080db9c4c26e22d6ffd7b0f1d..5d78c6fa0aac92b70c044cfd82b8b3346022da29 100644 (file)
@@ -19,9 +19,10 @@ use PVE::API2::User;
 use PVE::API2::Group;
 use PVE::API2::Role;
 use PVE::API2::ACL;
+use PVE::API2::OpenId;
+use PVE::API2::TFA;
 use PVE::Auth::Plugin;
 use PVE::OTP;
-use PVE::Tools;
 
 my $u2f_available = 0;
 eval {
@@ -56,6 +57,16 @@ __PACKAGE__->register_method ({
     path => 'domains',
 });
 
+__PACKAGE__->register_method ({
+    subclass => "PVE::API2::OpenId",
+    path => 'openid',
+});
+
+__PACKAGE__->register_method ({
+    subclass => "PVE::API2::TFA",
+    path => 'tfa',
+});
+
 __PACKAGE__->register_method ({
     name => 'index',
     path => '',
@@ -100,8 +111,8 @@ __PACKAGE__->register_method ({
     }});
 
 
-my $verify_auth = sub {
-    my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs) = @_;
+my sub verify_auth : prototype($$$$$$$) {
+    my ($rpcenv, $username, $pw_or_ticket, $otp, $path, $privs, $new_format) = @_;
 
     my $normpath = PVE::AccessControl::normalize_path($path);
 
@@ -112,7 +123,12 @@ my $verify_auth = sub {
     } elsif (PVE::AccessControl::verify_vnc_ticket($pw_or_ticket, $username, $normpath, 1)) {
        # valid vnc ticket
     } else {
-       $username = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
+       $username = PVE::AccessControl::authenticate_user(
+           $username,
+           $pw_or_ticket,
+           $otp,
+           $new_format,
+       );
     }
 
     my $privlist = [ PVE::Tools::split_list($privs) ];
@@ -123,22 +139,45 @@ my $verify_auth = sub {
     return { username => $username };
 };
 
-my $create_ticket = sub {
-    my ($rpcenv, $username, $pw_or_ticket, $otp) = @_;
+my sub create_ticket_do : prototype($$$$$$) {
+    my ($rpcenv, $username, $pw_or_ticket, $otp, $new_format, $tfa_challenge) = @_;
+
+    die "TFA response should be in 'password', not 'otp' when 'tfa-challenge' is set\n"
+       if defined($otp) && defined($tfa_challenge);
+
+    my ($ticketuser, undef, $tfa_info);
+    if (!defined($tfa_challenge)) {
+       # We only verify this ticket if we're not responding to a TFA challenge, as in that case
+       # it is a TFA-data ticket and will be verified by `authenticate_user`.
+
+       ($ticketuser, undef, $tfa_info) = PVE::AccessControl::verify_ticket($pw_or_ticket, 1);
+    }
 
-    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, $tfa_info) = PVE::AccessControl::authenticate_user($username, $pw_or_ticket, $otp);
+       ($username, $tfa_info) = PVE::AccessControl::authenticate_user(
+           $username,
+           $pw_or_ticket,
+           $otp,
+           $new_format,
+           $tfa_challenge,
+       );
     }
 
     my %extra;
     my $ticket_data = $username;
-    if (defined($tfa_info)) {
+    my $aad;
+    if ($new_format) {
+       if (defined($tfa_info)) {
+           $extra{NeedTFA} = 1;
+           $ticket_data = "!tfa!$tfa_info";
+           $aad = $username;
+       }
+    } elsif (defined($tfa_info)) {
        $extra{NeedTFA} = 1;
        if ($tfa_info->{type} eq 'u2f') {
            my $u2finfo = $tfa_info->{data};
@@ -154,7 +193,7 @@ my $create_ticket = sub {
        }
     }
 
-    my $ticket = PVE::AccessControl::assemble_ticket($ticket_data);
+    my $ticket = PVE::AccessControl::assemble_ticket($ticket_data, $aad);
     my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token($username);
 
     return {
@@ -165,55 +204,6 @@ my $create_ticket = sub {
     };
 };
 
-my $compute_api_permission = sub {
-    my ($rpcenv, $authuser) = @_;
-
-    my $usercfg = $rpcenv->{user_cfg};
-
-    my $res = {};
-    my $priv_re_map = {
-       vms => qr/VM\.|Permissions\.Modify/,
-       access => qr/(User|Group)\.|Permissions\.Modify/,
-       storage => qr/Datastore\.|Permissions\.Modify/,
-       nodes => qr/Sys\.|Permissions\.Modify/,
-       sdn => qr/SDN\.|Permissions\.Modify/,
-       dc => qr/Sys\.Audit|SDN\./,
-    };
-    map { $res->{$_} = {} } keys %$priv_re_map;
-
-    my $required_paths = ['/', '/nodes', '/access/groups', '/vms', '/storage', '/sdn'];
-
-    my $checked_paths = {};
-    foreach my $path (@$required_paths, keys %{$usercfg->{acl}}) {
-       next if $checked_paths->{$path};
-       $checked_paths->{$path} = 1;
-
-       my $path_perm = $rpcenv->permissions($authuser, $path);
-
-       my $toplevel = ($path =~ /^\/(\w+)/) ? $1 : 'dc';
-       if ($toplevel eq 'pool') {
-           foreach my $priv (keys %$path_perm) {
-               if ($priv =~ m/^VM\./) {
-                   $res->{vms}->{$priv} = 1;
-               } elsif ($priv =~ m/^Datastore\./) {
-                   $res->{storage}->{$priv} = 1;
-               } elsif ($priv eq 'Permissions.Modify') {
-                   $res->{storage}->{$priv} = 1;
-                   $res->{vms}->{$priv} = 1;
-               }
-           }
-       } else {
-           my $priv_regex = $priv_re_map->{$toplevel} // next;
-           foreach my $priv (keys %$path_perm) {
-               next if $priv !~ m/^($priv_regex)/;
-               $res->{$toplevel}->{$priv} = 1;
-           }
-       }
-    }
-
-    return $res;
-};
-
 __PACKAGE__->register_method ({
     name => 'get_ticket',
     path => 'ticket',
@@ -274,6 +264,20 @@ __PACKAGE__->register_method ({
                optional => 1,
                maxLength => 64,
            },
+           'new-format' => {
+               type => 'boolean',
+               description =>
+                   'With webauthn the format of half-authenticated tickts changed.'
+                   .' New clients should pass 1 here and not worry about the old format.'
+                   .' The old format is deprecated and will be retired with PVE-8.0',
+               optional => 1,
+               default => 0,
+           },
+           'tfa-challenge' => {
+               type => 'string',
+                description => "The signed TFA challenge string the user wants to respond to.",
+               optional => 1,
+           },
        }
     },
     returns => {
@@ -301,10 +305,17 @@ __PACKAGE__->register_method ({
            $rpcenv->check_user_enabled($username);
 
            if ($param->{path} && $param->{privs}) {
-               $res = &$verify_auth($rpcenv, $username, $param->{password}, $param->{otp},
-                                    $param->{path}, $param->{privs});
+               $res = verify_auth($rpcenv, $username, $param->{password}, $param->{otp},
+                                  $param->{path}, $param->{privs}, $param->{'new-format'});
            } else {
-               $res = &$create_ticket($rpcenv, $username, $param->{password}, $param->{otp});
+               $res = create_ticket_do(
+                   $rpcenv,
+                   $username,
+                   $param->{password},
+                   $param->{otp},
+                   $param->{'new-format'},
+                   $param->{'tfa-challenge'},
+               );
            }
        };
        if (my $err = $@) {
@@ -314,7 +325,7 @@ __PACKAGE__->register_method ({
            die PVE::Exception->new("authentication failure\n", code => 401);
        }
 
-       $res->{cap} = &$compute_api_permission($rpcenv, $username)
+       $res->{cap} = $rpcenv->compute_api_permission($username)
            if !defined($res->{NeedTFA});
 
        my $clinfo = PVE::Cluster::get_clinfo();
@@ -459,209 +470,6 @@ sub verify_user_tfa_config {
     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 or totp token.',
-       check => [ 'or',
-                  ['userid-param', 'self'],
-                  [ 'and',
-                    [ 'userid-param', 'Realm.AllocateUser'],
-                    [ 'userid-group', ['User.Modify']]
-                  ]
-           ],
-    },
-    protected => 1, # else we can't access shadow files
-    allowtoken => 0, # we don't want tokens to change the regular user's TFA settings
-    description => "Change user u2f authentication.",
-    parameters => {
-       additionalProperties => 0,
-       properties => {
-           userid => get_standard_option('userid', {
-               completion => \&PVE::AccessControl::complete_username,
-           }),
-           password => {
-               optional => 1, # Only required if not root@pam
-               description => "The current password.",
-               type => 'string',
-               minLength => 5,
-               maxLength => 64,
-           },
-           action => {
-               description => 'The action to perform',
-               type => 'string',
-               enum => [qw(delete new confirm)],
-           },
-           response => {
-               optional => 1,
-               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',
-               format => 'pve-tfa-secret',
-           },
-           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' },
-    code => sub {
-       my ($param) = @_;
-
-       my $rpcenv = PVE::RPCEnvironment::get();
-       my $authuser = $rpcenv->get_user();
-
-       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);
-
-       # Only root may modify root
-       raise_perm_exc() if $userid eq 'root@pam' && $authuser ne 'root@pam';
-
-       # Regular users need to confirm their password to change u2f settings.
-       if ($authuser ne 'root@pam') {
-           raise_param_exc({ 'password' => 'password is required to modify u2f data' })
-               if !defined($password);
-           my $domain_cfg = cfs_read_file('domains.cfg');
-           my $cfg = $domain_cfg->{ids}->{$realm};
-           die "auth domain '$realm' does not exist\n" if !$cfg;
-           my $plugin = PVE::Auth::Plugin->lookup($cfg->{type});
-           $plugin->authenticate_user($cfg, $realm, $ruid, $password);
-       }
-
-       if ($action eq 'delete') {
-           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') {
-           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);
-
-           my ($type, $u2fdata) = PVE::AccessControl::user_get_tfa($userid, $realm);
-           raise("no u2f data available")
-               if (!defined($type) || $type ne 'u2f');
-
-           my $challenge = $u2fdata->{challenge}
-               or raise("no active challenge");
-
-           my $u2f = get_u2f_instance($rpcenv);
-           $u2f->set_challenge($challenge);
-           my ($keyHandle, $publicKey) = $u2f->registration_verify($response);
-           PVE::AccessControl::user_set_tfa($userid, $realm, 'u2f', {
-               keyHandle => $keyHandle,
-               publicKey => $publicKey, # already base64 encoded
-           });
-       } else {
-           die "invalid action: $action\n";
-       }
-
-       return {};
-    }});
-
-__PACKAGE__->register_method({
-    name => 'verify_tfa',
-    path => 'tfa',
-    method => 'POST',
-    permissions => { user => 'all' },
-    protected => 1, # else we can't access shadow files
-    allowtoken => 0, # we don't want tokens to access TFA information
-    description => 'Finish a u2f challenge.',
-    parameters => {
-       additionalProperties => 0,
-       properties => {
-           response => {
-               type => 'string',
-               description => 'The response to the current authentication challenge.',
-           },
-       }
-    },
-    returns => {
-       type => 'object',
-       properties => {
-           ticket => { type => 'string' },
-           # cap
-       }
-    },
-    code => sub {
-       my ($param) = @_;
-
-       my $rpcenv = PVE::RPCEnvironment::get();
-       my $authuser = $rpcenv->get_user();
-       my ($username, undef, $realm) = PVE::AccessControl::verify_username($authuser);
-
-       my ($tfa_type, $tfa_data) = PVE::AccessControl::user_get_tfa($username, $realm);
-       if (!defined($tfa_type)) {
-           raise('no u2f data available');
-       }
-
-       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 ($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() || '';
-           syslog('err', "authentication verification failure; rhost=$clientip user=$authuser msg=$err");
-           die PVE::Exception->new("authentication failure\n", code => 401);
-       }
-
-       return {
-           ticket => PVE::AccessControl::assemble_ticket($authuser),
-           cap => &$compute_api_permission($rpcenv, $authuser),
-       }
-    }});
 
 __PACKAGE__->register_method({
     name => 'permissions',