示例#1
0
        /// <summary>
        /// Searches the given path for a gpg-id file.
        /// </summary>
        /// <param name="path">The path that should be searched. This path does not have to point to an
        /// existing file or directory, but it must be located within the password store.</param>
        /// <returns>An array of GPG ids taken from the first gpg-id file that is encountered,
        /// or null if no gpg-id file was found.</returns>
        private string[] GetGpgIds(string path)
        {
            // Ensure the path does not contain any trailing slashes or AltDirectorySeparatorChars
            path = Helpers.NormaliseDirectory(path);

            // Ensure the password file directory is actually located within the password store.
            if (!PasswordStore.IsParentOf(path))
            {
                throw new ArgumentException("The given directory is not a subdirectory of the password store.");
            }

            // Walk up from the innermost directory, and keep moving up until an existing directory
            // containing a gpg-id file is found.
            var current = new DirectoryInfo(path);

            while (!current.Exists || !current.ContainsFile(GpgIdFileName))
            {
                if (current.Parent == null || current.PathEquals(PasswordStore))
                {
                    return(null);
                }
                current = current.Parent;
            }

            return(File.ReadAllLines(Path.Combine(current.FullName, GpgIdFileName)));
        }
示例#2
0
 /// <summary>
 ///     Remove the password of file with a list of password
 /// </summary>
 /// <param name="app"></param>
 /// <param name="path"></param>
 /// <param name="store"></param>
 /// <returns></returns>
 private static int DoFilePassword(Excel.Application app, string path, PasswordStore store)
 {
     Console.WriteLine();
     Console.WriteLine("    Start cracking ... : " + path);
     store.Reset();
     while (store.HasNext())
     {
         string passwd = store.Next();
         int    status = CrackFile(app, path, passwd);
         if (status == IGNORED)
         {
             Console.WriteLine("\r    NO password: "******"\r    " + path + " : Crack success with password - [" + passwd + "]");
             return(SUCCESS);
         }
         else
         {
             Console.Write("\r    password [" + passwd + "] failed, retrying...");
         }
     }
     Console.WriteLine("\r    FAIL to crack ... : " + path);
     return(FAILED);
 }
示例#3
0
        public string GeneratePassword()
        {
            var password = PasswordStore.GeneratePassword(
                _passwordConfiguration.RequiredLength,
                _passwordConfiguration.GetMinNonAlphaNumericChars());

            var random = new Random();

            var passwordChars = password.ToCharArray();

            if (_passwordConfiguration.RequireDigit && passwordChars.ContainsAny(Enumerable.Range(48, 58).Select(x => (char)x)))
            {
                password += Convert.ToChar(random.Next(48, 58));  // 0-9
            }
            if (_passwordConfiguration.RequireLowercase && passwordChars.ContainsAny(Enumerable.Range(97, 123).Select(x => (char)x)))
            {
                password += Convert.ToChar(random.Next(97, 123));  // a-z
            }
            if (_passwordConfiguration.RequireUppercase && passwordChars.ContainsAny(Enumerable.Range(65, 91).Select(x => (char)x)))
            {
                password += Convert.ToChar(random.Next(65, 91));  // A-Z
            }
            if (_passwordConfiguration.RequireNonLetterOrDigit && passwordChars.ContainsAny(Enumerable.Range(33, 48).Select(x => (char)x)))
            {
                password += Convert.ToChar(random.Next(33, 48));  // symbols !"#$%&'()*+,-./
            }
            return(password);
        }
 public SettingsWindow(PasswordStore password, Config config)
 {
     _password = password;
     _config = config;
     Closing += OnWindowClosing;
     InitializeComponent();
     InitVlaues();
 }
 public RefreshWindow(Drive drive, Config config, PasswordStore password)
 {
     _config   = config;
     _drive    = drive;
     _password = password;
     InitializeComponent();
     Task.Run(() => RefreshAnime());
 }
示例#6
0
 public DownloadWindow(Anime anime, PasswordStore password, Config config)
 {
     _anime      = anime;
     _runner     = new RCloneRunner(config.RclonePath, password);
     _outputPath = config.OutputPath;
     Closing    += OnWindowClosing;
     InitializeComponent();
 }
示例#7
0
 public void Save(PasswordStore password)
 {
     using (var sw = new StreamWriter(ConfigFile))
     {
         sw.WriteLine(
             StringCipher.Encrypt(JsonConvert.SerializeObject(this), password.Get())
             );
     }
 }
 public FileListWindow(Anime anime, PasswordStore password, Config config)
 {
     _anime    = anime;
     _password = password;
     _config   = config;
     InitializeComponent();
     FileGrid.ItemsSource = anime.Files;
     DriveName.Text       = $"{anime.Drive.DriveName}:{anime.Drive.Path}";
 }
示例#9
0
        public void user_cant_login_with_wrong_password()
        {
            var clock             = new Clock();
            var passwordStore     = new PasswordStore(clock);
            var passwordGenerator = new PasswordGenerator(passwordStore);
            var username          = "******";
            var password          = passwordGenerator.GeneratePassword(username);
            var success           = passwordStore.IsPasswordValidForUsername(username, password + "te");

            Assert.False(success);
        }
示例#10
0
        public void Can_create_user_and_verify()
        {
            var clock             = new Clock();
            var passwordStore     = new PasswordStore(clock);
            var passwordGenerator = new PasswordGenerator(passwordStore);
            var username          = "******";
            var password          = passwordGenerator.GeneratePassword(username);
            var success           = passwordStore.IsPasswordValidForUsername(username, password);

            Assert.True(success);
        }
示例#11
0
        private void GetPassword()
        {
            var passwordWindow = new PasswordWindow();

            passwordWindow.ShowDialog();
            if (passwordWindow.Password == null || passwordWindow.Config == null)
            {
                Close();
            }

            _password = passwordWindow.Password;
            _config   = passwordWindow.Config;
        }
示例#12
0
        private static Config Deserialize(PasswordStore password)
        {
            if (!File.Exists(ConfigFile))
            {
                return(new Config());
            }

            var content  = File.ReadAllText(ConfigFile);
            var settings = JsonConvert.DeserializeObject <Config>(StringCipher.Decrypt(content, password.Get()));

            settings.AfterDeserialization();
            return(settings);
        }
示例#13
0
        private async Task Rollback(CancellationToken cancellationToken, params StoreTypes[] rollback)
        {
            if (rollback == null)
            {
                throw new ArgumentNullException(nameof(rollback));
            }
            foreach (var i in rollback)
            {
                switch (i)
                {
                case StoreTypes.UserStore:
                    await UserStore.RollbackAsync(cancellationToken);

                    break;

                case StoreTypes.EmailStore:
                    await EmailStore.RollbackAsync(cancellationToken);

                    break;

                case StoreTypes.LockoutStore:
                    await LockoutStore.RollbackAsync(cancellationToken);

                    break;

                case StoreTypes.NameStore:
                    await NameStore.RollbackAsync(cancellationToken);

                    break;

                case StoreTypes.PasswordStore:
                    await PasswordStore.RollbackAsync(cancellationToken);

                    break;

                case StoreTypes.TokenStore:
                    await TokenStore.RollbackAsync(cancellationToken);

                    break;

                case StoreTypes.ClaimStore:
                    await ClaimStore.RollbackAsync(cancellationToken);

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
示例#14
0
 private void CheckPassword()
 {
     Password = new PasswordStore(PasswordInput.Password);
     try
     {
         Config = Config.Get(Password);
         Close();
     }
     catch (Exception e)
     {
         Title = "Invalid password";
         SystemSounds.Hand.Play();
     }
 }
        public async Task <AuthenticationResult> RemoveUser(TUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            Handle(cancellationToken);
            var stores = new List <StoreTypes>();

            var result = await EmailStore.DeleteUserAsync(user, cancellationToken);

            stores.Add(StoreTypes.EmailStore);
            await AssertSingle(user, result, cancellationToken, stores);

            result = await ClaimStore.DeleteUserAsync(user, cancellationToken);

            stores.Add(StoreTypes.ClaimStore);
            await AssertSingle(user, result, cancellationToken, stores);

            await LoginStore.DeleteUser(user, cancellationToken);

            stores.Add(StoreTypes.LoginStore);

            await TokenStore.RemoveUserAsync(user, cancellationToken);

            stores.Add(StoreTypes.TokenStore);

            result = await LockoutStore.DeleteUserAsync(user, cancellationToken);

            stores.Add(StoreTypes.NameStore);
            await AssertSingle(user, result, cancellationToken, stores);

            result = await NameStore.DeleteUserAsync(user, cancellationToken);

            stores.Add(StoreTypes.NameStore);
            await AssertSingle(user, result, cancellationToken, stores);

            result = await PasswordStore.DeleteUserAsync(user, cancellationToken);

            stores.Add(StoreTypes.PasswordStore);
            await AssertSingle(user, result, cancellationToken, stores);

            result = await UserStore.DeleteUserAsync(user, cancellationToken);

            stores.Add(StoreTypes.UserStore);
            await AssertSingle(user, result, cancellationToken, stores);

            return(AuthenticationResult.Success());
        }
示例#16
0
 public void Dispose()
 {
     if (IsDiposed)
     {
         return;
     }
     UserStore.Dispose();
     PasswordStore.Dispose();
     EmailStore.Dispose();
     TokenStore.Dispose();
     LockoutStore.Dispose();
     NameStore.Dispose();
     ClaimStore.Dispose();
     IsDiposed = true;
 }
        public async Task <ApiResponeDto <string> > CreatePassStore([FromBody] PasswordStore storeDetails)
        {
            if (!this.TryValidateModel(storeDetails))
            {
                throw new PassStoreException(PassStoreException.ErrorCategory.InvalidInput, nameof(storeDetails));
            }

            var passtore = await _repo.Create(_mapper.Map <PasswordStoreModel>(storeDetails));

            return(new ApiResponeDto <string>()
            {
                Result = passtore?.Id,
                HasError = false
            });
        }
        public async Task <AuthenticationResult> UpdatePasswordAsync(TUser user, string password, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password));
            }
            Handle(cancellationToken);

            var validate = await ValidationConfiguration.PasswordValidator.ValidateAsync(password, cancellationToken);

            if (!validate.Succeeded)
            {
                return(AuthenticationResult.Invalidate(validate));
            }

            var random = await SecurityConfiguration.RandomProvider.GenerateRandomAsync(cancellationToken);

            var hashed = await SecurityConfiguration.PasswordHasher.HashPassword(password, random, cancellationToken);

            var result = await PasswordStore.SetPasswordAsync(user, hashed, cancellationToken);

            if (!result.Succeeded || result.RowsModified != 1)
            {
                await Rollback(cancellationToken, StoreTypes.PasswordStore);

                return(AuthenticationResult.ServerFault());
            }

            result = await PasswordStore.SetSaltAsync(user, random, cancellationToken);

            if (!result.Succeeded || result.RowsModified != 1)
            {
                await Rollback(cancellationToken, StoreTypes.PasswordStore);

                return(AuthenticationResult.ServerFault());
            }

            await Commit(cancellationToken, StoreTypes.PasswordStore);

            return(AuthenticationResult.Success());
        }
        public async Task <IActionResult> LoginUserAsync(
            string email    = "*****@*****.**",
            string password = "******",
            CancellationToken cancellationToken = default)
        {
            User user = await UserManager.FindByEmailAsync(email);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "لطفا از صحت اطلاعات وارد شده اطمینان حاصل کنید");
                return(View());
            }

            var passwordHash     = UserManager.PasswordHasher.HashPassword(user, password);
            var newPasswordHash  = PasswordHasher.HashPassword(user, password);
            var newPasswordHash1 = PasswordHasher.HashPassword(user, password);

            var passwordResult = await PasswordValidator.ValidateAsync(UserManager, user, password);

            var newPasswordHash2 = PasswordHasher.HashPassword(user, password);
            await PasswordStore.SetPasswordHashAsync(user, password, cancellationToken);

            var userStore = new UserStore <User, Role, ApplicationDbContext, int>(ApplicationDbContext);

            var checkPassSignIn = await SignInManager.CheckPasswordSignInAsync(user, password, true);

            if (checkPassSignIn.Succeeded)
            {
                //این متد PasswordSignInAsync تو خودش از متد بالایی یعنی CheckPasswordSignInAsync استفاده میکنه
                var result = await SignInManager.PasswordSignInAsync(email, password, true, false);

                if (result.Succeeded)
                {
                    RedirectToAction(nameof(Index));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "اطلاعات وارد شده صحیح نمی باشد");
                    return(View());
                }
            }

            return(View());
        }
示例#20
0
        public void user_cant_login_after_password_experation()
        {
            var clockMock    = new Mock <IClock>();
            var fakeDateTime = new DateTime().AddYears(10);

            clockMock.Setup(c => c.Now()).Returns(fakeDateTime);
            var passwordStore     = new PasswordStore(clockMock.Object);
            var passwordGenerator = new PasswordGenerator(passwordStore);
            var username          = "******";
            var password          = passwordGenerator.GeneratePassword(username);

            var futureClockMock    = new Mock <IClock>();
            var futureFakeDateTime = fakeDateTime.AddSeconds(31);

            futureClockMock.Setup(c => c.Now()).Returns(futureFakeDateTime);
            var passwordStoreWithExpiredClock = new PasswordStore(futureClockMock.Object);
            var success = passwordStoreWithExpiredClock.IsPasswordValidForUsername(username, password);

            Assert.False(success);
        }
        public async Task <IActionResult> ResetPasswordAsync(
            string code,
            string email    = "*****@*****.**",
            string password = "******",
            CancellationToken cancellationToken = default
            )
        {
            User user = await UserManager.FindByEmailAsync(email);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "کاربر نا معتبر");
                return(View());
            }

            var passwordHash     = UserManager.PasswordHasher.HashPassword(user, password);
            var newPasswordHash  = PasswordHasher.HashPassword(user, password);
            var newPasswordHash1 = PasswordHasher.HashPassword(user, password);

            var passwordResult = await PasswordValidator.ValidateAsync(UserManager, user, password);

            var newPasswordHash2 = PasswordHasher.HashPassword(user, password);
            await PasswordStore.SetPasswordHashAsync(user, password, cancellationToken);

            IdentityResult result = await UserManager.ResetPasswordAsync(user, code, password);

            if (result.Succeeded)
            {
                return(RedirectToAction(nameof(ResetPassword)));
            }

            foreach (IdentityError error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return(View());
        }
示例#22
0
        /// <summary>
        ///     Remove password of all the files with a list of password
        /// </summary>
        /// <param name="app"></param>
        /// <param name="path"></param>
        /// <param name="store"></param>
        private static void DoDirPassword(Excel.Application app, string path, PasswordStore store)
        {
            Console.WriteLine();
            Console.WriteLine("In path - " + path);

            string[] subPaths = Directory.GetFileSystemEntries(path);
            foreach (string subPath in subPaths)
            {
                if (IsExcelFile(subPath))
                {
                    DoFilePassword(app, subPath, store);
                }
            }
            foreach (string subPath in subPaths)
            {
                if (Directory.Exists(subPath))
                {
                    DoDirPassword(app, subPath, store);
                }
            }

            Console.WriteLine();
            Console.WriteLine("Out path - " + path);
        }
示例#23
0
        public async Task <IActionResult> ResetPasswordAsync(
            string code,
            string email    = "*****@*****.**",
            string password = "******",
            CancellationToken cancellationToken = default
            )
        {
            User user = await UserManager.FindByEmailAsync(email);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "کاربر نا معتبر");
                return(View());
            }

            IdentityResult result = await UserManager.ResetPasswordAsync(user, code, password);

            if (result.Succeeded)
            {
                return(RedirectToAction(nameof(ResetPassword)));
            }

            foreach (IdentityError error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            user.PasswordHash = UserManager.PasswordHasher.HashPassword(user, password);
            var resultt = await UserManager.UpdateAsync(user);

            if (!resultt.Succeeded)
            {
            }
            var token = await UserManager.GeneratePasswordResetTokenAsync(user);

            var resulttt = await UserManager.ResetPasswordAsync(user, token, password);

            var resultttt = await UserManager.ChangePasswordAsync(user, password, password);

            await UserManager.RemovePasswordAsync(user);

            await UserManager.AddPasswordAsync(user, password);

            if (!await UserManager.CheckPasswordAsync(user, password))
            {
                ViewBag.Notification = "Incorrect password ..";
                return(View());
            }
            else
            {
                if (password != password)
                {
                    ViewBag.notification = "try again";
                    return(View());
                }
                else
                {
                    string hashedNewPassword = UserManager.PasswordHasher.HashPassword(user, password);
                    await PasswordStore.SetPasswordHashAsync(user, hashedNewPassword, cancellationToken);

                    await UserManager.UpdateAsync(user);

                    ViewBag.notification = "successful";
                    return(View());
                }
            }

            return(View());
        }
示例#24
0
 public static Config Get(PasswordStore password)
 {
     return(_instance ?? (_instance = Deserialize(password)));
 }
示例#25
0
 public RCloneRunner(string path, PasswordStore password)
 {
     _rclonePath = path;
     _password   = password;
 }
        public async Task <AuthenticationResult <string> > CreateUserAsync(TUser user, string name, string username,
                                                                           string password, string email, CancellationToken cancellationToken)
        {
            // Handle any cancellation
            Handle(cancellationToken);

            // Quick validation of the parameters supplied. Validation of empty strings should be done above as well.
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException(nameof(username));
            }
            if (string.IsNullOrEmpty(nameof(password)))
            {
                throw new ArgumentNullException(nameof(password));
            }
            if (string.IsNullOrEmpty(nameof(email)))
            {
                throw new ArgumentNullException(nameof(email));
            }

            // Validates the parameters
            var validation = await ValidationConfiguration.EmailValidator.ValidateAsync(email, cancellationToken);

            if (!validation.Succeeded)
            {
                return(AuthenticationResult <string> .Invalidate(validation));
            }
            validation = await ValidationConfiguration.UserNameValidator.ValidateAsync(username, cancellationToken);

            if (!validation.Succeeded)
            {
                return(AuthenticationResult <string> .Invalidate(validation));
            }
            validation = await ValidationConfiguration.NameValidator.ValidateAsync(name, cancellationToken);

            if (!validation.Succeeded)
            {
                return(AuthenticationResult <string> .Invalidate(validation));
            }
            validation = await ValidationConfiguration.PasswordValidator.ValidateAsync(password, cancellationToken);

            if (!validation.Succeeded)
            {
                return(AuthenticationResult <string> .Invalidate(validation));
            }
            validation = await ValidationConfiguration.UserValidator.ValidateAsync(user, cancellationToken);

            if (!validation.Succeeded)
            {
                return(AuthenticationResult <string> .Invalidate(validation));
            }

            // Create the id of the new user
            var id = Guid.NewGuid().ToString();

            // All stores that have been modified
            var a = new List <StoreTypes>();

            // Add user in database and retrieve the resulting user
            var queryResult = await UserStore.CreateUserAsync(user, id, username, DateTime.Now, cancellationToken);

            a.Add(StoreTypes.UserStore);
            if (!queryResult.Succeeded || queryResult.RowsModified != 1)
            {
                await Rollback(cancellationToken, a.ToArray());

                return(AuthenticationResult <string> .ServerFault());
            }
            var qUser = queryResult.Result;

            // Add user to email store
            var result = await EmailStore.CreateUserAsync(qUser, email, cancellationToken);

            a.Add(StoreTypes.EmailStore);
            if (!result.Succeeded || result.RowsModified != 1)
            {
                await Rollback(cancellationToken, a.ToArray());

                return(AuthenticationResult <string> .ServerFault());
            }

            //Add user to password store
            var salt = await SecurityConfiguration.RandomProvider.GenerateRandomAsync(cancellationToken);

            var hashed = await SecurityConfiguration.PasswordHasher.HashPassword(password, salt, cancellationToken);

            result = await PasswordStore.CreateUserAsync(qUser, hashed, salt, cancellationToken);

            a.Add(StoreTypes.PasswordStore);
            if (!result.Succeeded || result.RowsModified != 1)
            {
                await Rollback(cancellationToken, a.ToArray());

                return(AuthenticationResult <string> .ServerFault());
            }

            // Start adding the email and configure it to be activated with a link.
            var guid  = Guid.NewGuid().ToString();
            var token = Convert.ToBase64String(
                SecurityConfiguration.TokenProvider.CreateToken(qUser, guid, Security.TokenField.Activation));

            result = await EmailStore.CreateUserAsync(qUser, email, cancellationToken);

            a.Add(StoreTypes.EmailStore);
            if (!result.Succeeded || result.RowsModified != 1)
            {
                await Rollback(cancellationToken, a.ToArray());

                return(AuthenticationResult <string> .ServerFault());
            }

            result = await TokenStore.CreateTokenAsync(qUser, token, cancellationToken);

            a.Add(StoreTypes.TokenStore);
            if (!result.Succeeded || result.RowsModified != 1)
            {
                await Rollback(cancellationToken, a.ToArray());

                return(AuthenticationResult <string> .ServerFault());
            }

            // Email the user with the result
            await EmailConfiguration.AccountVerificationTemplate.LoadAsync(new
            {
                Email = email,
                Token = id
            });

            await EmailConfiguration.EmailProvider.Email(EmailConfiguration.AccountVerificationTemplate, email, cancellationToken);

            // Add a lockout field
            result = await LockoutStore.CreateUserAsync(qUser, cancellationToken);

            a.Add(StoreTypes.LockoutStore);
            if (!result.Succeeded || result.RowsModified != 1)
            {
                await Rollback(cancellationToken, a.ToArray());

                return(AuthenticationResult <string> .ServerFault());
            }

            // Add a potential claims field
            result = await ClaimStore.CreateClaimsAsync(qUser, SecurityConfiguration.DefaultClaims, cancellationToken);

            a.Add(StoreTypes.ClaimStore);
            if (!result.Succeeded || result.RowsModified != SecurityConfiguration.DefaultClaims.Count())
            {
                await Rollback(cancellationToken, a.ToArray());

                return(AuthenticationResult <string> .ServerFault());
            }

            result = await NameStore.CreateUserAsync(qUser, name, cancellationToken);

            a.Add(StoreTypes.NameStore);
            if (!result.Succeeded || result.RowsModified != SecurityConfiguration.DefaultClaims.Count())
            {
                await Rollback(cancellationToken, a.ToArray());

                return(AuthenticationResult <string> .ServerFault());
            }

            await Commit(cancellationToken, a.ToArray());

            return(AuthenticationResult <string> .Success(id));
        }