# Security

## Password Storage

Here is an overview of how user passwords are currently being stored in Plinth.

### Storing a password (add_user function in auth module):

1. We check if the username or password is empty. If so, return an error message.

2. Use bcrypt (from passlib) to hash the password with a random salt. bcrypt returns the hash in the format:

  $2a$<base 10 number of rounds>$<22-character salt><31-character checksum>

This hashed string will be used in step 5.

3. If the password length is over 4096, bcrypt raises an exception. We catch this exception and return an error message.

4. Check if the username exists in user store. If so, return an error message.

5. If no error has occurred so far, create the new user. The username, hashed password, and salt are stored in the user store database. The salt is a substring of the hash output by bcrypt.

### Checking password at login (check_credentials function in auth module):

1. We check if the username or password is empty. If so, return an error message.

2. Use bcrypt to hash the supplied password. This step is performed regardless of whether the user already exists. If the user exists, use the salt value stored for that user in the database, otherwise, a random salt is used.

3. If the password length is over 4096, bcrypt raises an exception. We catch this exception and return an error message.

4. Check if the user doesn't exist, or if the hashed password doesn't match the stored hash. Return an error message "Bad user-name or password" if either of these conditions are true.

5. If no error has occurred so far, return None to indicate that the supplied credentials are valid.
