In this video, we are going to implement login and logout functionality in our app. At a high level, the authentication flow goes like this. When the user signs in, we validate their email address and password, match them with a user in our database, create a session in cache, and issue a session cookie. When the user logs out, we destroy the session and unset the cookie. Both routes should be behind guest and auth middleware respectively, since only a guest should be able to log in and only a logged in user can sign out.
One security flaw that we will highlight is the time difference between querying a user document and matching its hash with the password. Our if-conditional will first check if the user document is falsy, and if it is, that is MongoDB couldn’t match the email with any existing user, then it will skip the second check and throw an exception early. However, if the email was found, it will compare the user’s hash with the given password using bcrypt, and because hashing consumes many CPU cycles, the server would take up more time to respond. The delta is only a few hundred milliseconds, but it’s enough for an attacker to infer that that particular email and password combination triggered a separate logical branch.
As such, this conditional code although more efficient due to the early exit is also prone to a timing attack. By measuring the deltas of response times, an attacker could determine whether any given email address exists in our database. This attack is partly mitigated with rate limiting, though a proper fix would be to make response times constant. In other words, if the user was not found, you may still want to compare the input password with a sample hash, so as to consume the remaining time. This way, if you return a generic error message, the client won’t be able to deduce any information from the response times, since they would fall within the same range. Do note that timing attacks may not always be a grave concern in distributed systems https://security.stackexchange.com/q/222765
GitHub repo https://github.com/alex996/node-auth
source by Code Realm