CWE-522 in APIs
- CWE ID
- CWE-522
- Category
- Data Exposure
- Severity
- CRITICAL
- Short Name
- Credential Exposure
What is CWE-522?
CWE-522 refers to the weakness of Insufficiently Protected Credentials. This occurs when sensitive authentication data—such as passwords, API keys, or tokens—is stored, transmitted, or processed without adequate protection. The weakness manifests when credentials are exposed through insecure storage, weak encryption, or improper transmission methods, allowing attackers to capture or reconstruct authentication data.
The core issue is that credentials remain in a form that can be recovered or misused by unauthorized parties. This might involve storing passwords in plaintext, using weak cryptographic algorithms, or transmitting credentials over unencrypted channels. The result is that authentication mechanisms can be bypassed or compromised, leading to unauthorized access to systems and data.
CWE-522 in API Contexts
In API environments, CWE-522 appears in several critical ways that directly impact API security. API endpoints often handle authentication tokens, API keys, and session identifiers that must be protected throughout their lifecycle.
- API Key Exposure: Hardcoded API keys in client applications or transmitted in URLs can be captured through network sniffing or source code leaks.
- Token Storage: JWT tokens or session cookies stored in localStorage or transmitted without proper security flags become vulnerable to XSS attacks or interception.
- Credential Transmission: APIs that accept credentials over HTTP instead of HTTPS expose authentication data to network-level attacks.
- Response Headers: Authentication details inadvertently included in API responses through debug headers or error messages.
- Database Storage: User credentials stored without proper hashing or using weak algorithms like MD5 or SHA-1.
APIs are particularly vulnerable because they often serve as gateways to multiple systems, making credential compromise especially damaging. A single exposed API key can provide access to entire backend services, data stores, or third-party integrations.
Detection
Detecting CWE-522 requires examining how credentials are handled throughout the API lifecycle. Manual code review should focus on authentication flows, configuration files, and response handling. Automated tools can scan for common patterns like hardcoded secrets, weak encryption usage, and improper credential transmission.
Security scanners like middleBrick specifically test for credential-related weaknesses by examining API responses for exposed tokens, testing authentication mechanisms for bypass vulnerabilities, and checking for proper encryption in transit. The scanner evaluates whether authentication headers are properly secured and whether credentials appear in unexpected locations like error messages or debug output.
Static analysis tools can identify hardcoded credentials in source code, while dynamic analysis can test whether credentials are transmitted securely over the network. API security testing should include attempts to capture authentication data through various attack vectors, including man-in-the-middle scenarios and response manipulation.
Key detection areas include:
- Checking for HTTPS enforcement on all endpoints
- Verifying proper token storage mechanisms
- Examining database schemas for password storage practices
- Testing for credential exposure in API responses
- Scanning for hardcoded secrets in configuration files
Remediation
Fixing CWE-522 requires implementing defense-in-depth strategies for credential protection. The foundation is using strong, proven cryptographic methods for all credential-related operations.
For password storage, always use bcrypt, Argon2, or PBKDF2 with appropriate work factors. Never store passwords in plaintext or use weak hashing algorithms:
// Secure password storage using bcrypt
const bcrypt = require('bcrypt');
const saltRounds = 12;
async function hashPassword(password) {
return await bcrypt.hash(password, saltRounds);
}
async function verifyPassword(plaintext, hashed) {
return await bcrypt.compare(plaintext, hashed);
}
For API key management, use environment variables or secure secret management services rather than hardcoding:
// Secure API key handling
require('dotenv').config();
const apiKey = process.env.API_KEY;
if (!apiKey) {
throw new Error('API key not configured');
}
// Use key in requests
async function makeSecureRequest() {
const response = await fetch('https://api.example.com/data', {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
return response.json();
}
Always enforce HTTPS/TLS for all API communications:
// Express middleware to enforce HTTPS
app.use((req, res, next) => {
if (req.secure || process.env.NODE_ENV === 'development') {
return next();
}
res.redirect(`https://${req.headers.host}${req.url}`);
});
Implement proper token handling with secure flags:
// Secure JWT handling
const jwt = require('jsonwebtoken');
function createSecureToken(payload, secret) {
return jwt.sign(payload, secret, {
expiresIn: '1h',
issuer: 'your-app'
});
}
// Set secure cookie flags
function setAuthCookie(res, token) {
res.cookie('authToken', token, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 3600000
});
}
Additional remediation steps include implementing rate limiting on authentication endpoints, using multi-factor authentication where possible, and regularly rotating API keys and tokens. Security headers like Strict-Transport-Security and Content-Security-Policy add additional protection layers.