I'm trying to generate a random password for a user in a Yii2 application.
I have the following code:
$rand_password = Yii::$app->security->generateRandomString(8);
$user->password = Yii::$app->security->generatePasswordHash($rand_password);
After that I save the $user model and the hashed string is also saved in the database. However, I cannot log in with the $rand_password string after that as I'm getting Invalid Password error message.
The generatePasswordHash description says that the hash is generated from the provided password and a random salt string. Indeed, I called the function with the same password string several times in a row and I got different result every time. So my question is, if that salt string is random and different every time, how can I use this function at all to verify passwords? When I try to login I call the same function with the password string provided by the user but this time the salt will be different so I'm unable to produce the same hash as before? What am I missing here?
Well, after hours of debugging and looking for resources and explanation, it turns out the the user module I'm using: https://github.com/amnah/yii2-user is actually automatically hashing the passwords before saving them in the database. In other words, as soon as you call:
$user->password = SOMETHING;
that SOMETHING is automatically going through the generatePasswordHash() function upon save. My problem was that I was dropping it in there in my code as well so basically the password got hashed twice.
Related
I have succeded in hashing my password for my admin user, the problem is now that i can no longer use the original password to log in (no errors, exept the correct response for invalid passwords). I am able to to select the user table and just copy in the hashed password from PGadmin (using PostgreSQL). Im not really sure where to go from here.
1. I think i have to get my login form to recognize the hashed password, and somehow match it up with the original.
2. figure out how to add salt and pepper to the hash
I am not looking for the exact solution, but maybe some hints to get further :)
Code
function createAdmin(){
var usertypeid = null;
const type = "adm";
pool.query(`INSERT INTO usertype(type) VALUES ($1) RETURNING userTypeId;`, [type], function (error, results) {
if (error){
throw error;
} else{
usertypeid = results.rows[0].usertypeid;
console.log(usertypeid);
insertAdmin();
}
});
function insertAdmin(){
pool.query(`
INSERT INTO users(
usertypeid, userName, email, password)
VALUES($1, 'admin', 'admin#admin.com', CRYPT('admin', GEN_SALT('md5')));`, [usertypeid]);
}
}
As mentioned in the comments, don't use MD5 anymore as it's deprecated a long time ago.
The other thing is that hashing is different from encrypting. You can't decrypt a hash like you do with a cipher.
What should happen is that you run the plaintext through the hashing algorithm and then see if it matches the original hash computed at the beginning.
For Node.js there are good libraries out there like bcrypt which can be used to simplify the process and perhaps make it more secure.
If you insist to perform your own validation procedure, then it should be like the following:
Get the user's password from the login form
Run it through the hashing algo of your choice (no MD5 please)
Query the database for the hashed password
Compare if the hashed password from the login form is the same as the one in the DB
As the docs say, you want something like this (renaming table and columns to match your example):
SELECT (password = crypt('entered password', password)) AS pswmatch FROM users where username='admin';
The value stored in users.password from your insertion is a combination of the algorithm, the salt, and result of hashing the actual password with that algorithm and salt. Now you pass users.password into crypt again, so that it can extract from it the algorithm and the salt. It then uses that algorithm and salt to recompute the hash of the alleged password. If the re-computed value matches the stored value, then the alleged password is correct.
I'm creating a flask-app and using wtforms. I have password stored in my database that is created from a form using the following:
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(form.password.data.encode('utf-8'), salt)
Now I want to check the password using:
if bcrypt.checkpw(form.password.data.encode('utf8'), password_from_db):
When I do this the following error arises:
TypeError: Unicode-objects must be encoded before checking
Not sure exactly what is causing this or how to resolve. It is something to do with the form and the data type though as I can follow standard python examples.
Many thanks
EDIT
I've checked this question here but it didn't resolve my query. My query is using data from forms. I'm using the same method as in the answer but am still receiving the error.
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(form.password.data.encode('utf-8'), salt).decode('utf-8')
# While checking:
password_hashed=bcrypt.hashpw(form.password.data.encode('utf8'), password_from_db.encode('utf-8')).decode('utf-8')
if password_hashed == password_from_db:
print('User succesfully logged in')
I would like to have a piece of code that is able to check if a given password match the one stored in the crowd cwd_user table.
The passwords in that table starts with "{PKCS5S2}..." and I found in the link below that crowd is using the PBKDF2 algorithm:
The default is "Atlassian Security", which is currently a dumb wrapper around Bouncy Castle's implementation of PKCS 5 version 2 (aka PBKDF2), using a random 16 byte salt, 10, 000 iterations, and generating a 256-bit hash as the final output
https://answers.atlassian.com/questions/235858/password-security
Is anybody able to provide me a method I can use to match that password?
For example, if I create a user "toto" with password "1234", I get the following row in my database :
user_name credential
------------- -------------------------------------------------------------------------
toto {PKCS5S2}m+u8ed1RKRew3jjHPilZw0ICL6BG/qyeN+kVRRS9nsO+VK7Q5I0vCK3gLvCFWC3n
I would like a method such that:
public String getHash(String rowPassword){
// ?????
}
where
getHash("1234") returns "{PKCS5S2}m+u8ed1RKRew3jjHPilZw0ICL6BG/qyeN+kVRRS9nsO+VK7Q5I0vCK3gLvCFWC3n"
As a Crowd customer, you have access to the class AtlassianSecurityPasswordEncoder which is exactly that.
The underlying encoder chooses a random salt, ignoring the one passed in, so encodePassword won't give you the same hash each time. Use isPasswordValid to confirm that the password and hash match.
i am using Devise and devise_security_extension.
https://github.com/plataformatec/devise
https://github.com/phatworx/devise_security_extension
I tried to figure out how i could validate a provided password WITHOUT updating a User record.
Validation (password was not used before, password is complex enough ....)
For example:
john = User.find(1)
john.password = "Testing"
john.password_confirmation = "Testing"
result = john.save
Result would return true or false. With result.errors i would get the related error messages (Thats exactly what i want but without really change this user password).
My Problem is that this would really change the password of this user (object). That would cause problems with old_passwords.
Is there any way to do a dry run ? (result = john.save_dry_run)
FYI:
I already tried to change the User password and change it back after i got the result. But this is really ugly and also make much trouble with devise old_passwords table.
I hope my question is clear enough. If you need any further information please let me know !
You should call valid? rather than save in your example. This will only run the model validations without actually saving any data to the database:
john = User.find(1)
john.password = "Testing"
john.password_confirmation = "Testing"
result = john.valid?
You can find more information in the Rails documentation.
My company's CRM system utilizes a captcha system at each login and in order to utilize certain administrative functions. The original implementation stored the current captcha value for in a server-side session variable.
We're now required to redevelop this to store all necessary captcha verification information in a hashed client-side cookie. This is due to a parent IT policy which is intended to reduce overhead by disallowing use of sessions for users who are not already authenticated to the application. Thus, the authentication process itself is disallowed from using server-side storage or sessions.
The design was a bit of a group effort, and I have my doubts as to its overall efficacy. My question is, can anyone see any obvious security issues with the implementation shown below, and is it overkill or insufficient in any way?
EDIT: Further discussion has led to an updated implementation, so I've replaced the original code with the new version and edited the description to talk to this revision.
(The code below is a kind of pseudo-code; the original uses some idiosyncratic legacy libraries and structure which make it difficult to read. Hopefully this style is easy enough to understand.)
// Generate a "session" cookie unique to a particular machine and timeframe
String generateSessionHash(timestamp) {
return sha256( ""
+ (int)(timestamp / CAPTCHA_VALIDITY_SECONDS)
+ "|" + request.getRemoteAddr()
+ "|" + request.getUserAgent()
+ "|" + BASE64_8192BIT_SECRET_A
);
}
// Generate a hash of the captcha, salted with secret key and session id
String generateCaptchaHash(captchaValue, session_hash) {
return sha256( ""
+ captchaValue
+ "|" + BASE64_8192BIT_SECRET_B
+ "|" + session_hash
);
}
// Set cookie with hash matching the provided captcha image
void setCaptchaCookie(CaptchaGenerator captcha) {
String session_hash = generateSessionHash(time());
String captcha_hash = generateCaptchaHash(captcha.getValue(), session_hash);
response.setCookie(CAPTCHA_COOKIE, captcha_hash + session_hash);
}
// Return true if user's input matches the cookie captcha hash
boolean isCaptchaValid(userInputValue) {
String cookie = request.getCookie(CAPTCHA_COOKIE);
String cookie_captcha_hash = substring(cookie, 0, 64);
String cookie_session_hash = substring(cookie, 64, 64);
String session_hash = generateSessionHash(time());
if (!session_hash.equals(cookie_session_hash)) {
session_hash = generateSessionHash(time() - CAPTCHA_VALIDITY_SECONDS);
}
String captcha_hash = generateCaptchaHash(userInputValue, session_hash);
return captcha_hash.equals(cookie_captcha_hash);
}
Concept:
The "session_hash" is intended to prevent the same cookie from being used on multiple machines, and enforces a time period after which it becomes invalid.
Both the "session_hash" and "captcha_hash" have their own secret salt keys.
These BASE64_8192BIT_SECRET_A and _B salt keys are portions of an RSA private key stored on the server.
The "captcha_hash" is salted with both the secret and the "session_hash".
Delimiters are added where client-provided data is used, to avoid splicing attacks.
The "captcha_hash" and "session_hash" are both stored in the client-side cookie.
EDIT: re:Kobi Thanks for the feedback!
(I would reply in comments, but it doesn't seem to accept the formatting that works in questions?)
Each time they access the login page, the captcha is replaced; This does however assume that they don't simply resubmit without reloading the login form page. The session-based implementation uses expiration times to avoid this problem. We could also add a nonce to the login page, but we would need server-side session storage for that as well.
Per Kobi's suggestion, an expiration timeframe is now included in the hashed data, but consensus is to add it to the session_hash instead, since it's intuitive for a session to have a timeout.
This idea of hashing some data and including another hash in that data seems suspect to me. Is there really any benefit, or are we better off with a single hash containing all of the relevant data (time, IP, User-agent, Captcha value, and secret key). In this implementation we are basically telling the user part of the hashed plaintext.
Questions:
Are there any obvious deficiencies?
Are there any subtle deficiencies?
Is there a more robust approach?
Is salting the hash with another hash helping anything?
Is there a simpler and equally robust approach?
New question:
I personally think that we're better off leaving it as a server-side session; can anybody point me to any papers or articles proving or disproving the inherent risk of sending all verification data to the client side only?
Assuming no other security than stated here:
It seems an attacker can solve the captcha once, and save the cookie.
She then has her constant session_hash and captcha_hash. Nothing prevents her from submitting the same cookie with the same hashed data - possibly breaking your system.
This can be avoided by using time as part of captcha_hash (you'll need to round it to an even time, possibly a few minutes - and checking for two options - the current time and the previous)
To calrifiy, you said:
The "session_hash" is intended to prevent the same cookie from being used on multiple machines.
Is that true?
On isCaptchaValid you're doing String session_hash = substring(cookie, 64, 64); - that is: you're relying on data in the cookie. How can you tell it wasn't copied from another computer? - you're not hashing the client data again to confirm it (in fact, you have a random number there, so it may not be possible). How can you tell it's new request, and hadn't been used?
I realize the captcha is replaced with each login, but how can you know that when a request was made? You aren't checking the new captcha on isCaptchaValid - your code will still validate the request, even if it doesn't match the displayed captcha.
Consider the following scenario (can be automated):
Eve open the login page.
Gets a new cookie and a new captcha.
Replaces it with her old cookie, with hashed data of her old cptcha.
Submits the old cookie, and userInputValue with the old captcha word.
With this input, isCaptchaValid validates the request - captcha_hash, session_hash, userInputValue and BASE64_8192BIT_SECRET are all the same as they were on the first request.
by the way, in most systems you'll need a nonce anyway, to avoid XSS, and having one also solves your problem.