length-extension-attacks-anti-pattern
Security anti-pattern for hash length extension vulnerabilities (CWE-328). Use when generating or reviewing code that uses hash(secret + message) for authentication, API signatures, or integrity verification. Detects Merkle-Damgard hash misuse.
What this skill does
# Length Extension Attacks Anti-Pattern
**Severity:** High
## Summary
Hash length extension attacks exploit Merkle-Damgård construction vulnerabilities in MD5, SHA-1, and SHA-256. Attackers knowing `hash(secret + message)` and secret length can compute `hash(secret + message + padding + attacker_data)` without knowing the secret. This enables appending data to signed messages with valid signatures, completely breaking message integrity and authentication.
## The Anti-Pattern
Never use vulnerable hash functions (MD5, SHA-1, SHA-256) in `hash(secret + message)` construction for MACs. Use HMAC instead.
### BAD Code Example
```python
# VULNERABLE: Using hash(secret + message) for message signature
import hashlib
SECRET_KEY = b"my_super_secret_key_16b" # 16 bytes
def get_signed_url(message):
# Signature created by prepending secret to message and hashing
# Vulnerable to length extension
signature = hashlib.sha256(SECRET_KEY + message.encode()).hexdigest()
return f"/api/action?{message}&signature={signature}"
def verify_request(message, signature):
expected_signature = hashlib.sha256(SECRET_KEY + message.encode()).hexdigest()
return signature == expected_signature
# 1. Legitimate URL generated:
# Message: "user=alice&action=view"
# URL: /api/action?user=alice&action=view&signature=...
# 2. Attacker intercepts URL. Knows signature and message.
# Doesn't know SECRET_KEY but can guess length (16 bytes)
# 3. Using `hashpump`, attacker computes new valid signature for extended message
# Original: "user=alice&action=view"
# Extended: "user=alice&action=view" + padding + "&action=delete&target=bob"
# Tool generates new signature and message with padding
# 4. Server receives forged request, recomputes hash of `SECRET_KEY + extended_message`,
# finds it matches attacker's signature. Delete action processed
```
### GOOD Code Example
```python
# SECURE: Use HMAC (Hash-based Message Authentication Code)
import hmac
import hashlib
SECRET_KEY = b"my_super_secret_key_16b"
def get_signed_url_secure(message):
# HMAC designed to prevent length extension attacks
# Two-step hashing: hash(key XOR opad, hash(key XOR ipad, message))
signature = hmac.new(SECRET_KEY, message.encode(), hashlib.sha256).hexdigest()
return f"/api/action?{message}&signature={signature}"
def verify_request_secure(message, signature):
expected_signature = hmac.new(SECRET_KEY, message.encode(), hashlib.sha256).hexdigest()
# Use hmac.compare_digest for constant-time comparison, prevents timing attacks
return hmac.compare_digest(signature, expected_signature)
# Attacker cannot extend HMAC-signed message without secret key
# Inner hash `hash(key XOR ipad, message)` prevents continuing hash chain
```
### Language-Specific Examples
**JavaScript/Node.js:**
```javascript
// VULNERABLE: hash(secret + message) construction
const crypto = require('crypto');
const SECRET = 'my_secret_key';
function signMessage(message) {
// Vulnerable to length extension!
const signature = crypto.createHash('sha256')
.update(SECRET + message)
.digest('hex');
return signature;
}
```
```javascript
// SECURE: Use HMAC
const crypto = require('crypto');
const SECRET = 'my_secret_key';
function signMessageSecure(message) {
const signature = crypto.createHmac('sha256', SECRET)
.update(message)
.digest('hex');
return signature;
}
// Verify with constant-time comparison
function verifySignature(message, signature) {
const expected = signMessageSecure(message);
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
```
**Java:**
```java
// VULNERABLE: Manual hash(secret + message)
import java.security.MessageDigest;
public class InsecureSigning {
private static final String SECRET = "my_secret_key";
public static String signMessage(String message) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// Vulnerable to length extension!
String combined = SECRET + message;
byte[] hash = digest.digest(combined.getBytes());
return bytesToHex(hash);
}
}
```
```java
// SECURE: Use HMAC
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
public class SecureSigning {
private static final String SECRET = "my_secret_key";
public static String signMessage(String message) throws Exception {
Mac hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(
SECRET.getBytes(), "HmacSHA256");
hmac.init(secretKey);
byte[] hash = hmac.doFinal(message.getBytes());
return bytesToHex(hash);
}
// Constant-time comparison
public static boolean verifySignature(String message, String signature)
throws Exception {
String expected = signMessage(message);
return MessageDigest.isEqual(
signature.getBytes(),
expected.getBytes()
);
}
}
```
## Detection
- **Find hash(secret + message) patterns:** Grep for concatenation before hashing:
- `rg 'hashlib\.(md5|sha1|sha256)\(.*\+' --type py`
- `rg 'crypto\.createHash.*update.*\+' --type js`
- `rg 'MessageDigest.*update.*\+' --type java`
- Look for `hash(key + data)` or `hash(data + key)` patterns
- **Identify vulnerable hash functions for MACs:** Search for signing without HMAC:
- `rg 'hashlib\.(md5|sha1|sha256)' --type py | rg -v 'hmac'`
- `rg 'crypto\.createHash\(' --type js | rg -v 'createHmac'`
- `rg 'MessageDigest\.getInstance.*MD5|SHA-1|SHA-256' --type java | rg -v 'Mac\.getInstance'`
- **Audit signature generation:** Find custom MAC implementations:
- `rg 'signature.*=.*hash|mac.*=.*hash' -i`
- Check API signatures, token generation, cookie signing
- **Use static analysis:** Run tools to detect weak crypto:
- Semgrep: `python.lang.security.audit.hashlib-weak-hash`
- Bandit: `B303` (MD5/SHA1 usage)
## Prevention
- [ ] **Use HMAC:** Always use HMAC for message authentication codes. Industry standard, immune to length extension attacks, available in standard libraries
- [ ] **Choose secure hash functions:** Use HMAC with SHA-256 or SHA-3
- [ ] **Never roll your own crypto:** Avoid custom schemes like `hash(message + secret)` or `hash(secret + message + secret)`. Use HMAC
- [ ] **Alternative if HMAC unavailable:** Use SHA-3 or BLAKE2 (not vulnerable to length extension). HMAC still preferred
## Related Security Patterns & Anti-Patterns
- [Weak Encryption Anti-Pattern](../weak-encryption/): Part of broader cryptographic failures category
- [Timing Attacks Anti-Pattern](../timing-attacks/): Use constant-time comparison for signature verification to prevent timing leaks
## References
- [OWASP Top 10 A04:2025 - Cryptographic Failures](https://owasp.org/Top10/2025/A04_2025-Cryptographic_Failures/)
- [OWASP GenAI LLM10:2025 - Unbounded Consumption](https://genai.owasp.org/llmrisk/llm10-unbounded-consumption/)
- [CWE-328: Reversible One-Way Hash](https://cwe.mitre.org/data/definitions/328.html)
- [CAPEC-97: Cryptanalysis](https://capec.mitre.org/data/definitions/97.html)
- [Length Extension Attack (Wikipedia)](https://en.wikipedia.org/wiki/Length_extension_attack)
- [Hash Length Extension Attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks)
- [BlueKrypt - Cryptographic Key Length Recommendation](https://www.keylength.com/)
- Source: [sec-context](https://github.com/Arcanum-Sec/sec-context)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.