public void EnableBiometrics(Action <bool> callback)
        {
            var passwordStorage = new PasswordStorageManager(this);
            var executor        = ContextCompat.GetMainExecutor(this);
            var authCallback    = new AuthenticationCallback();

            authCallback.Success += async(_, result) =>
            {
                try
                {
                    var password = await SecureStorageWrapper.GetDatabasePassword();

                    passwordStorage.Store(password, result.CryptoObject.Cipher);
                }
                catch (Exception e)
                {
                    Logger.Error(e);
                    callback(false);
                    return;
                }

                callback(true);
            };

            authCallback.Failed += delegate
            {
                callback(false);
            };

            authCallback.Error += delegate
            {
                // Do something, probably
                callback(false);
            };

            var prompt = new BiometricPrompt(this, executor, authCallback);

            var promptInfo = new BiometricPrompt.PromptInfo.Builder()
                             .SetTitle(GetString(Resource.String.setupBiometricUnlock))
                             .SetNegativeButtonText(GetString(Resource.String.cancel))
                             .SetConfirmationRequired(false)
                             .SetAllowedAuthenticators(BiometricManager.Authenticators.BiometricStrong)
                             .Build();

            Cipher cipher;

            try
            {
                cipher = passwordStorage.GetEncryptionCipher();
            }
            catch (Exception e)
            {
                Logger.Error(e);
                passwordStorage.Clear();
                callback(false);
                return;
            }

            prompt.Authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher));
        }
示例#2
0
        private async Task <RestoreResult> RestoreFromDir(Uri destUri)
        {
            if (!HasPersistablePermissionsAtUri(destUri))
            {
                throw new Exception("No permission at URI");
            }

            var directory = DocumentFile.FromTreeUri(_context, destUri);
            var files     = directory.ListFiles();

            var mostRecentBackup = files
                                   .Where(f => f.IsFile && f.Type == Backup.MimeType && f.Name.EndsWith(Backup.FileExtension) && f.Length() > 0 && f.CanRead())
                                   .OrderByDescending(f => f.LastModified())
                                   .FirstOrDefault();

            if (mostRecentBackup == null || mostRecentBackup.LastModified() <= _preferences.MostRecentBackupModifiedAt)
            {
                return(new RestoreResult());
            }

            _preferences.MostRecentBackupModifiedAt = mostRecentBackup.LastModified();
            var password = await SecureStorageWrapper.GetAutoBackupPassword();

            if (password == null)
            {
                throw new Exception("No password defined.");
            }

            var data = await FileUtil.ReadFile(_context, mostRecentBackup.Uri);

            var backup = Backup.FromBytes(data, password);

            var(authsAdded, authsUpdated) = await _authSource.AddOrUpdateMany(backup.Authenticators);

            var categoriesAdded = backup.Categories != null
                ? await _categorySource.AddMany(backup.Categories)
                : 0;

            if (backup.AuthenticatorCategories != null)
            {
                await _authSource.AddOrUpdateManyCategoryBindings(backup.AuthenticatorCategories);
            }

            var customIconsAdded = backup.CustomIcons != null
                ? await _customIconSource.AddMany(backup.CustomIcons)
                : 0;

            try
            {
                await _customIconSource.CullUnused();
            }
            catch (Exception e)
            {
                // ignored
                Logger.Error(e);
            }

            return(new RestoreResult(authsAdded, authsUpdated, categoriesAdded, customIconsAdded));
        }
示例#3
0
 private async void OnPasswordEntered(object sender, string password)
 {
     _preferences.AutoBackupPasswordProtected = password != "";
     ((BackupPasswordBottomSheet)sender).Dismiss();
     UpdatePasswordStatusText();
     UpdateSwitchesAndTriggerButton();
     await SecureStorageWrapper.SetAutoBackupPassword(password);
 }
示例#4
0
        private async void OnSetPasswordButtonClick(object sender, EventArgs e)
        {
            if (_passwordText.Text != _passwordConfirmText.Text)
            {
                _passwordConfirmLayout.Error = GetString(Resource.String.passwordsDoNotMatch);
                return;
            }

            var newPassword = _passwordText.Text == "" ? null : _passwordText.Text;

            _setPasswordButton.Enabled = _cancelButton.Enabled = false;
            _setPasswordButton.SetText(newPassword != null ? Resource.String.encrypting : Resource.String.decrypting);
            SetCancelable(false);

            try
            {
                var currentPassword = await SecureStorageWrapper.GetDatabasePassword();

                await Database.SetPassword(currentPassword, newPassword);

                try
                {
                    await SecureStorageWrapper.SetDatabasePassword(newPassword);
                }
                catch
                {
                    // Revert changes
                    await Database.SetPassword(newPassword, currentPassword);

                    throw;
                }
            }
            catch
            {
                Toast.MakeText(Context, Resource.String.genericError, ToastLength.Short).Show();
                SetCancelable(true);
                UpdateSetPasswordButton();
                _cancelButton.Enabled = true;
                return;
            }

            _preferences.AllowBiometrics   = false;
            _preferences.PasswordProtected = newPassword != null;
            _preferences.PasswordChanged   = true;

            try
            {
                var manager = new PasswordStorageManager(Context);
                manager.Clear();
            }
            catch
            {
                // Not really an issue if this fails
            }

            await((SettingsActivity)Context).BaseApplication.Unlock(newPassword);
            Dismiss();
        }
        private async Task <string> GetBackupPassword()
        {
            if (_preferences.DatabasePasswordBackup)
            {
                return(await SecureStorageWrapper.GetDatabasePassword());
            }

            return(await SecureStorageWrapper.GetAutoBackupPassword());
        }
示例#6
0
 public WearQueryService()
 {
     _initTask = new Lazy <Task>(async delegate
     {
         var password      = await SecureStorageWrapper.GetDatabasePassword();
         _connection       = await Database.GetPrivateConnection(password);
         _customIconSource = new CustomIconSource(_connection);
         _categorySource   = new CategorySource(_connection);
         _authSource       = new AuthenticatorSource(_connection);
     });
 }
示例#7
0
        public AutoBackupWorker(Context context, WorkerParameters workerParams) : base(context, workerParams)
        {
            _context     = context;
            _preferences = new PreferenceWrapper(context);

            _initTask = new Lazy <Task>(async delegate
            {
                var password      = await SecureStorageWrapper.GetDatabasePassword();
                _connection       = await Database.GetPrivateConnection(password);
                _customIconSource = new CustomIconSource(_connection);
                _categorySource   = new CategorySource(_connection);
                _authSource       = new AuthenticatorSource(_connection);

                await _categorySource.Update();
                await _customIconSource.Update();
                await _authSource.Update();
            });
        }
示例#8
0
        public WearQueryService()
        {
            _shouldCloseDatabase             = false;
            _database                        = Dependencies.Resolve <Database>();
            _authenticatorView               = Dependencies.Resolve <IAuthenticatorView>();
            _authenticatorCategoryRepository = Dependencies.Resolve <IAuthenticatorCategoryRepository>();
            _categoryRepository              = Dependencies.Resolve <ICategoryRepository>();
            _customIconRepository            = Dependencies.Resolve <ICustomIconRepository>();

            _initTask = new Lazy <Task>(async delegate
            {
                if (!_database.IsOpen)
                {
                    var password = await SecureStorageWrapper.GetDatabasePassword();
                    await _database.Open(password);
                    _shouldCloseDatabase = true;
                }
            });
        }
示例#9
0
        private async Task <BackupResult> BackupToDir(Uri destUri)
        {
            if (!_authSource.GetAll().Any())
            {
                return(new BackupResult());
            }

            if (!HasPersistablePermissionsAtUri(destUri))
            {
                throw new Exception("No permission at URI");
            }

            var password = await SecureStorageWrapper.GetAutoBackupPassword();

            if (password == null)
            {
                throw new Exception("No password defined.");
            }

            var backup = new Backup(
                _authSource.GetAll(),
                _categorySource.GetAll(),
                _authSource.CategoryBindings,
                _customIconSource.GetAll()
                );

            var dataToWrite = backup.ToBytes(password);

            var directory = DocumentFile.FromTreeUri(_context, destUri);
            var file      = directory.CreateFile(Backup.MimeType, $"backup-{DateTime.Now:yyyy-MM-dd_HHmmss}.{Backup.FileExtension}");

            if (file == null)
            {
                throw new Exception("File creation failed, got null.");
            }

            await FileUtil.WriteFile(_context, file.Uri, dataToWrite);

            return(new BackupResult(file.Name));
        }
        public AutoBackupWorker(Context context, WorkerParameters workerParams) : base(context, workerParams)
        {
            _context             = context;
            _preferences         = new PreferenceWrapper(context);
            _shouldCloseDatabase = false;

            _database                        = Dependencies.Resolve <Database>();
            _restoreService                  = Dependencies.Resolve <IRestoreService>();
            _authenticatorRepository         = Dependencies.Resolve <IAuthenticatorRepository>();
            _categoryRepository              = Dependencies.Resolve <ICategoryRepository>();
            _authenticatorCategoryRepository = Dependencies.Resolve <IAuthenticatorCategoryRepository>();
            _customIconRepository            = Dependencies.Resolve <ICustomIconRepository>();

            _initTask = new Lazy <Task>(async delegate
            {
                if (!_database.IsOpen)
                {
                    var password = await SecureStorageWrapper.GetDatabasePassword();
                    await _database.Open(password);
                    _shouldCloseDatabase = true;
                }
            });
        }
        private async void OnSetPasswordButtonClick(object sender, EventArgs args)
        {
            if (_passwordText.Text != _passwordConfirmText.Text)
            {
                _passwordConfirmLayout.Error = GetString(Resource.String.passwordsDoNotMatch);
                return;
            }

            var newPassword = _passwordText.Text == "" ? null : _passwordText.Text;

            _setPasswordButton.Enabled = _cancelButton.Enabled = false;
            _setPasswordButton.SetText(newPassword != null ? Resource.String.encrypting : Resource.String.decrypting);
            _progressBar.Visibility = ViewStates.Visible;
            SetCancelable(false);

            try
            {
                var currentPassword = await SecureStorageWrapper.GetDatabasePassword();

                await _database.SetPassword(currentPassword, newPassword);

                try
                {
                    await SecureStorageWrapper.SetDatabasePassword(newPassword);
                }
                catch
                {
                    // Revert changes
                    await _database.SetPassword(newPassword, currentPassword);

                    throw;
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);

                Toast.MakeText(Context, Resource.String.genericError, ToastLength.Short).Show();
                _progressBar.Visibility = ViewStates.Invisible;
                SetCancelable(true);
                UpdateSetPasswordButton();
                _cancelButton.Enabled = true;
                return;
            }

            _preferences.AllowBiometrics   = false;
            _preferences.PasswordProtected = newPassword != null;
            _preferences.PasswordChanged   = true;

            if (newPassword == null && _preferences.DatabasePasswordBackup)
            {
                _preferences.DatabasePasswordBackup = false;
            }

            try
            {
                var manager = new PasswordStorageManager(Context);
                manager.Clear();
            }
            catch (Exception e)
            {
                // Not really an issue if this fails
                Logger.Error(e);
            }

            Dismiss();
        }