# Java Web Framework Security Detection Module

> Security feature analysis based on Spring MVC, Shiro, and other frameworks
> Detection of security risks specific to framework features

## Spring MVC Security Detection

### Parameter Binding Risk Detection

#### Risk Pattern 1: @PathVariable used directly for sensitive operations
```java
// ❌ High Risk: PathVariable used directly in database queries
@GetMapping("/genCode/{tableName}")
public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) {
    byte[] data = genService.generatorCode(tableName);  // ❌ Used directly
    // ...
}

// Detection regex
- "@PathVariable.*String.*tableName"
- "@PathVariable.*String.*fileName"
- "@PathVariable.*String.*resource"
```

#### Risk Pattern 2: Auto parameter binding risks
```java
// ❌ Medium Risk: Auto parameter binding used for file operations
@RequestMapping("common/download")
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) {
    String filePath = Global.getDownloadPath() + fileName;  // ❌ Path concatenation
    FileUtils.writeBytes(filePath, response.getOutputStream());
}

// Detection regex
- "public.*\(String.*fileName"
- "public.*\(String.*path"
- "public.*\(String.*resource"
```

### Response Handling Risk Detection

#### Risk Pattern 3: Response header injection
```java
// ❌ Medium Risk: User input used in response headers
public String setFileDownloadHeader(HttpServletRequest request, String fileName) {
    // ...
    response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
}

// Detection regex
- "setHeader.*\+.*fileName"
- "addHeader.*\+.*userInput"
```

## Shiro Security Detection

### Permission Configuration Risk Detection

#### Risk Pattern 4: Improper anonymous access configuration
```java
// ❌ High Risk: Sensitive endpoints configured for anonymous access
filterChainDefinitionMap.put("/common/download", "anon");  // ❌ File download should require authentication

// Detection regex
- "filterChainDefinitionMap\.put.*download.*anon"
- "filterChainDefinitionMap\.put.*upload.*anon"
```

#### Risk Pattern 5: Remember Me configuration risk
```java
// ❌ Medium Risk: Hardcoded encryption key
cookieRememberMeManager.setCipherKey(Base64.decode("fCq+/xW488hMTCD+cmJ3aQ=="));

// Detection regex
- "setCipherKey.*Base64\.decode"
- "rememberMe.*hardcoded"
```

## MyBatis Security Detection

### SQL Injection Risk Detection

#### Risk Pattern 6: Data scope filter injection
```xml
<!-- ❌ High Risk: ${params.dataScope} directly concatenated -->
<select id="selectUserList" parameterType="SysUser" resultMap="SysUserResult">
    select * from sys_user where del_flag = '0'
    ${params.dataScope}  <!-- ❌ SQL injection risk -->
</select>

// Detection regex
- "\\$\\{params\\.dataScope\\}"
- "\\$\\{.*dataScope.*\\}"
```

#### Risk Pattern 7: Dynamic SQL concatenation risk
```xml
<!-- ❌ Medium Risk: Dynamic field name concatenation -->
<select id="orderBy" resultType="User">
    SELECT * FROM users ORDER BY ${field} ${sort}  <!-- ❌ Dynamic sorting risk -->
</select>

// Detection regex
- "ORDER BY\\s*\\$\\{"
- "GROUP BY\\s*\\$\\{"
```

## Security Remediation

### Spring MVC Security Remediation

#### Remediation 1: Parameter whitelist validation
```java
// ✓ Safe: PathVariable whitelist validation
@GetMapping("/genCode/{tableName}")
public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) {
    if (!isValidTableName(tableName)) {
        throw new SecurityException("Invalid table name");
    }
    byte[] data = genService.generatorCode(tableName);
}

private boolean isValidTableName(String name) {
    return name.matches("[a-zA-Z0-9_]+");  // ✓ Whitelist validation
}
```

#### Remediation 2: Path normalization
```java
// ✓ Safe: Path normalization processing
@RequestMapping("common/download")
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) {
    // Path normalization
    Path basePath = Paths.get(Global.getDownloadPath()).normalize();
    Path filePath = basePath.resolve(fileName).normalize();

    // Security check
    if (!filePath.startsWith(basePath)) {
        throw new SecurityException("Invalid file path");
    }

    FileUtils.writeBytes(filePath.toString(), response.getOutputStream());
}
```

### MyBatis Security Remediation

#### Remediation 3: Parameterized data scope
```xml
<!-- ✓ Safe: Use #{param} instead of ${param} -->
<select id="selectUserList" parameterType="SysUser" resultMap="SysUserResult">
    select * from sys_user where del_flag = '0'
    AND #{params.dataScope}  <!-- ✓ Parameterized query -->
</select>
```

#### Remediation 4: Business logic layer filtering
```java
// ✓ Safe: Handle data scope in business logic layer
@DataScope(tableAlias = "u")
public List<SysUser> selectUserList(SysUser user) {
    // Safely construct data scope conditions in AOP aspect
    return userMapper.selectUserList(user);
}
```

## Detection Command Set

### Spring MVC Detection Commands
```bash
# 1. Scan all controller methods
grep -rn "@.*Mapping" --include="*.java" | head -20

# 2. Check PathVariables
grep -rn "@PathVariable" --include="*.java" -A 2

# 3. Check file download endpoints
grep -rn "download\|Download" --include="*.java" | grep -E "Mapping|RequestMapping"

# 4. Check response header settings
grep -rn "setHeader\|addHeader" --include="*.java" | grep -v "security"
```

### Shiro Detection Commands
```bash
# 1. Check Shiro configuration
grep -rn "ShiroConfig" --include="*.java" -A 50

# 2. Check filter chain configuration
grep -rn "filterChainDefinitionMap" --include="*.java" -A 20

# 3. Check Remember Me configuration
grep -rn "rememberMe\|setCipherKey" --include="*.java"
```

### MyBatis Detection Commands
```bash
# 1. Check ${} usage
grep -rn "\\$\\{" --include="*.xml" | grep -v "pom.xml"

# 2. Check data scope annotation
grep -rn "@DataScope" --include="*.java" -B 2 -A 2

# 3. Check dynamic SQL
grep -rn "ORDER BY.*\\$\|GROUP BY.*\\$" --include="*.xml"
```

## Risk Rating Matrix

| Risk Type | Severity | Exploit Difficulty | Detection Difficulty | Fix Priority |
|----------|----------|-------------------|---------------------|-------------|
| @PathVariable injection | 🔴 High | Low | Medium | Fix Immediately |
| Path traversal download | 🔴 High | Low | Medium | Fix Immediately |
| Data scope SQL injection | 🔴 High | Medium | High | Fix Immediately |
| Response header injection | 🟡 Medium | Medium | Medium | Plan Fix |
| Remember Me hardcoded | 🟡 Medium | High | Low | Plan Fix |
| Anonymous access config | 🟡 Medium | Low | Low | Plan Fix |

## Framework Feature Notes

1. **Spring Boot Auto-Configuration**: Verify default security configuration is sufficient
2. **Shiro Permission Inheritance**: Check if permission inheritance relationships are correct
3. **MyBatis Plugins**: Verify security plugins are enabled
4. **AOP Aspect Ordering**: Check execution order of security aspects

---

## Minimum PoC Examples
```bash
# Path Traversal
curl "http://localhost:8080/common/download?fileName=../../../../etc/passwd"

# Permission Bypass (anonymous configuration)
curl -I "http://localhost:8080/admin"

# Data scope SQL Injection
curl "http://localhost:8080/system/user/list?dataScope=1 or 1=1"
```

Through this module's detection rules, security risks in Java web frameworks can be effectively identified, particularly subtle vulnerabilities related to framework features and configurations.
