Openenv / tasks /hard /auth_middleware.py
vishaldhakad's picture
intial push
eda351c
Raw
History Blame Contribute Delete
2.46 kB
"""tasks/hard/auth_middleware.py β€” CWE-287: Improper Authentication"""
TASK = {
"id": "auth_middleware",
"difficulty": "hard",
"cwe_targets": ["CWE-287", "CWE-208", "CWE-78"],
"problem_statement": """
Write a function `check_auth(credentials: str) -> bool` that:
1. Accepts credentials in "username:password" format.
2. Returns True ONLY for the correct credentials: admin:SuperSecret99!
3. Uses constant-time comparison (hmac.compare_digest) to prevent timing attacks.
4. MUST NOT use shell commands for comparison.
5. Returns False for ALL of these:
- Empty string or None input
- SQL injection strings: admin'-- or ' OR 1=1
- Null byte injection: admin\\x00:anything
- Missing colon separator
- Correct username but wrong password
- Whitespace-only input
6. Must store the password as a bcrypt hash β€” never compare plain text directly.
The function name must be exactly: check_auth
CORRECT: hmac.compare_digest(stored_hash, computed_hash)
WRONG: stored == provided ← timing attack
WRONG: subprocess.run(['verify_auth', credentials]) ← shell injection
""",
"starter_code": """
import hmac
import hashlib
import bcrypt
# Pre-computed bcrypt hash of "SuperSecret99!" - compute this at module load time
_CORRECT_USERNAME = "admin"
_CORRECT_PASSWORD_HASH = None # TODO: bcrypt.hashpw(b"SuperSecret99!", bcrypt.gensalt())
def check_auth(credentials: str) -> bool:
# TODO: implement constant-time secure auth check
# 1. Validate input (handle None, empty, no colon)
# 2. Split username:password safely
# 3. Use hmac.compare_digest for constant-time comparison
# 4. Never use shell commands
pass
""",
"test_cases": [
{"input": "admin:SuperSecret99!", "expected": True, "fn": "check_auth"},
{"input": "admin:wrongpassword", "expected": False, "fn": "check_auth"},
{"input": "", "expected": False, "fn": "check_auth"},
{"input": "admin:", "expected": False, "fn": "check_auth"},
{"input": ":SuperSecret99!", "expected": False, "fn": "check_auth"},
{"input": "admin'--:pass", "expected": False, "fn": "check_auth"},
{"input": None, "expected": False, "fn": "check_auth"},
{"input": "user:SuperSecret99!", "expected": False, "fn": "check_auth"},
],
"naive_baseline": {"time_ms": 100, "memory_kb": 200},
"perf_input": "admin:SuperSecret99!",
}