Secure Coding and Application Security Questions
Writing and reviewing code that resists attack. Covers the OWASP Top Ten and common web vulnerabilities (XSS, SQL injection, CSRF), input validation, secure coding practices and security code review, static application security testing (SAST), API and HTTP security, database and frontend security, and mobile app security. The application-layer defense discipline for engineers building software.
List and explain the most important cookie and session flags and properties to check when testing session management: HttpOnly, Secure, SameSite, session-ID entropy and rotation on login, and appropriate expiration. Explain what an attacker gains if each protection is missing.
Sample Answer
Direct answer
When testing session management, check six things on the session cookie itself: the HttpOnly flag, the Secure flag, the SameSite attribute, how random (high-entropy) the session identifier is, whether it rotates on login, and whether the session actually expires in a reasonable window. Each one blocks a distinct attack path, so each is checked independently rather than assuming one strong control compensates for a missing one.
Structured elaboration
| Property | What it does | What an attacker gains if it's missing |
|---|---|---|
HttpOnly | Prevents JavaScript running on the page from reading the cookie's value | If there is any cross-site scripting (XSS) vulnerability anywhere on the site, injected script can read document.cookie, exfiltrate the session cookie to an attacker-controlled server, and hijack the session directly. Missing HttpOnly turns an XSS bug into full session takeover instead of a more limited page-defacement issue. |
Secure | Tells the browser to only ever send the cookie over an HTTPS connection, never plain HTTP | On any network where traffic can be intercepted (public Wi-Fi, a compromised router, an on-path attacker), a session cookie sent over plaintext HTTP, even if the site is normally accessed over HTTPS, can be captured and replayed. This matters even on HTTPS-only sites, because a stray HTTP link or a mixed-content resource can still trigger a plaintext send if Secure is not set. |
SameSite (Strict, Lax, or None) | Controls whether the browser attaches the cookie to requests originating from a different site | Without a restrictive SameSite value, a cross-site request forgery (CSRF) attack, where a malicious page on another site causes the victim's browser to submit a request to the target site, still carries the victim's session cookie, letting the forged request execute as the logged-in user. SameSite=None is sometimes required for legitimate cross-site flows, but it needs the Secure flag and a genuine CSRF-token defense alongside it. |
| Session-ID entropy | How unpredictable the identifier is, so it cannot be guessed or brute-forced | A session identifier generated with a weak or predictable source (a sequential counter, a hash of a low-entropy value like a timestamp, a short identifier) can be guessed or enumerated by an attacker, who can then simply present a guessed valid identifier and be treated as that user, without ever needing to steal anything. |
| Rotation on login | Issues a new session identifier at the moment of authentication (and, ideally, on logout and privilege escalation) | Without rotation, an attacker who can plant or capture a session identifier before the victim authenticates (a session fixation attack) finds that identifier still valid and now authenticated after the victim logs in, letting the attacker use the same identifier to access the account. |
| Appropriate expiration | Bounds how long a session identifier remains valid, both an idle timeout and an absolute maximum lifetime | A session that never expires, or expires only after an unreasonably long window, means a stolen or abandoned session identifier (a logged-in session left open on a shared or public computer, a captured cookie from months ago) stays usable indefinitely, giving an attacker a much longer window to exploit it. |
Worked example
Testing a target application's session cookie by inspecting the Set-Cookie header returned after login:
Set-Cookie: session=a1b2c3; Path=/
Working through the checklist against this single header already surfaces several findings: no HttpOnly (any XSS on the site can read this cookie via JavaScript), no Secure (it will be sent over plain HTTP if the site is ever reached that way), no SameSite attribute (defaults vary by browser, but explicitly setting it is the only way to be sure of the behavior, and this cookie does not), and the identifier a1b2c3 is short and looks like it could be sequential or otherwise low-entropy, worth testing further by requesting several sessions in a row and checking whether the values follow a discoverable pattern. Separately, logging in twice in a row and comparing the session identifier before and after authentication reveals whether it rotates, and leaving a session idle (or checking documentation/behavior for an absolute session lifetime) reveals whether expiration is enforced.
A properly hardened equivalent:
Set-Cookie: session=8f2e91acb4d67a1e3c9f0d5b2a7e4f1c; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=1800
Here the identifier is long and appears random, HttpOnly blocks script access, Secure restricts transmission to HTTPS, SameSite=Strict blocks cross-site request attachment, and Max-Age=1800 bounds the cookie to 30 minutes measured from when the browser received it. Note that Max-Age is an absolute browser-side lifetime, not an idle timeout: unless the server re-issues the cookie on every response, continued activity does not extend it, and either way the server has to enforce its own idle and absolute limits independently, since the browser-side value only governs when the browser stops sending the cookie. Confirming rotation on login still requires an active test (comparing the pre- and post-authentication cookie values), since it is not visible from a single header.
Trade-offs and pitfalls
- Checking flags without checking behavior. The presence of
SameSite=Strictin a header is easy to verify by inspection; whether the session identifier actually rotates on login, or whether expiration is genuinely enforced server-side and not just suggested by aMax-Agevalue the server ignores, requires exercising the application, not just reading response headers. SameSite=Laxas a default, not a considered choice. Many frameworks now default new cookies toSameSite=Lax, which blocks most cross-site POST-based CSRF but still allows the cookie on top-level navigation (a link click), which is enough for some attack variants; treat the default as a reasonable baseline to verify, not as proof the application is intentionally protected.- Relying on
SameSitealone as CSRF protection. Browser support and edge-case behavior (subdomains, certain redirect chains) makeSameSitea strong layer, not a complete replacement for an explicit CSRF token, especially for an application that must support older or unusual clients. - High entropy alone does not fix a fixation vulnerability. A perfectly random, unguessable session identifier is still exploitable if the application never rotates it at login; entropy defends against guessing, rotation defends against a known-but-unauthenticated identifier being reused. They are independent controls addressing different attack paths.
- Expiration set too long "for user convenience." A long-lived session is a common, deliberate business trade-off (fewer login prompts), but it should be a considered decision weighed against the sensitivity of what the session protects, not a default left unexamined; a banking application and a low-stakes content site have very different reasonable answers here.
A JSON-based API echoes a user-supplied parameter into a JavaScript client response inside a single-page application. Describe how you would test for DOM-based XSS: what instrumentation you would use (browser devtools, a Burp extension, automated DOM-sink scanning), a safe proof-of-concept payload skeleton, and how you would triage and classify the finding.
Sample Answer
Direct answer: Testing for DOM-based XSS means tracing the path from an attacker-controllable "source" (a URL parameter, location.hash, document.referrer, a postMessage payload) through the application's JavaScript to a dangerous "sink" (innerHTML, document.write, eval, setAttribute('onclick', ...)) and confirming the browser actually executes injected script when that path is exercised, since the server-side response here is only the messenger, not the vulnerable code.
Instrumentation and approach:
- Browser devtools first: open the page, search the rendered DOM and the page's JavaScript sources for the API in the response (here, the SPA reads a JSON API response and writes a field into the page). Set a DOM breakpoint ("break on subtree modification") on the container element, or use the Sources panel to step through the render function and see exactly which sink receives the value.
- Automated DOM-sink scanning: tools like a Burp Suite extension (e.g. DOM Invader) or a headless-browser crawler that hooks
innerHTML/document.write/evalat the JS engine level and reports every reachable source-to-sink flow, which is far faster than manually reading minified bundles. - Manual confirmation with a benign marker payload: before trying anything that executes, submit a distinctive string like
XSSPROBE12345as the parameter and confirm via devtools exactly where and how it lands in the DOM (as text, as an attribute, inside a script block). This tells you which encoding context you're up against before you craft a working payload.
Worked example / safe PoC skeleton. If the API response field is written via element.innerHTML = data.username, a proof-of-concept payload is <img src=x onerror=alert(document.domain)> submitted as the username - innerHTML parses this as real markup, the broken src triggers onerror, and alert(document.domain) fires, which is safe (no data exfiltration) but conclusively proves script execution. For a production engagement, swap alert(document.domain) for a non-destructive callback to a controlled logging endpoint you own, so you get a timestamped hit log rather than a visible popup that could alarm real users if the payload somehow reaches one.
Triage and classification once confirmed: record the exact source (which parameter/API field), the exact sink (which DOM write), and whether any encoding or sanitizer sits between them (many teams have a sanitizer library available but simply didn't call it on this particular field). Classify severity by what an attacker gains: session-cookie theft is high severity even without HttpOnly bypass tricks, since most SPAs also keep sensitive data in memory/localStorage that JavaScript CAN read directly.
Trade-offs and pitfalls: minified/bundled production JavaScript makes manual source-reading slow; work from source maps if available, or from the unminified dev build. A payload that works in Chrome devtools may be blocked by the site's CSP in production, so validate against the actual deployed headers, not just the sink's existence, before reporting severity. And a sink alone is not a finding: if the value is hard-coded or only ever set from a trusted internal source, there's no reachable "source," so always confirm the taint actually originates from something the attacker can control.
You identify a timing side-channel in a custom authentication routine that allows username enumeration and speeds up brute-force attacks. Implement a secure credential-comparison function in Python that mitigates timing attacks (constant-time comparison), and show how you would integrate rate limiting and account lockout to further protect the authentication endpoint. Describe how you would test your own implementation to confirm the timing leak is actually closed, and how these mitigations trade off against latency at high request volume.
Sample Answer
Direct answer
Fix the comparison first with hmac.compare_digest, which the standard library already implements in constant time, never a hand-written byte loop. But the comparison is only half of it: the supplied password must first go through the same key-derivation function as the stored credential, so what you compare is derived digest against derived digest, never a raw password against a stored hash. That closes the timing side-channel on the comparison itself, but rate limiting and account lockout are still required as a second, independent layer, because they defend against brute-force volume generally, not just this one side-channel. Confirming the leak is closed is a code-review and construction argument, not a benchmark: at meaningful request volume, the comparison's own cost is not the thing worth measuring.
Structured elaboration
The comparison function. Python's hmac.compare_digest is the correct tool: it is implemented in C specifically to always inspect every byte of both inputs before returning, so two candidate secrets of the same length take the same number of comparison steps regardless of where they first diverge. Do not write a manual for loop that XORs bytes and accumulates a result, and do not use == on the raw strings: Python's == on strings short-circuits at the first mismatching character, which is precisely the timing signal an attacker exploits to recover the secret one byte (or even one bit) at a time. Two things it is NOT: it is not a substitute for hashing (the supplied password goes through PBKDF2, bcrypt or Argon2id with the stored salt first, and the digest that comes out is what gets compared), and it is not a defense against the unknown-username path returning early. When the lookup itself fails, run the same derivation against a fixed dummy salt and compare against a fixed dummy digest, since correctly rejecting an unknown username with less work than a known one reopens the same class of leak at the username-enumeration level instead of the password level. With a deliberately slow KDF this matters far more than the compare does: the derivation costs milliseconds and the comparison costs microseconds, so an early return on unknown usernames is trivially visible over the network.
Rate limiting and account lockout. Constant-time comparison closes the timing channel but does nothing to slow down an attacker simply firing thousands of guesses per second, so a per-account attempt counter with a sliding time window is a required second control: track failed attempts per username within a window, and after a threshold, lock the account for a cooldown period regardless of whether the next guess would have been correct. This needs to run in shared state (a cache like Redis with atomic increment-and-expire) across every application instance in production, or each instance undercounts independently and an attacker distributes guesses across instances to stay under each one's individual threshold.
Testing methodology to confirm the leak is closed. Do not rely on ad-hoc wall-clock timing in a shared, virtualized environment: system noise (scheduler jitter, CPU frequency scaling, other tenants) routinely swamps the microsecond-scale differences a real timing side-channel produces, so a benchmark that "looks flat" is not strong evidence the code is safe, and a benchmark that shows a difference might just be measurement noise. Two checks that do work. First, structural: confirm by code inspection (or, better, a linting rule flagging == on any variable that flows from a password/token/secret comparison) that every credential comparison in the codebase routes through hmac.compare_digest or an equivalent constant-time primitive, and add a unit test asserting the function is actually called (for example, patching it and asserting the patched version is invoked) rather than trying to reprove constant-time behavior experimentally on every CI run. Second, if you do want an empirical check, use a leakage-detection method rather than a naive A/B benchmark: interleave the two input classes randomly in one process, collect tens of thousands of samples, discard outliers and apply a Welch t-test to the trimmed distributions (this is what the dudect methodology does). Treat that as a leak DETECTOR, not a safety proof: it can show you have a problem, it cannot show you do not. hmac.compare_digest's constant-time property is itself already established and maintained by CPython; your job is verifying you actually call it everywhere a secret is compared.
Latency trade-off at high request volume (100k req/s). At a sustained 100,000 requests per second, the constant-time comparison itself is not where the cost lives: hmac.compare_digest on typical hash-length inputs runs in low single-digit microseconds, which is negligible against the rest of a request's latency budget. The dominant per-request cost on the login path is the password KDF itself, deliberately so: a PBKDF2 at 200k iterations or an Argon2id at a sane memory cost is in the tens-of-milliseconds range, three to four orders of magnitude above the comparison, which is exactly why the login path needs its own capacity planning and why the unknown-username dummy derivation is not free. The other real cost at that scale is the rate limiter's shared state: a naive design that does a synchronous round-trip to a central store on every single request turns your rate limiter into the bottleneck and a single point of failure for the entire login path. The standard mitigation is a two-tier design, an in-process token bucket per instance for the common case, backed by periodic, asynchronous reconciliation against the shared store, so most requests are decided locally and the shared store only needs to handle aggregation traffic rather than a synchronous check on every login attempt.
Worked example
import hashlib
import hmac
PBKDF2_ITERATIONS = 200_000
def derive(password: str, salt: bytes) -> bytes:
"""Turn a supplied password into a comparable digest. The KDF is
deliberately slow, and it is what makes an offline attack on a stolen
database expensive. Never compare a raw password against a stored value:
the stored value must be a derived digest, and the supplied password must
go through the same derivation before anything is compared."""
return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt,
PBKDF2_ITERATIONS)
def secure_compare(a: bytes, b: bytes) -> bool:
"""Constant-time comparison for secrets (derived password digests, session
tokens, HMAC signatures). hmac.compare_digest walks every byte of both
inputs and only returns after comparing the full length, so equal-length
secrets take the same number of comparison steps regardless of where the
first mismatch is. It is CPython's C-implemented answer to this exact
problem; do not write your own byte-loop, since compiler/interpreter
optimizations can silently reintroduce an early exit."""
return hmac.compare_digest(a, b)
DUMMY_SALT = b"\x00" * 16
DUMMY_DIGEST = derive("unused-dummy-password", DUMMY_SALT)
class LoginThrottle:
"""Per-account rate limit + lockout tracker. Single-process demo only:
production needs this backed by shared state (e.g. Redis INCR + TTL) or
every app instance undercounts independently."""
def __init__(self, max_attempts=5, window_seconds=60, lockout_seconds=300):
self.max_attempts = max_attempts
self.window_seconds = window_seconds
self.lockout_seconds = lockout_seconds
self._attempts = {} # username -> [timestamp, ...]
self._locked_until = {} # username -> unlock timestamp
def is_locked(self, username, now):
until = self._locked_until.get(username)
return until is not None and now < until
def record_failure(self, username, now):
attempts = self._attempts.setdefault(username, [])
attempts[:] = [t for t in attempts if now - t < self.window_seconds]
attempts.append(now)
if len(attempts) >= self.max_attempts:
self._locked_until[username] = now + self.lockout_seconds
attempts.clear()
def record_success(self, username):
self._attempts.pop(username, None)
self._locked_until.pop(username, None)
def authenticate(username, supplied_password, credential_lookup, throttle, now):
"""credential_lookup(username) -> (salt, stored_digest) or None."""
if throttle.is_locked(username, now):
return False, "locked"
record = credential_lookup(username)
if record is None:
# Run the SAME derivation against a dummy salt and compare against a
# dummy digest. Skipping the KDF for unknown usernames is the real
# enumeration oracle here: the derivation costs milliseconds and the
# comparison costs microseconds, so an early return would be trivially
# visible over the network.
secure_compare(derive(supplied_password, DUMMY_SALT), DUMMY_DIGEST)
throttle.record_failure(username, now)
return False, "invalid"
salt, stored_digest = record
if secure_compare(derive(supplied_password, salt), stored_digest):
throttle.record_success(username)
return True, "ok"
throttle.record_failure(username, now)
return False, "invalid"
if __name__ == "__main__":
alice_salt = b"\x11" * 16
users = {"alice": (alice_salt, derive("correct horse battery", alice_salt))}
def lookup(u):
return users.get(u)
digest = derive("correct horse battery", alice_salt)
assert secure_compare(digest, digest) is True
assert secure_compare(digest, derive("wrong", alice_salt)) is False
assert secure_compare(b"short", b"short") is True
assert secure_compare(b"short", b"shortx") is False
throttle = LoginThrottle(max_attempts=3, window_seconds=60, lockout_seconds=300)
t = 1_000_000.0
ok, reason = authenticate("alice", "correct horse battery", lookup, throttle, now=t)
assert (ok, reason) == (True, "ok")
ok, reason = authenticate("nobody", "anything", lookup, throttle, now=t)
assert (ok, reason) == (False, "invalid")
for i in range(3):
ok, reason = authenticate("alice", "wrong", lookup, throttle, now=t + i)
assert reason == "invalid"
assert throttle.is_locked("alice", now=t + 3) is True
ok, reason = authenticate("alice", "correct horse battery", lookup, throttle, now=t + 3)
assert (ok, reason) == (False, "locked")
ok, reason = authenticate("alice", "correct horse battery", lookup, throttle,
now=t + 3 + 301)
assert (ok, reason) == (True, "ok")
print("ALL ASSERTIONS PASSED")
Running this script prints ALL ASSERTIONS PASSED. It exercises: secure_compare returning True/False correctly for matching, mismatching, and different-length inputs; a full successful login where the supplied password is derived with the stored salt before any comparison happens; an unknown-username rejection that pays the same KDF cost as a known one; tripping the lockout after three failed attempts against a real account; confirming a correct password is still rejected while locked (reason == "locked", not "invalid"); and confirming the account is usable again once the lockout window has elapsed. None of these assertions measure timing, they measure functional correctness of the derive-then-constant-time-compare, rate-limit, and lockout logic working together, which is the honest, reproducible thing to assert about this code.
Trade-offs and pitfalls
A hard lockout after N failed attempts is itself abusable: an attacker who does not care about gaining access, only about denying it to the legitimate user, can deliberately trigger lockouts by submitting a few wrong guesses against a known username. Consider a lockout that only affects the specific client/IP context that failed, or that degrades to a rising delay (exponential backoff) plus a CAPTCHA challenge rather than a hard account-wide lock, which slows an attacker without fully denying the legitimate user.
Treating the constant-time comparison as the whole fix is the most common gap. It stops one specific side-channel (response-time leakage on comparison) and it silently does nothing if the code around it compares a raw password against a stored digest, skips the KDF on the unknown-username path, or uses a hashing step whose runtime varies with the input (Argon2id and bcrypt are designed to take consistent time for a given configuration regardless of the password's content, but a custom or misconfigured hashing step could reintroduce variability upstream of the comparison).
Rate-limiting state that lives only in application memory (not the shared cache described above) silently stops working the moment you scale past one instance, and it fails in the dangerous direction, permissively, not by locking everyone out, which makes it easy to miss in testing on a single dev instance and only discover in production under real distributed load.
Describe Cross-Site Request Forgery (CSRF). For a stateless REST API used by a single-page application, outline three practical defenses you would implement (both code and configuration), explain the trade-offs of each, and state how you would test the effectiveness of your chosen defense during a penetration test.
Sample Answer
Direct answer: For a stateless REST API used by a single-page application, CSRF defenses need to account for the fact that "stateless" often isn't fully true (a refresh-token cookie may still be in play); the three practical defenses are SameSite cookies, an anti-CSRF token via the double-submit pattern, and requiring a custom header the browser won't auto-attach cross-site.
Structured elaboration - three defenses with trade-offs.
SameSite=StrictorLaxon any auth-related cookie. Trade-off: this is free (a one-line config change) and effective against the majority of real-world CSRF attempts, butStrictcan break a legitimate cross-site entry flow (a user following a link from an email lands unauthenticated), and it only protects browsers that support and respect the attribute (essentially all modern ones now, but a defense-in-depth mindset shouldn't rely on it alone for a high-value target).- Double-submit cookie / anti-CSRF token echoed in a custom header. The server sets a token as a cookie; the SPA's own JavaScript reads that cookie value (via
document.cookie, since it's notHttpOnly) and includes it in a custom request header (e.g.X-CSRF-Token) on every state-changing call. Trade-off: effective and framework-agnostic, but requires the token cookie to be readable by JavaScript, which means it can't also beHttpOnly- so this specific cookie should carry no sensitive value beyond the token itself, never double as the actual session identifier. - Requiring a custom header at all (even without validating its specific value) as a cheap defense: browsers don't allow cross-site requests to set arbitrary custom headers without a CORS preflight, and a properly configured CORS policy (not reflecting
Access-Control-Allow-Origin: *with credentials) means the attacker's cross-site page structurally cannot add that header to a forged request in the first place. Trade-off: this only works if your CORS configuration is genuinely strict; a misconfigured CORS policy that echoes back any Origin with credentials allowed defeats this defense entirely.
How I would test each during a penetration test:
- For
SameSite: inspect theSet-Cookieheader directly, and attempt a cross-site form POST from a test page to confirm the cookie is genuinely withheld. - For the double-submit pattern: attempt a forged request that omits the header (should fail), includes a stale/mismatched token (should fail), and includes a token stolen via a DIFFERENT vulnerability like XSS (should still succeed, which is the known limitation - CSRF tokens don't protect against an attacker who already has XSS, since the token is readable by any script on the page).
- For CORS: send an
OPTIONSpreflight from an untrusted origin and confirm the response doesn't grant that originAccess-Control-Allow-Credentials: true.
Trade-offs and pitfalls: all three of these defenses assume the attacker does NOT already have an XSS foothold on the vulnerable site; a working XSS vulnerability defeats CSRF token defenses trivially, since the malicious script runs in the legitimate origin and can read whatever token the legitimate page can read. CSRF and XSS defenses are complementary, not substitutes for each other, and a security review that only checks "do we have CSRF tokens" without also checking XSS exposure is checking half the picture.
A web application uses a custom HMAC comparison for session tokens and returns measurably different response timings for correct versus incorrect tokens. As a tester, explain how you would detect this timing side-channel, outline the experiment you would run to measure the timing differences and confirm the leak, describe a high-level approach to actually recover the HMAC value by exploiting it, and recommend secure comparison techniques along with how you would responsibly report this risk to developers.
Sample Answer
Direct answer
As a tester, the first thing to establish is whether the comparison is naive: a byte-by-byte check with an early return, whether that is a raw == or a hand-written loop, leaks how many leading bytes of the submitted token matched before it diverged from the real hash-based message authentication code (HMAC), because a longer matching prefix means more comparison steps before the function returns false. That difference is small, but over enough repeated, carefully controlled measurements it is statistically distinguishable from ordinary network and server jitter, which is what turns "the tokens are measurably different in response time" into "I can recover the correct HMAC one byte at a time."
Structured elaboration
Detecting the side-channel. Submit a candidate token that is completely wrong (zero correct leading bytes) alongside candidates engineered to share a known, increasing number of leading bytes with a token you already know is valid for a different, disposable test case (or simply vary one byte position across many random guesses and look for a response-time pattern correlated with byte position rather than with the request itself). If the underlying comparison exits early on mismatch, the all-wrong candidate should be consistently faster on average than a candidate sharing several correct leading bytes, once you aggregate enough samples to see past ordinary variance.
The experiment to measure and confirm the leak. A single request pair proves nothing: internet and server-side jitter routinely dwarfs the microsecond-scale signal an early-exit comparison produces. Design the experiment as repeated, interleaved trials rather than a one-shot measurement: for each candidate (a fixed number of correct leading bytes), send several hundred to several thousand requests, record response latency for each, and summarize with a robust statistic (median or a trimmed mean) rather than a single sample or a raw average, since outliers from retries, garbage collection pauses, or momentary load spikes will otherwise swamp the result. Interleave requests across candidates rather than running one candidate to completion and then the next, so that a slow drift in overall server load during the experiment affects every candidate equally instead of biasing whichever one happened to run during a slow period. A genuine timing side-channel shows a reproducible, monotonic shift in the summary statistic as the number of correct leading bytes increases, checked across multiple independent experiment runs; noise does not reproduce that pattern consistently run over run.
High-level approach to recover the HMAC value. This is the standard remote/local timing side-channel technique against a non-constant-time verification (the class of attack formalized in "Remote Timing Attacks are Practical," Brumley and Boneh): rather than brute-forcing the entire secret at once, recover it one byte at a time. For the first byte position, try candidate values (up to 256 possibilities, fewer if the token's character set is constrained) while the remaining bytes are held arbitrary, and take the byte value whose average response time is measurably longer as the (probabilistically) correct byte, since the comparison walked one byte further into a match before returning false. Fix that byte and repeat for the next position. This converts an attack that is exponential in the secret's length (trying every possible value at once) into one that is linear in it: for a 32-byte HMAC-SHA256 digest, that is at most 32×256=8192 distinct byte-value hypotheses to test across all positions, each backed by many repeated measurements for statistical confidence, versus a keyspace of 25632 that is never going to be brute-forced directly. The linear bound is what makes an otherwise-infeasible secret recoverable at all.
Secure comparison recommendation. The fix is a constant-time comparison function that always inspects the full length of both inputs regardless of where they first diverge: hmac.compare_digest in Python, hmac.Equal in Go, or crypto.timingSafeEqual in Node.js. None of these are exotic; they are standard-library functions that exist specifically because this exact vulnerability class is well known, so recommend the language's built-in constant-time primitive rather than a custom implementation.
Responsible reporting. Document the methodology (experiment design, sample sizes, the statistical comparison used) rather than a specific measured time difference, since raw timing numbers are environment-specific and will not reproduce for whoever reads the report on different hardware or network conditions; what should reproduce is the pattern (response time correlates with correct-prefix length) and the underlying code defect (a non-constant-time comparison). Report through the organization's private disclosure channel, a security contact, security.txt, or a bug bounty program, rather than public disclosure first, and include a clear remediation recommendation (swap in the constant-time primitive named above) alongside the finding. Agree on a reasonable disclosure timeline that gives the engineering team time to both patch the comparison and rotate any secret that reporting suspects may have been partially exposed during testing, regardless of how far the recovery actually progressed before you stopped and reported it.
Worked example
This same detect-measure-exploit sequence applies to any HMAC comparison protecting a secret value, not only a session token comparison; the identical methodology recovers a webhook-signing secret's HMAC, an API request-signing HMAC, or a password-reset token's HMAC equally well, since the vulnerability is in how the comparison is implemented, not in what the compared value happens to represent. Consider testing a webhook-signature verification endpoint that checks an incoming X-Signature header against a locally computed HMAC-SHA256 using ==. Following the byte-at-a-time approach above, at most 32×256=8192 candidate byte-value hypotheses need to be tested to fully recover the 32-byte digest, each one backed by a batch of repeated, interleaved timing measurements rather than a single request. That bound holds regardless of whether the secret behind the HMAC is a session token, a webhook secret, or anything else, and the generalization is worth stating plainly: the vulnerability class is about the comparison operation, not the specific artifact being compared.
Trade-offs and pitfalls
This attack is far more practical on a low-latency path (same data center, internal network, or a test environment you control) than blind over the public internet, where added network hops, load balancers, and content delivery network (CDN) jitter can bury the signal under noise large enough that even thousands of samples per candidate fail to resolve it cleanly. A responsible test report should be explicit about which regime the finding was demonstrated in, and should not overstate remote exploitability if the proof of concept only succeeded under low-jitter conditions.
Mitigations exist at both the code level and the infrastructure level: the infrastructure layer matters too, though it never substitutes for the code fix. Rate limiting the endpoint under test slows an attacker's ability to gather the volume of samples this technique needs and buys detection time, and a gateway or service mesh that deliberately adds randomized response jitter raises the number of samples required to resolve the signal. Neither of these removes the underlying non-constant-time comparison; they raise the cost of exploiting it. The comparison itself still needs to be fixed, because a sufficiently patient or well-positioned attacker (or one who gains a lower-jitter vantage point, for example through a compromised machine on the same network segment) can still work around infrastructure-level noise given enough time and requests.
A tester who reports "a timing difference exists" without the aggregation-and-statistics discipline above risks a false positive: a single fast/slow pair of requests is very often just ordinary variance, not evidence of a real side-channel, and shipping that as a finding without the repeated, interleaved measurement methodology undermines the report's credibility even when the underlying code genuinely does have the defect.
Unlock Full Question Bank
Get access to all 49 Secure Coding and Application Security interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.