Spring4shell in Express with Bearer Tokens
Spring4shell in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Spring4shell (CVE-2022-22965) is a remote code execution vulnerability in Spring Framework affecting versions prior to 5.3.18 and 5.2.x prior to 5.2.19. It exploits data binding via the class parameter to execute arbitrary code. When an Express API that proxies or interoperates with Spring-based services uses Bearer Tokens for authorization but does not adequately validate or scope user-supplied input before it reaches backend Spring endpoints, the attack surface expands.
In this combination, Bearer Tokens are typically validated at the Express layer (e.g., via middleware checking a JWT or an introspection endpoint), but the token is then passed along with user-controlled parameters to the Spring backend. If the backend uses request parameters to bind to Java objects (e.g., via ServletRequest or controller method arguments), an attacker can embed a malicious payload (such as class.module.classLoader.resources.context.pipeline.first.pattern) in query or body fields. Even when a valid Bearer Token is presented, the authorization check may pass while the underlying Spring application processes the malicious parameter, leading to remote code execution.
For example, an Express route that forwards a user-supplied template query parameter to a Spring service without sanitization can allow traversal: /render?template=../../exploit&class=malicious.Class. The Bearer Token may authorize the request, but the token does not prevent the malicious parameter from reaching the vulnerable Spring component. Because the vulnerability resides in parameter binding rather than authentication, the presence of Bearer Tokens alone does not mitigate Spring4shell; it only identifies which principal made the call, which can complicate audit trails but not stop exploitation.
An Express middleware that passes headers and query strings to a Spring backend without filtering or schema validation can inadvertently forward attacker-controlled data. This becomes critical if the backend uses reflection-based data binding (e.g., Spring MVC’s @RequestParam or @ModelAttribute). In such cases, an attacker who knows the parameter names can craft requests like GET /api/items?class=java.lang.Runtime&method=exec&args[]=id while including a valid Bearer Token, testing whether the token is accepted before the exploit is attempted. middleBrick scans such unauthenticated attack surfaces and flags the risk where parameter-based injection can coexist with token-based auth, highlighting the need for input validation and strict schema checks on forwarded parameters.
Bearer Tokens-Specific Remediation in Express — concrete code fixes
To secure Express APIs that interact with Spring-based backends, treat Bearer Tokens strictly as identity carriers and never as a substitute for input validation. Always validate and sanitize all incoming parameters before forwarding them, and enforce strict schema rules on forwarded requests.
Example of insecure Express code that forwards user input directly to a Spring service:
// Insecure: forwards query parameters without validation
app.get('/api/render', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!validateBearer(token)) return res.status(401).send('Unauthorized');
// Dangerous: user-controlled query parameters passed through
const url = `http://spring-backend/data?template=${req.query.template}&class=${req.query.class}`;
fetch(url, { headers: { Authorization: `Bearer ${token}` } })
.then(r => r.text())
.then(data => res.send(data))
.catch(err => res.status(500).send('Error'));
});
This pattern allows an attacker to inject parameters like class even when a valid Bearer Token is provided. Remediation involves strict allowlisting, schema validation, and avoiding direct concatenation of user input into URLs.
Secure Express code with input validation and schema-based filtering:
const { body, query, validationResult } = require('express-validator');
app.get('/api/render', [
// Validate and sanitize query parameters
query('template').isString().trim().escape(),
query('class').optional().isString().custom(value => {
// Explicitly disallow dangerous class-related parameter names
const forbidden = ['class', 'method', 'args', 'module'];
if (forbidden.some(f => value.toLowerCase().includes(f))) {
throw new Error('Forbidden parameter');
}
return true;
}),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const token = req.headers.authorization?.split(' ')[1];
if (!validateBearer(token)) return res.status(401).send('Unauthorized');
// Safe: only known, sanitized parameters are forwarded
const params = new URLSearchParams();
if (req.query.template) params.set('template', req.query.template);
// class is not forwarded; if needed, map to a safe internal value
const url = 'http://spring-backend/data?' + params.toString();
fetch(url, { headers: { Authorization: `Bearer ${token}` } })
.then(r => r.text())
.then(data => res.send(data))
.catch(err => res.status(500).send('Error'));
});
Additionally, use middleware to enforce that sensitive endpoints do not forward unexpected parameters. For Bearer Token usage, ensure tokens are verified via a reliable identity provider and that token scopes are checked to limit what each client can request. middleBrick’s API scans can help detect endpoints where parameter forwarding occurs alongside token-based auth without input validation, supporting compliance with OWASP API Top 10 and frameworks such as PCI-DSS and SOC2.
For continuous assurance, the middleBrick CLI can be integrated into scripts: middlebrick scan <url>. The Pro plan supports continuous monitoring and GitHub Action integration to fail builds if risk scores degrade, while the MCP Server enables scanning APIs directly from AI coding assistants within your IDE.
Frequently Asked Questions
Does a valid Bearer Token prevent Spring4shell exploitation?
How can I test if my Express API is vulnerable when using Bearer Tokens?
class, method) while including a valid Bearer Token. Observe whether these parameters are forwarded to backend services. middleBrick scans unauthenticated attack surfaces and can flag endpoints that forward user input alongside token-based auth, highlighting risks where parameter validation is missing.