Beispiel #1
0
            public static async Task <AuditEventType[]> GetAvailableEvents(this IAuthentication auth)
            {
                var rq = new GetAuditEventDimensionsCommand();
                var rs = await auth.ExecuteAuthCommand <GetAuditEventDimensionsCommand, GetAuditEventDimensionsResponse>(rq);

                return(rs.Dimensions?.AuditEventTypes);
            }
        private static async Task <List <KeeperApiResponse> > ExecuteCommands(this IAuthentication auth, IReadOnlyCollection <KeeperApiCommand> commands)
        {
            var responses = new List <KeeperApiResponse>();
            var pos       = 0;

            while (pos < commands.Count)
            {
                var executeRq = new ExecuteCommand
                {
                    Requests = commands.Skip(pos).Take(99).ToArray()
                };
                pos += 99;

                var executeRs = await auth.ExecuteAuthCommand <ExecuteCommand, ExecuteResponse>(executeRq);

                responses.AddRange(executeRs.Results);
                if (responses.Count < pos)
                {
                    break;
                }

                await Task.Delay(TimeSpan.FromSeconds(10));
            }

            return(responses);
        }
 public static async Task ShareAccount(this IAuthentication auth, AccountShareTo[] shareAccountTo)
 {
     if (shareAccountTo != null)
     {
         foreach (var shareTo in shareAccountTo)
         {
             var key     = CryptoUtils.LoadPublicKey(shareTo.PublicKey.Base64UrlDecode());
             var command = new ShareAccountCommand
             {
                 ToRoleId    = shareTo.RoleId,
                 TransferKey = CryptoUtils.EncryptRsa(auth.AuthContext.DataKey, key).Base64UrlEncode()
             };
             await auth.ExecuteAuthCommand(command);
         }
     }
 }
            public static async Task <string> ChangeMasterPassword(this IAuthentication auth)
            {
                if (auth.AuthCallback is IPostLoginTaskUI postUi)
                {
                    var userParams = await auth.Endpoint.GetNewUserParams(auth.Username);

                    var rules = userParams.PasswordMatchDescription
                                .Zip(userParams.PasswordMatchRegex,
                                     (description, pattern) => new PasswordRule
                    {
                        description = description,
                        match       = true,
                        pattern     = pattern
                    })
                                .ToArray();
                    var ruleMatcher = new PasswordRuleMatcher(rules);

                    var newPassword = await postUi.GetNewPassword(ruleMatcher);

                    var failedRules = ruleMatcher.MatchFailedRules(newPassword);
                    if (failedRules.Length != 0)
                    {
                        throw new KeeperApiException("password_rule_failed", failedRules[0]);
                    }

                    var iterations           = 100000;
                    var authSalt             = CryptoUtils.GetRandomBytes(16);
                    var authVerifier         = CryptoUtils.CreateAuthVerifier(newPassword, authSalt, iterations);
                    var keySalt              = CryptoUtils.GetRandomBytes(16);
                    var encryptionParameters = CryptoUtils.CreateEncryptionParams(newPassword, keySalt, iterations, auth.AuthContext.DataKey);

                    var command = new ChangeMasterPasswordCommand
                    {
                        AuthVerifier     = authVerifier.Base64UrlEncode(),
                        EncryptionParams = encryptionParameters.Base64UrlEncode()
                    };

                    await auth.ExecuteAuthCommand(command);

                    return(newPassword);
                }

                return(null);
            }
Beispiel #5
0
            public static async Task <Tuple <GetAuditEventReportsResponse, long> > GetUserEvents(this IAuthentication auth, string forUser, long recentUnixTime, long latestUnixTime = 0)
            {
                if (recentUnixTime < 0 || latestUnixTime < 0 || string.IsNullOrEmpty(forUser))
                {
                    return(null);
                }

                if (recentUnixTime == 0)
                {
                    recentUnixTime = DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000;
                }

                var rq = new GetAuditEventReportsCommand
                {
                    Filter = new ReportFilter
                    {
                        Username = forUser,
                        Created  = new CreatedFilter
                        {
                            Max = recentUnixTime == 0 ? (long?)null : recentUnixTime,
                            Min = latestUnixTime == 0 ? (long?)null : latestUnixTime
                        }
                    },
                    Limit      = 1000,
                    ReportType = "raw",
                    Order      = "descending"
                };

                var rs = await auth.ExecuteAuthCommand <GetAuditEventReportsCommand, GetAuditEventReportsResponse>(rq);

                var response = Tuple.Create <GetAuditEventReportsResponse, long>(rs, -1);

                if (rs.Events == null || rs.Events.Count == 0)
                {
                    return(response);
                }

                if (rq.Limit > 0 && rs.Events?.Count < 0.95 * rq.Limit)
                {
                    return(response);
                }


                var pos = rs.Events.Count - 1;

                if (!rs.Events[pos].TryGetValue("created", out var lastCreated))
                {
                    return(response);
                }

                while (pos > 0)
                {
                    pos--;
                    if (rs.Events[pos].TryGetValue("created", out var created))
                    {
                        if (!Equals(created, lastCreated))
                        {
                            break;
                        }
                    }
                }

                if (pos <= 0 || pos >= rs.Events.Count - 1)
                {
                    return(response);
                }
                if (!(lastCreated is IConvertible conv))
                {
                    return(response);
                }

                rs.Events.RemoveRange(pos + 1, rs.Events.Count - pos - 1);
                return(Tuple.Create(rs, conv.ToInt64(CultureInfo.InvariantCulture) + 1));
            }
        public static async Task ExecuteDeviceApprove(IAuthentication auth, IList <string> messages)
        {
            var keysRq = new EnterpriseDataCommand
            {
                include = new[] { "devices_request_for_admin_approval" }
            };
            var rs = await auth.ExecuteAuthCommand <EnterpriseDataCommand, EnterpriseDataResponse>(keysRq);

            if ((rs.DeviceRequestForApproval?.Count ?? 0) == 0)
            {
                return;
            }

            var userDataKeys = new Dictionary <long, byte[]>();

            foreach (var drq in rs.DeviceRequestForApproval)
            {
                if (!userDataKeys.ContainsKey(drq.EnterpriseUserId))
                {
                    userDataKeys[drq.EnterpriseUserId] = null;
                }
            }

            var dataKeyRq = new UserDataKeyRequest();

            dataKeyRq.EnterpriseUserId.AddRange(userDataKeys.Keys);
            var dataKeyRs = await auth.ExecuteAuthRest <UserDataKeyRequest, EnterpriseUserDataKeys>("enterprise/get_enterprise_user_data_key", dataKeyRq);

            foreach (var key in dataKeyRs.Keys)
            {
                if (key.UserEncryptedDataKey.IsEmpty)
                {
                    continue;
                }
                if (key.KeyTypeId != 2)
                {
                    continue;
                }
                try
                {
                    var userDataKey = CryptoUtils.DecryptEc(key.UserEncryptedDataKey.ToByteArray(), _enterprisePrivateKey);
                    userDataKeys[key.EnterpriseUserId] = userDataKey;
                }
                catch (Exception e)
                {
                    messages.Add($"Data key decrypt error: {e.Message}");
                }
            }

            var approveDevicesRq = new ApproveUserDevicesRequest();

            foreach (var drq in rs.DeviceRequestForApproval)
            {
                if (!userDataKeys.ContainsKey(drq.EnterpriseUserId) || userDataKeys[drq.EnterpriseUserId] == null)
                {
                    continue;
                }

                var dataKey         = userDataKeys[drq.EnterpriseUserId];
                var devicePublicKey = CryptoUtils.LoadPublicEcKey(drq.DevicePublicKey.Base64UrlDecode());
                var encDataKey      = CryptoUtils.EncryptEc(dataKey, devicePublicKey);
                var approveRq       = new ApproveUserDeviceRequest
                {
                    EnterpriseUserId       = drq.EnterpriseUserId,
                    EncryptedDeviceToken   = ByteString.CopyFrom(drq.EncryptedDeviceToken.Base64UrlDecode()),
                    EncryptedDeviceDataKey = ByteString.CopyFrom(encDataKey),
                    DenyApproval           = false,
                };
                approveDevicesRq.DeviceRequests.Add(approveRq);
            }

            if (approveDevicesRq.DeviceRequests.Count == 0)
            {
                return;
            }

            var approveRs = await auth.ExecuteAuthRest <ApproveUserDevicesRequest, ApproveUserDevicesResponse>("enterprise/approve_user_devices", approveDevicesRq);

            foreach (var deviceRs in approveRs.DeviceResponses)
            {
                var message = $"Approve device for {deviceRs.EnterpriseUserId} {(deviceRs.Failed ? "failed" : "succeeded")}";
                Debug.WriteLine(message);
                messages.Add(message);
            }
        }
 /// <summary>
 /// Executes JSON authenticated command.
 /// </summary>
 /// <typeparam name="TC">JSON authenticated command type.</typeparam>
 /// <param name="auth">The authenticated connection.</param>
 /// <param name="command">SON authenticated command.</param>
 /// <returns>Awaitable task.</returns>
 /// <exception cref="KeeperApiException">Keeper API Exception.</exception>
 /// <seealso cref="IKeeperEndpoint.ExecuteV2Command"/>
 public static Task ExecuteAuthCommand <TC>(this IAuthentication auth, TC command)
     where TC : AuthenticatedCommand
 {
     return(auth.ExecuteAuthCommand <TC, KeeperApiResponse>(command));
 }
 /// <summary>
 /// Executes JSON authenticated command.
 /// </summary>
 /// <typeparam name="TC">JSON authenticated command type.</typeparam>
 /// <typeparam name="TR">JSON response type.</typeparam>
 /// <param name="auth">The authenticated connection.</param>
 /// <param name="command">JSON authenticated command.</param>
 /// <param name="throwOnError">if <c>True</c> throw exception on Keeper error.</param>
 /// <returns>A Task returning JSON response.</returns>
 /// <exception cref="KeeperApiException">Keeper API Exception.</exception>
 /// <seealso cref="IKeeperEndpoint.ExecuteV2Command"/>
 public static async Task <TR> ExecuteAuthCommand <TC, TR>(this IAuthentication auth, TC command, bool throwOnError = true)
     where TC : AuthenticatedCommand
     where TR : KeeperApiResponse
 {
     return((TR)await auth.ExecuteAuthCommand(command, typeof(TR), throwOnError));
 }
 /// <summary>
 /// Executes JSON authenticated command that does not return data.
 /// </summary>
 /// <param name="auth">The authenticated connection.</param>
 /// <param name="command">JSON authenticated command.</param>
 /// <returns>A Task returning basic JSON response.</returns>
 /// <seealso cref="IKeeperEndpoint.ExecuteV2Command"/>
 public static async Task <KeeperApiResponse> ExecuteAuthCommand(this IAuthentication auth, AuthenticatedCommand command)
 {
     return(await auth.ExecuteAuthCommand(command, typeof(KeeperApiResponse), true));
 }