CWE-798 in APIs
- CWE ID
- CWE-798
- Category
- Authentication
- Severity
- CRITICAL
- Short Name
- Hardcoded Creds
What is CWE-798?
CWE-798, "Use of Hard-coded Credentials," is a critical software weakness where authentication credentials, cryptographic keys, or other sensitive information are embedded directly in source code, configuration files, or deployment artifacts. This creates a severe security vulnerability because anyone with access to the codebase or binary can potentially extract these credentials.
The weakness manifests when developers embed secrets directly into code for convenience, often during development or testing phases. Common examples include hard-coded API keys, database passwords, encryption keys, or administrative credentials. These credentials remain in the final product, creating persistent attack vectors that persist across deployments and environments.
The fundamental problem is that hard-coded credentials cannot be rotated, cannot be managed securely, and are often shared across multiple environments (development, staging, production). When credentials are embedded in code, they become part of the software's attack surface, accessible through source code repositories, decompiled binaries, or configuration files in production environments.
CWE-798 in API Contexts
In API development, CWE-798 appears in several critical forms that directly impact authentication, authorization, and data protection mechanisms. API keys embedded in source code are perhaps the most common manifestation, where developers hard-code service credentials, database connections, or third-party API keys directly into the application logic.
Database connection strings with embedded credentials represent another frequent vulnerability. An API might contain code like: jdbc:mysql://localhost:3306/mydb?user=admin&password=secret123, exposing database credentials to anyone with code access. This becomes especially dangerous when APIs connect to production databases containing sensitive user data.
Authentication mechanisms are particularly vulnerable to this weakness. Hard-coded admin credentials, default passwords, or static API keys embedded in authentication middleware create backdoors that bypass normal security controls. An API might implement a debug endpoint with hard-coded credentials like if (username === 'debug' && password === 'letmein'), providing unauthorized administrative access.
Configuration files that contain environment-specific credentials but are committed to version control represent another variant. Developers might create config.js files with production database credentials or API keys, then commit these files to repositories where they become accessible to all team members and potentially to attackers through public repositories.
Third-party service integrations often suffer from hard-coded credentials when developers embed API keys for services like payment processors, cloud storage, or external APIs directly in the code rather than using secure credential management systems.
Detection
Detecting CWE-798 requires both static code analysis and runtime scanning to identify embedded credentials across the entire application stack. Static analysis tools can scan source code repositories for patterns matching common credential formats, including base64-encoded strings, hexadecimal sequences, and known credential patterns.
Regular expressions can identify potential credentials in code: /password\s*[:=]\s*['"]\w+['"]|secret\s*[:=]\s*['"]\w+['"]|key\s*[:=]\s*['"]\w+['"]. However, sophisticated attackers use more advanced techniques like entropy analysis to find high-entropy strings that might represent cryptographic keys or passwords.
middleBrick's black-box scanning approach specifically tests for authentication bypass vulnerabilities that often stem from CWE-798 weaknesses. The scanner attempts to access protected API endpoints without credentials, testing whether any endpoints respond without proper authentication. This can reveal endpoints that rely on hard-coded credentials or have disabled authentication mechanisms.
Configuration file analysis is critical for detection. middleBrick examines configuration files, environment files, and deployment manifests for embedded credentials. The scanner looks for patterns like DB_PASSWORD, API_KEY, or SECRET in configuration files that might contain actual credential values rather than references to secure storage.
Runtime credential leakage testing involves sending requests to API endpoints and analyzing responses for authentication bypass. If an API endpoint responds with sensitive data or administrative functionality without proper credentials, this may indicate hard-coded credentials or disabled authentication checks.
middleBrick's comprehensive scanning includes testing for common default credentials and known vulnerable patterns. The scanner maintains a database of default passwords and common credential patterns to test against API endpoints, identifying instances where developers have failed to change default credentials.
Remediation
Remediating CWE-798 requires a systematic approach to credential management that eliminates hard-coded secrets and implements secure credential storage and retrieval mechanisms. The fundamental principle is that credentials should never exist in source code, configuration files, or deployment artifacts.
Environment-based configuration is the first remediation step. Instead of hard-coding credentials, applications should read them from environment variables or secure credential stores. Example implementation:
// BAD: Hard-coded credentials
const db = mysql.createConnection({
host: 'localhost',
user: 'admin',
password: 'secret123',
database: 'mydb'
});
// GOOD: Environment variables
const db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
});Secret management services provide secure storage and retrieval of credentials. Services like AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault allow applications to retrieve credentials at runtime without storing them in code. Implementation example:
const AWS = require('aws-sdk');
const client = new AWS.SecretsManager({ region: 'us-west-2' });
async function getDatabaseCredentials() {
const data = await client.getSecretValue({ SecretId: 'my-db-credentials' }).promise();
return JSON.parse(data.SecretString);
}
// Use credentials at runtime
const credentials = await getDatabaseCredentials();
const db = mysql.createConnection({
host: credentials.host,
user: credentials.username,
password: credentials.password,
database: credentials.database
});Configuration file restructuring eliminates credential exposure. Instead of committing configuration files with actual credentials, use template files that reference environment variables:
// config.template.js
module.exports = {
database: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
},
externalApi: {
baseUrl: process.env.EXTERNAL_API_URL,
apiKey: process.env.EXTERNAL_API_KEY
}
};Credential rotation policies ensure that even if credentials are compromised, their useful lifetime is limited. Implement automated credential rotation for database credentials, API keys, and service accounts, with applications designed to handle credential changes without downtime.
Secrets scanning in CI/CD pipelines prevents credential commits. Tools like git-secrets, truffleHog, or GitHub's secret scanning can detect and block commits containing potential credentials before they reach repositories. Integrate these tools into your development workflow to catch credentials before they're committed.
Code review processes should specifically check for credential-related patterns. Train developers to recognize hard-coded credential anti-patterns and implement peer review requirements for authentication and configuration code changes.
Runtime credential validation ensures that applications fail safely when credentials are unavailable rather than falling back to default or hard-coded values. Implement proper error handling for credential retrieval failures and ensure applications cannot operate without proper authentication.
Frequently Asked Questions
How can I tell if my API has hard-coded credentials?
Look for suspicious patterns in your source code: base64 strings, hexadecimal sequences, or credentials in configuration files. middleBrick can scan your API endpoints for authentication bypass vulnerabilities that often indicate hard-coded credentials. The scanner tests whether endpoints respond without proper authentication and examines configuration files for embedded secrets. Additionally, use static analysis tools to scan your codebase for credential patterns before committing changes.
What's the difference between hard-coded credentials and environment variables?
Hard-coded credentials are embedded directly in source code or configuration files, making them part of the codebase that can be extracted by anyone with access. Environment variables store credentials outside the codebase, typically in the deployment environment's configuration. While environment variables are more secure than hard-coded credentials, they still require proper management and should be stored in secure credential stores rather than in plain text files or version control systems.