Preventing Timing Attacks in Axion's Login Route with Dummy Hashes
Hey guys! 👋🏻
I wanted to share a good security fix I applied to my microforum, Axion. It's about stopping attackers from finding out which usernames exist through timing attacks.
Why Timing Attacks Happen in Login Routes. When you're building a login route for a platform like Axion, the normal flow looks simple: find the user by their username, and if they exist, compare the password they typed with their saved hash.
The problem is that password hashing takes heavy CPU work. Because of that, an attacker can measure how long each login request takes to finish, and two different things happen:
- Wrong username: There is no hash to compare, so the server uses less CPU time. This gives a faster response, which tells the attacker the username doesn't exist.
- Right username: There is a password hash to compare, so the server uses more CPU time. This gives a slower response, which tells the attacker the username exists.
Just by checking the time difference between login requests, an attacker can figure out which accounts are real. 🙃
My Fix: Calculating a Dummy Hash. The fix was pretty simple. Instead of returning an error right away when a username isn't found, I force the server to calculate and compare a dummy hash anyway:
export async function login(req, res) { const { username, password } = req.data; const user = await models.Users.findOne({ username }).select("password").lean(); // The constant variable is declared at the top of the file! const hash = user ? user.password : DUMMY_HASH; const isMatch = await bcrypt.compare(password, hash); if (!user || !isMatch) { return res.status(401).json({ error: errors.INVALID_CREDENTIALS() }); } await initSession(req, user._id); return res.status(200).json({ success: true }); } The cool part about this fix is that both cases now do the exact same amount of CPU work. Whether the username is right or wrong, the response takes the same time, so the attacker can't use timing differences to guess valid usernames anymore.
How do you keep your login routes safe from timing attacks? Let's talk in the comments below. See you next time! 🌟