Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Code Review for Auth Flaws

MediumCoding00:00
Practice interviewer
In session
5 left
00:00

Your question is Code Review for Auth Flaws. Take a moment with it on the right.

Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).

You need to log in / sign up to chat or submit.

Problem

Ankercloud is reviewing a customer's cloud console login code as part of a security assessment. Here is the authentication and password-reset logic in question.

import hashlib
import sqlite3

def authenticate_user(username, password):
    conn = sqlite3.connect("users.db")
    cursor = conn.cursor()

    query = "SELECT id, password_hash FROM users WHERE username = '" + username + "'"
    cursor.execute(query)
    row = cursor.fetchone()

    if row is None:
        return False

    hashed = hashlib.md5(password.encode()).hexdigest()

    if hashed == row[1]:
        session_token = username + "_" + str(row[0])
        print("Login successful, token: " + session_token)
        return True

    return False


def reset_password(username, new_password):
    conn = sqlite3.connect("users.db")
    cursor = conn.cursor()
    hashed = hashlib.md5(new_password.encode()).hexdigest()
    cursor.execute("UPDATE users SET password_hash = ? WHERE username = ?", (hashed, username))
    conn.commit()
    return True

Review this snippet of Python code handling user authentication. What security flaws can you find, and how would you fix them?