Claude
Skills
Sign in
Back

java-best-practices-security-audit

Included with Lifetime
$97 forever

Performs comprehensive security audits of Java code against OWASP Top 10 and best practices. Use when auditing security, checking for vulnerabilities, analyzing SQL injection risks, preventing XSS attacks, reviewing authentication/authorization, detecting sensitive data exposure, checking dependency vulnerabilities, ensuring OWASP compliance, or hardening Java applications. Works with Java web applications, REST APIs, Spring applications, and any Java codebase.

Backend & APIs

What this skill does


# Java Security Audit

## Table of Contents

- [Purpose](#purpose)
- [When to Use](#when-to-use)
- [Quick Start](#quick-start)
- [Instructions](#instructions)
- [Examples](#examples)
- [Requirements](#requirements)
- [Security Audit Checklist](#security-audit-checklist)
- [Output Format](#output-format)
- [Error Handling](#error-handling)

## Purpose

Conducts comprehensive security audits of Java applications, identifying vulnerabilities based on OWASP Top 10, analyzing code for injection flaws, authentication issues, sensitive data exposure, and dependency vulnerabilities. Provides actionable remediation guidance.

## When to Use

Use this skill when you need to:
- Audit Java applications for security vulnerabilities
- Check for SQL injection vulnerabilities
- Detect XSS (Cross-Site Scripting) risks
- Review authentication and authorization implementation
- Identify sensitive data exposure issues
- Scan dependencies for known CVEs
- Ensure OWASP Top 10 compliance
- Review cryptographic implementations
- Check for insecure deserialization
- Audit session management security
- Detect hardcoded credentials or secrets
- Review access control mechanisms
- Perform pre-deployment security validation
- Conduct security code reviews

## Quick Start
Point to any Java codebase for immediate security analysis:

```bash
# Audit entire project
Perform security audit on this Java project

# Audit specific components
Security audit for src/main/java/com/example/controller/

# Check for specific vulnerability
Check for SQL injection vulnerabilities in this codebase
```

## Instructions

### Step 1: Identify Audit Scope
Determine what to audit:

**Full Application Audit:**
- All Java source files
- Configuration files (application.yml, application.properties)
- Dependencies (pom.xml, build.gradle)
- Database access layers
- Authentication/authorization code
- API endpoints and controllers

**Targeted Audit:**
- Specific vulnerability type (SQL injection, XSS, etc.)
- Specific component (authentication, payment processing)
- Recent changes (git diff for new code)

### Step 2: OWASP Top 10 Checklist

#### A01:2021 - Broken Access Control
**What to Check:**
- Authorization checks on every endpoint
- Horizontal privilege escalation (user accessing other user's data)
- Vertical privilege escalation (user accessing admin functions)
- CORS misconfiguration
- Missing function-level access control

**Red Flags:**
```java
// BAD: No authorization check
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
    return userRepository.findById(id).orElseThrow();
}

// BAD: Using user input directly without validation
@GetMapping("/users/{id}/orders")
public List<Order> getOrders(@PathVariable Long id) {
    return orderRepository.findByUserId(id);  // Any user can access any user's orders!
}
```

**Good Patterns:**
```java
@GetMapping("/users/{id}")
@PreAuthorize("#id == authentication.principal.id or hasRole('ADMIN')")
public User getUser(@PathVariable Long id) {
    return userRepository.findById(id).orElseThrow();
}

@GetMapping("/users/me/orders")
public List<Order> getMyOrders(@AuthenticationPrincipal UserDetails user) {
    return orderRepository.findByUserId(user.getId());
}
```

#### A02:2021 - Cryptographic Failures
**What to Check:**
- Passwords stored in plaintext
- Weak hashing algorithms (MD5, SHA1)
- Sensitive data transmitted over HTTP
- Hardcoded encryption keys
- Sensitive data in logs

**Red Flags:**
```java
// BAD: Plaintext password
user.setPassword(request.getPassword());

// BAD: Weak hashing
String hash = DigestUtils.md5Hex(password);

// BAD: Hardcoded secret
String secret = "mySecretKey123";
```

**Good Patterns:**
```java
// Use BCrypt for password hashing
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12);
}

user.setPassword(passwordEncoder.encode(request.getPassword()));

// Externalize secrets
@Value("${jwt.secret}")
private String jwtSecret;

// Encrypt sensitive data at rest
@Convert(converter = SensitiveDataConverter.class)
private String socialSecurityNumber;
```

#### A03:2021 - Injection
**What to Check:**
- SQL injection in dynamic queries
- Command injection in Runtime.exec()
- LDAP injection
- XML injection
- Expression Language injection

**SQL Injection Red Flags:**
```java
// BAD: String concatenation in SQL
String sql = "SELECT * FROM users WHERE email = '" + email + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);

// BAD: Using + in JPA queries
String jpql = "SELECT u FROM User u WHERE u.email = '" + email + "'";
Query query = em.createQuery(jpql);

// BAD: String format in queries
String sql = String.format("SELECT * FROM users WHERE id = %s", userId);
```

**Good Patterns:**
```java
// GOOD: PreparedStatement with parameters
String sql = "SELECT * FROM users WHERE email = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, email);
ResultSet rs = pstmt.executeQuery();

// GOOD: Named parameters in JPA
@Query("SELECT u FROM User u WHERE u.email = :email")
User findByEmail(@Param("email") String email);

// GOOD: Spring Data JPA method names
User findByEmail(String email);
```

#### A04:2021 - Insecure Design
**What to Check:**
- Missing rate limiting
- No account lockout after failed attempts
- Weak session management
- Missing security headers
- Inadequate logging and monitoring

**Red Flags:**
```java
// BAD: No rate limiting on sensitive endpoints
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
    // Attacker can brute force passwords
    return authenticate(request);
}

// BAD: Predictable session IDs
String sessionId = userId + "_" + timestamp;
```

**Good Patterns:**
```java
// Rate limiting with bucket4j
@PostMapping("/login")
@RateLimiter(name = "loginRateLimit", fallbackMethod = "loginFallback")
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
    return authenticate(request);
}

// Account lockout
@Service
public class LoginAttemptService {
    private final LoadingCache<String, Integer> attemptsCache;

    public void loginFailed(String username) {
        int attempts = attemptsCache.get(username);
        attemptsCache.put(username, attempts + 1);
    }

    public boolean isBlocked(String username) {
        return attemptsCache.get(username) >= MAX_ATTEMPTS;
    }
}
```

#### A05:2021 - Security Misconfiguration
**What to Check:**
- Default credentials still active
- Unnecessary features enabled
- Stack traces exposed to users
- Missing security headers
- Outdated framework versions
- Excessive error details in responses

**Red Flags:**
```java
// BAD: Detailed error messages to clients
catch (Exception e) {
    return ResponseEntity.status(500).body(e.getMessage());
}

// BAD: Debug mode in production
spring.devtools.enabled=true

// BAD: Allowing all CORS origins
@CrossOrigin(origins = "*")
```

**Good Patterns:**
```java
// Security headers configuration
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .headers(headers -> headers
                .xssProtection(xss -> xss.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK))
                .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))
                .frameOptions(frame -> frame.deny())
                .httpStrictTransportSecurity(hsts -> hsts
                    .includeSubDomains(true)
                    .maxAgeInSeconds(31536000))
            );
        return http.build();
    }
}

// Generic error responses
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception e) {
    log.error("Error occurred", e);  // Log details server-side
    return ResponseEntity.status(500)
        .body(new ErrorResponse("An error occurred"));  // Generic message to client
}
```

#### A06:2021 - Vulnerable a

Related in Backend & APIs