HIGH integrity failuresbearer tokens

Integrity Failures with Bearer Tokens

How Integrity Failures Manifests in Bearer Tokens

Integrity failures in Bearer Token systems occur when attackers can tamper with token claims, expiration times, or cryptographic signatures without detection. Unlike other authentication mechanisms, Bearer Tokens are transmitted as complete payloads that clients can potentially manipulate if proper integrity controls aren't enforced.

The most common integrity failure pattern involves token manipulation where attackers modify the 'exp' (expiration) claim to extend token lifetime. Since Bearer Tokens are often transmitted as Base64-encoded strings, an attacker who intercepts a token can decode it, alter claims, and re-encode it. Without proper signature verification, the server accepts these modified tokens as valid.

// Vulnerable: No signature verification
const token = req.headers.authorization.split(' ')[1];
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
if (payload.exp > Date.now() / 1000) {
// Accepts modified token!
return authenticateUser(payload.sub);
}

Another critical integrity failure occurs in signature bypass attacks. Many implementations incorrectly verify only the presence of a signature without validating its cryptographic integrity. Attackers can remove or replace the signature portion of JWT tokens, causing verification to fail silently or default to accepting the token.

// Vulnerable: Signature bypass
const [header, payload, signature] = token.split('.');
if (signature) {
// Only checks if signature exists, not if it's valid!
return authenticateUser(JSON.parse(atob(payload)));
}

Timing attacks represent another integrity failure vector. When comparing cryptographic signatures or token claims, using standard equality operators can leak information through timing differences. An attacker can exploit these timing variations to gradually reconstruct valid signatures or bypass integrity checks.

// Vulnerable: Timing attack
function compareSignatures(sig1, sig2) {
return sig1 === sig2; // Timing leak!
}

Bearer Tokens-Specific Detection

Detecting integrity failures in Bearer Token implementations requires systematic testing of token validation logic. The first step is verifying that all tokens undergo cryptographic signature verification before processing any claims. This can be tested by removing the signature portion of a valid token and observing whether the server still accepts it.

// Test: Signature bypass detection
const validToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
const [header, payload, signature] = validToken.split('.');
const unsignedToken = [header, payload, ''].join('.');
const response = await fetch('/api/protected', {
headers: { Authorization: `Bearer ${unsignedToken}` }
});
console.log(response.status); // Should reject with 401

Claim manipulation testing involves modifying specific token claims and verifying that the server detects these changes. The 'exp' claim is particularly important to test, as attackers commonly attempt to extend token lifetimes.

// Test: Claim manipulation
const tokenParts = validToken.split('.');
const header = JSON.parse(Buffer.from(tokenParts[0], 'base64').toString());
const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64').toString());
payload.exp = Date.now() / 1000 + 86400; // Extend by 1 day
const modifiedToken = [tokenParts[0], Buffer.from(JSON.stringify(payload)).toString('base64'), tokenParts[2]].join('.');
// Verify server rejects modified expiration

Automated scanning tools like middleBrick can systematically test these integrity failure patterns across multiple endpoints. The scanner tests for signature bypass by submitting unsigned tokens, modified claims, and timing-sensitive comparisons. It also verifies that tokens are properly validated against their cryptographic signatures before any claims are processed.

middleBrick's integrity failure detection includes checking for common implementation mistakes like accepting tokens with mismatched algorithms, failing to verify 'kid' header claims, and improper handling of 'none' algorithm tokens. The scanner provides specific findings about which endpoints are vulnerable to integrity bypass and what claims can be manipulated.

Bearer Tokens-Specific Remediation

Proper integrity protection for Bearer Tokens requires cryptographic signature verification with constant-time comparison operations. The most secure approach uses asymmetric cryptography where the server only has the public key for verification, preventing any possibility of signature forgery.

// Secure: Asymmetric signature verification
const jwt = require('jsonwebtoken');
const publicKey = fs.readFileSync('public.pem');

function verifyToken(token) {
try {
const decoded = jwt.verify(token, publicKey, {
algorithms: ['RS256']
});
return decoded;
} catch (err) {
return null; // Invalid or tampered token
}
}

Critical to integrity protection is using constant-time comparison for all sensitive operations. Node.js provides crypto.timingSafeEqual for this purpose, which prevents timing attacks that could leak signature information.

// Secure: Constant-time comparison
const crypto = require('crypto');

function secureCompare(val1, val2) {
if (val1.length !== val2.length) return false;
return crypto.timingSafeEqual(Buffer.from(val1), Buffer.from(val2));
}

// Usage in token validation
const storedSignature = getStoredSignature(token);
const computedSignature = computeSignature(token);
if (!secureCompare(storedSignature, computedSignature)) {
throw new Error('Token integrity check failed');
}

Additional integrity controls include claim validation and strict algorithm enforcement. Every token should be validated against expected values for 'iss' (issuer), 'aud' (audience), and 'nbf' (not before) claims, not just 'exp'.

// Secure: Comprehensive claim validation
function validateClaims(token) {
const now = Date.now() / 1000;
if (token.exp < now) throw new Error('Token expired');
if (token.nbf > now) throw new Error('Token not valid yet');
if (token.iss !== 'expected-issuer') throw new Error('Invalid issuer');
if (!token.aud.includes('expected-audience')) throw new Error('Invalid audience');
return true;
}

For applications using Bearer Tokens in API communications, implementing token binding can prevent token replay attacks. This involves binding tokens to specific client details like IP address or user agent, adding an additional integrity layer.

// Secure: Token binding
function bindToken(token, clientIp, userAgent) {
const bindingData = { ip: clientIp, ua: userAgent };
...token,
binding: bindingData
}, privateKey, { algorithm: 'RS256' });
}

Frequently Asked Questions

How can I test if my Bearer Token implementation is vulnerable to integrity failures?
Use middleBrick to scan your API endpoints - it automatically tests for signature bypass, claim manipulation, and timing attacks. You can also manually test by removing the signature from a valid token or modifying the 'exp' claim to see if the server still accepts it.
What's the difference between integrity failures and confidentiality failures in Bearer Tokens?
Integrity failures involve attackers tampering with token contents (claims, expiration, signatures) without detection, while confidentiality failures involve unauthorized parties reading token contents. Integrity protects against modification; confidentiality protects against disclosure.