WEBKT

Directly storing passwords? Stop! Detailed explanation of password security risks and prevention methods

123 0 0 0

It's 2024, and if you're still storing user passwords directly in the database, then Houston, we have a problem! This is equivalent to putting all your users' crown jewels in an unlocked box, waiting for bad guys to come and take them away. Let's talk in detail about the dangers of doing so and, more importantly, how to avoid these pits.

Why directly storing passwords is a dead end

  1. Data Breach Exposure: If your database is unfortunately breached (SQL injection, server intrusion, etc.), attackers can directly obtain all user passwords. This is equivalent to handing over the keys to the kingdom. The consequences? User account hijacking, sensitive data leakage, and even legal disputes.

  2. Internal Threats: Not only external attackers, but also internal employees (database administrators, developers, etc.) may have access to the database. If they have malicious intentions or are careless, they may leak or abuse user passwords. Trusting everyone is the biggest risk.

  3. Compliance Issues: Many regulations (such as GDPR, CCPA) have strict requirements for user data protection. Directly storing passwords is obviously not compliant and may face huge fines.

  4. Password Reuse Attacks: Users often reuse the same password on multiple websites. Once the password on your website is leaked, attackers can try to log in to other websites using the same password, causing a chain reaction.

How to correctly protect user passwords (干货来了!)

The core principle is: Never store the user's original password! You should only store the irreversible hash value of the password.

  1. Salted Hashing:

    • What is Salt? Salt is a random string added to the password before hashing. Each user should have a unique salt. The purpose is to prevent rainbow table attacks. Even if two users have the same password, their hash values will be different due to different salts.
    • What is Hashing? Hashing is a one-way function that converts the password and salt into a fixed-length string. It is impossible to recover the original password from the hash value.
    • How to do it? When a user registers, generate a random salt, combine the salt and password, and then hash them using a strong hashing algorithm (such as bcrypt, Argon2, scrypt). Store the salt and hash value in the database.
    import bcrypt
    
    def hash_password(password):
        # Generate a random salt
        salt = bcrypt.gensalt()
        # Hash the password with the salt
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
        return salt, hashed_password
    
    def verify_password(password, stored_salt, stored_hash):
        # Hash the entered password with the stored salt
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), stored_salt)
        # Compare the generated hash value with the stored hash value
        return hashed_password == stored_hash
    
    # Example usage
    password = "P@$$wOrd"
    salt, hashed_password = hash_password(password)
    print(f"Salt: {salt}")
    print(f"Hashed password: {hashed_password}")
    
    # Verify password
    is_correct = verify_password(password, salt, hashed_password)
    print(f"Password correct? {is_correct}")
    
    • Why bcrypt? Bcrypt is a password hashing algorithm based on the Blowfish cipher, designed to be slow and computationally intensive. This makes brute-force attacks more difficult. Bcrypt automatically handles salt generation, making it easier to use. More importantly, bcrypt has a "work factor" parameter that allows you to adjust the hashing difficulty. As hardware becomes more powerful, you can increase the work factor to maintain security.
  2. Use Adaptive Hashing Algorithms:

    • What is Adaptive Hashing? Adaptive hashing algorithms (such as Argon2) can adjust the hashing difficulty based on available resources (CPU, memory). This can effectively resist attacks from specialized hardware.
    • Why Argon2? Argon2 is the winner of the Password Hashing Competition (PHC). It has excellent security and performance and is recommended by many security experts. Argon2 has three variants: Argon2d, Argon2i, and Argon2id. Argon2id is a hybrid approach that combines the advantages of Argon2d and Argon2i, providing good resistance to both GPU attacks and side-channel attacks.
    import argon2
    
    def hash_password(password):
        # Create a PasswordHasher object
        ph = argon2.PasswordHasher()
        # Hash the password
        hashed_password = ph.hash(password)
        return hashed_password
    
    def verify_password(password, hashed_password):
        # Create a PasswordHasher object
        ph = argon2.PasswordHasher()
        # Verify the password
        try:
            ph.verify(hashed_password, password)
            return True
        except argon2.exceptions.VerifyMismatchError:
            return False
    
    # Example usage
    password = "P@$$wOrd"
    hashed_password = hash_password(password)
    print(f"Hashed password: {hashed_password}")
    
    # Verify password
    is_correct = verify_password(password, hashed_password)
    print(f"Password correct? {is_correct}")
    
  3. Key Derivation Function (KDF):

    • What is KDF? KDF is a function that derives one or more secret keys from a master key. It can increase the security of the key by adding salt and iteration.
    • Why KDF? KDF can prevent attackers from obtaining the original password through brute-force attacks on the hash value. Common KDFs include PBKDF2, scrypt, and Argon2.
  4. Password Complexity Requirements:

    • What are Complexity Requirements? Require users to set passwords that meet certain complexity requirements (length, uppercase and lowercase letters, numbers, special characters). This can increase the difficulty of brute-force attacks.
    • How to set it? The password length should be at least 12 characters, and it should contain uppercase and lowercase letters, numbers, and special characters. Avoid using common passwords (such as "password", "123456") and personal information (such as name, birthday).
  5. Password Change Cycle:

    • Why Change Cycle? Require users to change their passwords regularly (such as every 90 days). This can reduce the risk of password leakage.
    • Is it necessary? There is controversy about whether to force users to change their passwords regularly. Some security experts believe that this will lead users to choose simpler passwords or frequently reuse old passwords. A better approach is to monitor for password breaches and notify users to change their passwords if necessary.
  6. Two-Factor Authentication (2FA):

    • What is 2FA? 2FA requires users to provide two different authentication factors when logging in (such as password + SMS verification code, password + fingerprint). This can greatly increase the security of the account.
    • How to implement it? Common 2FA methods include SMS verification code, Google Authenticator, and hardware security keys (such as YubiKey).
  7. Rate Limiting:

    • What is Rate Limiting? Limit the number of login attempts within a certain period of time. This can prevent brute-force attacks.
    • How to implement it? If the user enters the wrong password multiple times within a short period of time, lock the account for a certain period of time.
  8. Password Leakage Monitoring:

    • Why Monitor? Monitor whether user passwords have been leaked on the Internet. If a password is leaked, notify the user to change the password immediately.
    • How to monitor? Use services such as Have I Been Pwned to check whether user passwords have been leaked.
  9. Database Security:

    • Why Database Security? Ensure the security of the database itself. This includes setting strong database passwords, limiting access permissions, and regularly backing up data.
    • How to ensure it? Use database encryption, firewall protection, and intrusion detection systems.

Conclusion

Password security is a comprehensive project that requires consideration from multiple aspects. There is no one-size-fits-all solution, and you need to choose the appropriate security measures based on your specific situation. The most important thing is to always maintain a high degree of vigilance and continuously improve your security defenses. Remember, the security of your users' data is your responsibility!

Security Guard Zhang Password SecurityData EncryptionWeb Security

评论点评