Security Resources

⌘K
  1. Home
  2. Security Resources
  3. Secure Code Explain
  4. Constant-Time Verification and Timing Attack Defense

Constant-Time Verification and Timing Attack Defense

Here is an example of Node.js code vulnerable to timing side-channel attacks when verifying API tokens or HMAC signatures:

🥺 Vulnerable Code

// Vulnerable: Standard equality comparison leaks timing side-channels
const express = require('express');
const app = express();

const SECRET_API_KEY = "sec_live_9f83b271a04e5d6c8e9b0a1f2";

app.post('/api/webhook', (req, res) => {
    const clientKey = req.headers['x-api-key'];
    
    // Vulnerable: Standard '===' short-circuits on the first mismatched character
    // Attackers measure microsecond latency differences to deduce characters sequentially
    if (clientKey === SECRET_API_KEY) {
        return res.json({ status: 'authenticated' });
    }
    
    res.status(401).json({ error: 'Unauthorized' });
});

The standard equality operator (=== or ==) compares strings character by character from left to right, returning false immediately upon encountering the first non-matching character (early exit). An attacker issuing statistical batches of HTTP requests can measure microsecond differences in response latency. A key beginning with the correct first character takes slightly longer to reject than one with an incorrect first character, allowing attackers to guess secret keys and HMAC signatures byte by byte.

😎 Secure Code

Here is the secure version using Node.js crypto.timingSafeEqual() to ensure comparisons execute in constant time:

// Secure: Constant-time verification using crypto.timingSafeEqual
const express = require('express');
const crypto = require('crypto');
const app = express();

const SECRET_API_KEY = "sec_live_9f83b271a04e5d6c8e9b0a1f2";
const SECRET_BUFFER = Buffer.from(SECRET_API_KEY, 'utf-8');

function verifyApiKey(clientKey) {
    if (typeof clientKey !== 'string') {
        return false;
    }
    
    const clientBuffer = Buffer.from(clientKey, 'utf-8');
    
    // If lengths differ, compare dummy buffer to prevent length-leak timing discrepancy
    if (clientBuffer.length !== SECRET_BUFFER.length) {
        // Still perform constant-time comparison against itself to equalize latency
        crypto.timingSafeEqual(SECRET_BUFFER, SECRET_BUFFER);
        return false;
    }
    
    // Secure: Constant-time comparison ensures identical latency regardless of match index
    return crypto.timingSafeEqual(clientBuffer, SECRET_BUFFER);
}

app.post('/api/webhook', (req, res) => {
    const clientKey = req.headers['x-api-key'];
    
    if (verifyApiKey(clientKey)) {
        return res.json({ status: 'authenticated' });
    }
    
    res.status(401).json({ error: 'Unauthorized' });
});

crypto.timingSafeEqual() inspects every byte in the buffers without early termination, ensuring that the execution time is entirely independent of where mismatches occur. Additionally, by comparing a dummy buffer when string lengths differ, the function prevents timing side-channels from leaking the length of the secret key.