CRITICAL spring4shellbearer tokens

Spring4shell with Bearer Tokens

How Spring4shell Manifests in Bearer Tokens

Spring4shell (CVE-2022-22965) exploits a critical deserialization vulnerability in Spring Framework versions 5.3.0 to 5.3.17, 5.2.0 to 5.2.19, and older versions. When Bearer Tokens applications use Spring's default deserialization mechanisms, attackers can craft malicious payloads that bypass authentication and execute arbitrary code.

The vulnerability specifically targets how Spring processes HTTP request parameters during bean property binding. In Bearer Tokens applications, this often manifests when parsing Authorization headers containing Bearer tokens. An attacker can construct a payload that, when deserialized by Spring's ObjectFactory, triggers remote code execution.

Consider this vulnerable Bearer Tokens configuration:

@RestController
public class AuthController {
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody AuthRequest request) {
        // Authentication logic
        String token = generateToken(request.getUsername());
        return ResponseEntity.ok(token);
    }

    @GetMapping("/protected")
    public ResponseEntity<String> protectedResource(@RequestHeader("Authorization") String authHeader) {
        // Spring deserializes the Authorization header
        // Vulnerable to Spring4shell if header contains malicious payload
        return ResponseEntity.ok("Access granted");
    }
}

The critical issue occurs in the Authorization header processing. When Spring deserializes the Bearer token value, it can be tricked into executing arbitrary Java code through specially crafted payloads that exploit the PropertyEditor mechanism.

Attackers exploit this by crafting payloads that:

  • Trigger class instantiation through ObjectFactory
  • Execute system commands via Runtime.getRuntime().exec()
  • Access sensitive application data
  • Bypass authentication mechanisms entirely
  • Establish reverse shells on compromised servers

The impact is severe: complete server compromise, data theft, and lateral movement within networks. For Bearer Tokens applications, this means attackers can steal all active tokens, impersonate users, and access protected resources without authentication.

Bearer Tokens-Specific Detection

Detecting Spring4shell in Bearer Tokens applications requires a multi-layered approach. The vulnerability manifests through specific network traffic patterns and application behaviors that can be identified through careful monitoring.

Network-level detection focuses on anomalous Authorization header patterns:

# Using curl to test for Spring4shell vulnerability
curl -X POST http://api.example.com/login \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=malicious&password=payload" \
  --trace-ascii /dev/stdout

Key indicators include:

  • Unexpected class loading patterns in server logs
  • Unusual memory consumption during request processing
  • Network connections to external IP addresses from the application server
  • Process execution attempts visible in audit logs

For automated detection, middleBrick's black-box scanning can identify Spring4shell vulnerabilities without requiring source code access:

# Scan Bearer Tokens API with middleBrick
middlebrick scan https://api.example.com \
  --test spring4shell \
  --output json

middleBrick tests for:

  • Deserialization vulnerabilities in request parameter handling
  • Authorization header processing weaknesses
  • Class loading vulnerabilities
  • Runtime execution capabilities

The scanner generates a security risk score (A–F) with specific findings for Spring4shell, including severity levels and remediation guidance. For Bearer Tokens applications, it specifically checks how Authorization headers are processed and whether they're vulnerable to deserialization attacks.

Runtime detection using application performance monitoring:

# Log suspicious deserialization attempts
logging.level.org.springframework.beans=DEBUG
logging.level.org.springframework.core=DEBUG

# Monitor for specific patterns
logback.xml configuration:
<appender name="SECURITY" class="ch.qos.logback.core.FileAppender">
    <file>security.log</file>
    <encoder>
        <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
</appender>

Bearer Tokens-Specific Remediation

Remediating Spring4shell in Bearer Tokens applications requires immediate patching and architectural changes. The primary fix is upgrading Spring Framework to patched versions: 5.3.18+ or 5.2.20+.

Immediate mitigation steps:

# Maven pom.xml updates
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.3.18</version>
</dependency>

# Gradle build.gradle updates
dependencies {
    implementation 'org.springframework:spring-core:5.3.18'
}

Code-level hardening for Bearer Tokens applications:

@Component
public class SecureTokenService {
    
    public String validateAndParseToken(String authHeader) {
        // Strict validation before processing
        if (!authHeader.startsWith("Bearer ")) {
            throw new InvalidTokenException("Invalid token format");
        }
        
        String token = authHeader.substring(7);
        
        // Validate token structure and length
        if (token.length() < 64 || token.length() > 2048) {
            throw new InvalidTokenException("Token length suspicious");
        }
        
        // Check for dangerous characters
        if (token.matches(".*[<>"{}();|&].*")) {
            throw new InvalidTokenException("Suspicious characters in token");
        }
        
        return parseToken(token);
    }
    
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new SecurityInterceptor());
            }
        };
    }
}

@Component
public class SecurityInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String authHeader = request.getHeader("Authorization");
        
        // Block suspicious Authorization headers
        if (authHeader != null && authHeader.length() > 2000) {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return false;
        }
        
        return true;
    }
}

Additional security measures:

  • Implement strict Content-Type validation
  • Use Spring Security's built-in protections
  • Enable strict deserialization controls
  • Deploy WAF rules for Spring4shell detection
  • Implement rate limiting on authentication endpoints

For continuous monitoring, integrate middleBrick into your CI/CD pipeline:

# GitHub Actions workflow
name: Security Scan
on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Scan with middleBrick
        run: |
          npm install -g middlebrick
          middlebrick scan ${{ secrets.API_URL }} \
            --test spring4shell \
            --fail-on-severity=high
      - name: Fail on security issues
        if: failure()
        run: exit 1

These remediation steps, combined with continuous scanning, ensure Bearer Tokens applications remain protected against Spring4shell exploitation while maintaining functionality for legitimate users.

Frequently Asked Questions

Can Spring4shell be exploited through Bearer Tokens without authentication?
Yes, Spring4shell exploits the deserialization process itself, which occurs before authentication checks in many Bearer Tokens implementations. The vulnerability allows attackers to execute arbitrary code by crafting malicious payloads in Authorization headers, bypassing authentication entirely.
How does middleBrick detect Spring4shell in Bearer Tokens applications?
middleBrick performs black-box scanning that tests for deserialization vulnerabilities by sending specially crafted payloads to Authorization headers and other request parameters. It analyzes the application's response patterns, memory usage, and network behavior to identify Spring4shell indicators without requiring source code access or credentials.