SuperAPI AI Directory

java-file-read-audit

Coding & development

View repository

Updated 10-16 06:52

About this skill

Java File Read Vulnerability Audit Tool

Inspect Java Web project source code, identify file read operation implementations, and detect arbitrary file read and path traversal vulnerabilities.

Core Requirements

This skill must fully analyze all file read-related code; omissions are not allowed.

  • ✅ Identify all file read entry points (BufferedReader/Scanner/Files)
  • ✅ Analyze the path source of each file operation
  • ✅ Detect all potential path traversal patterns
  • ✅ Provide a verification PoC for each vulnerability point
  • ❌ Omitting any file read operation is prohibited
  • ❌ Skipping decompilation steps is prohibited

Vulnerability Severity Classification Standards

See SEVERITY_RATING.md

  • Vulnerability ID format: {C/H/M/L}-FILE-{序号}
  • Severity level = f(reachability R, impact scope I, exploitation complexity C)
  • Score = R × 0.40 + I × 0.35 + C × 0.25, mapped to CVSS 3.1
Prefix CVSS 3.1 Meaning
🔴 C 9.0-10.0 Can directly lead to system compromise
🟠 H 7.0-8.9 Can cause major damage
🟡 M 4.0-6.9 Can cause certain damage
🔵 L 0.1-3.9 Security hardening recommendations

Skill Collaboration Workflow (CRITICAL)

java-file-read-audit should be executed after java-route-mapper, conducting the audit based on the already-organized route information.

┌─────────────────────────────────────────────────────────────────┐
│                    完整审计流程                                  │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  [步骤1] java-route-mapper                                      │
│     │                                                           │
│     │ 输出:                                                    │
│     │ ├─ 所有 HTTP 路由列表                                     │
│     │ ├─ 每个路由的参数定义                                     │
│     │ │   ├─ 参数名、类型                                       │
│     │ │   └─ JSON 内部字段                                      │
│     │ └─ Burp Suite 请求模板                                    │
│     │                                                           │
│     ↓                                                           │
│  [步骤2] java-file-read-audit(本技能)                         │
│     │                                                           │
│     │ 输入:java-route-mapper 的输出                            │
│     │                                                           │
│     │ 执行:                                                    │
│     │ ├─ 快速扫描文件操作                                       │
│     │ ├─ 参数-文件路径映射分析                                  │
│     │ ├─ 检查每个 String 参数是否用作文件路径                   │
│     │ └─ 执行条件分析                                           │
│     │                                                           │
│     ├─── 需要深入追踪 ───→ java-route-tracer                    │
│     │                           │                               │
│     │    ←── 返回调用链信息 ────┘                               │
│     │                                                           │
│     ↓                                                           │
│  [步骤3] 输出综合审计报告                                       │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Input Dependencies (from java-route-mapper)

Before starting the audit, you must first check whether the output file of java-route-mapper already exists:

{project_name}_audit/
├── route_mapper/
│   ├── {project_name}_route_mapper_{timestamp}.md    ← 主索引(先读此文件定位模块详情)
│   ├── {module_name}/
│   │   └── {project_name}_module_{module_name}_{timestamp}.md  ← 模块详情
│   └── webservice/
│       └── {project_name}_ws_{service_name}_{timestamp}.md
└── file_read_audit/
    └── {project_name}_file_read_audit_{timestamp}.md  ← 本技能输出

If the route_mapper output does not exist, you must first run:

Skill(skill="java-route-mapper", args="--project {project_path}")

Key Information Obtained from route_mapper

Information Purpose
Route path Locate Controller/Action entry points
Parameter name + type Identify high-risk String-type parameters
JSON internal fields Identify nested parameters (such as fileInfo.path)
Parameter purpose description Determine whether it is used for file paths

Workflow (Three Phases)

Phase 1: Quick Scan (Execute First)

Goal: Quickly locate file read-related code without missing key points.

# 1.1 搜索文件读取方法
grep -ri "BufferedReader\|FileReader\|FileInputStream" --include="*.java"
grep -ri "Scanner.*File\|Scanner.*Path" --include="*.java"
grep -ri "Files.lines\|Files.readAllLines\|Files.readAllBytes" --include="*.java"

# 1.2 搜索文件下载/读取接口
grep -ri "download\|readFile\|getFile\|viewFile" --include="*.java"
grep -ri "@RequestMapping.*download\|@GetMapping.*download" --include="*.java"

# 1.3 搜索路径拼接模式
grep -ri "new File.*\+" --include="*.java"
grep -ri "Paths.get.*\+" --include="*.java"
grep -ri "File.separator" --include="*.java"

# 1.4 搜索路径参数
grep -ri "filePath\|fileName\|file\|path" --include="*.java" | grep "@RequestParam\|@PathVariable"

Output: High-risk file list (sorted by priority)

Priority File Type Audit Focus
P0 *Controller.java Methods containing download/readFile in filePath, fileName parameters
P1 *Service.java, *ServiceImpl.java File path processing logic
P2 *Util.java, *Helper.java General file read methods
P3 *Dao.java, *Repository.java Configuration file reading

Phase 2: Parameter-File Path Mapping Check

Based on the output of java-route-mapper, check whether each parameter is used as a file path.

2.1 High-Risk Parameter Identification

Extract all String-type parameters from the route_mapper output:

Parameter Source Parameter Name Type File Read Vulnerability Possibility
@RequestParam filePath String High risk - Used directly as path
@RequestParam fileName String High risk - Filename concatenation
@RequestParam file String High risk - File path
@PathVariable path String High risk - URL path parameter
JSON fileInfo.path String High risk - JSON internal field

2.2 Parameter tracing

For each high-risk parameter, trace its usage in the code:

HTTP 参数: filePath (String)
    ↓ 传递
Controller.download(filePath)
    ↓ 传递
Service.readFile(filePath)
    ↓ 拼接
basePath + File.separator + filePath
    ↓ 使用
new FileInputStream(fullPath)  ← 文件读取点

2.3 File read point inspection

For each file read point found in phase 1, check:

  1. Is the file path controllable?

    • Entirely from user input → High risk
    • Base path fixed + user input filename → Medium risk
    • Fully hardcoded → Safe
  2. Is there path validation?

    • Whitelist directory restriction → Safe
    • File extension validation → May be bypassed
    • No validation → High risk
  3. Are path traversal characters filtered?

    • Filter ../, ..\\ → Possibly safe (bypass needs testing)
    • No filtering → High risk

Phase 3: In-depth inspection and reporting

3.1 Trigger java-route-tracer

When the following situations are found, call java-route-tracer to obtain the complete call chain:

Trigger condition Invocation method
Parameters are passed through multiple layers Skill(skill="java-route-tracer", args="--route {route}")
Path concatenation logic is complex Skill(skill="java-route-tracer", args="--route {route}")
Validation logic is unclear Skill(skill="java-route-tracer", args="--route {route}")

3.2 Execution condition check

After discovering a file read, the execution conditions must be checked (see subsequent chapters for details).

3.3 Generate report

Integrate all analysis results and generate a comprehensive audit report.


File read method identification

For detailed rules, see FILE_READ_METHODS.md

Method category Identification feature Risk point
BufferedReader new BufferedReader(new FileReader(path)) Source of path parameter
Scanner new Scanner(new FileReader(path)) Source of path parameter
Files.lines Files.lines(Path.of(path)) Source of path parameter
Files.readAllLines Files.readAllLines(Path.of(path)) Source of path parameter
Files.readAllBytes Files.readAllBytes(Path.of(path)) Source of path parameter
FileInputStream new FileInputStream(path) Source of path parameter

Decompilation phase (CRITICAL)

When source code is unavailable, the CFR decompiler must be used to decompile file operation-related classes.

For detailed strategy, see DECOMPILE_STRATEGY.md

Decompilation tool invocation

# 反编译单个 Controller/Service 类
java -jar {CFR_JAR} /path/to/FileController.class --outputdir {output_path}/decompiled

# 反编译文件操作相关目录
find /path/to/WEB-INF/classes/com/example/controller -name "*.class" | xargs java -jar {CFR_JAR} --outputdir {output_path}/decompiled

# 反编译多个指定文件
java -jar {CFR_JAR} /path/to/FileController.class /path/to/FileService.class /path/to/FileUtil.class --outputdir {output_path}/decompiled

Output file naming convention:

  • Decompiled files are saved in the {output_dir} directory
  • Filename format:{ClassName}.java
  • Preserve the original package structure:com/example/controller/FileController.java

Classes that must be decompiled

Type Match pattern Purpose
Controller *Controller.class Extract routes and parameter definitions
Service *Service.class, *ServiceImpl.class Trace file operation call chains
Utility class *FileUtil*.class, *FileHelper*.class Extract common file read methods
DAO *Dao.class, *Repository.class Configuration file read logic

Execution condition check (CRITICAL - avoid false positives)

After discovering file read code, you must check whether the code will actually be executed!

1. Path validation check

After discovering a file read, you must check whether path validation exists:

Check pattern Code feature Handling method
Whitelist directory path.startsWith("/upload/") Marked as restricted path
Extension validation fileName.endsWith(".txt") Check whether it can be bypassed
Path normalization new File(path).getCanonicalPath() Check whether it is complete
No validation Directly uses user input Marked as high risk

2. Code path reachability analysis

Trace the complete path from the entry point to file reading, and check:

Check item Description Impact
Early return if (!validate()) return; May prevent execution
Exception thrown throw new SecurityException() Code does not execute
Condition not satisfied if (false) and other dead code Code does not execute
Permission restriction Accessible only to administrators Permissions need to be confirmed

3. Conclusion classification (must be marked)

Status Meaning Follow-up action
⚠️ Pending verification Code contains file reading, but execution conditions are unconfirmed Target environment needs to be confirmed
✅ Confirmed exploitable Verified that the code path executes and has no effective validation Perform vulnerability exploitation testing
❌ Not exploitable Effective security validation exists Mark the reason and lower the priority
🔍 Environment dependency The vulnerability exists but is exploitable only under specific conditions Mark environmental conditions

Path traversal detection rule quick reference

⚠️ High-risk pattern detection (CRITICAL)

Dangerous pattern Code example Risk description
Direct concatenation basePath + fileName Unfiltered ../
File.separator concatenation basePath + File.separator + fileName Path traversal possible
String formatting String.format("%s/%s", base, file) Unfiltered ../
Path.of concatenation Path.of(basePath, fileName) Path traversal possible
Paths.get concatenation Paths.get(basePath).resolve(fileName) Normalization needs to be checked

⚠️ Safe vs dangerous patterns

Type Dangerous pattern Safe pattern
Path concatenation basePath + fileName Whitelist validation + normalization
File reading new FileInputStream(userInput) getCanonicalPath() validation
Path traversal No filtering ../ path.contains("..") interception
Extension No validation Whitelist extension

Safe pattern example:

// 安全: 路径规范化 + 白名单目录校验
String basePath = "/var/uploads";
File file = new File(basePath, fileName);
String canonicalPath = file.getCanonicalPath();
if (!canonicalPath.startsWith(basePath)) {
    throw new SecurityException("Path traversal detected");
}

Audit checklist (to prevent omissions)

Dangerous patterns that must be searched

At the start of the audit, the following searches must be performed:

# 文件读取方法检测
grep -r "FileInputStream\|FileReader\|BufferedReader" --include="*.java"
grep -r "Files.readAllBytes\|Files.readAllLines\|Files.lines" --include="*.java"

# 路径拼接检测
grep -r "new File.*\+" --include="*.java"
grep -r "File.separator" --include="*.java"

# 下载接口检测
grep -r "download\|readFile\|getFile" --include="*.java"

Data flow tracing (load java-route-tracer when needed)

When parameter tracing is needed

When the following situations are found,the java-route-tracer skill must be loaded for in-depth tracing:

Scenario Description Action
Parameters are passed through multiple layers HTTP parameters are passed through multiple layers Controller → Service → Util and then used as a file path Load java-route-tracer
Path concatenation is complex Path concatenation and conversion in multiple places Load java-route-tracer
Validation logic is scattered Validation logic is in different classes/methods Load java-route-tracer

Report generation

Output a single comprehensive audit report file:

{project_name}_audit/file_read_audit/
└── {route_name}/
    └── {project_name}_file_read_audit_{timestamp}.md      # 综合审计报告

Route name description:

  • The route name is extracted from the route path, removing the leading slash and special characters
  • For example:/api/file/download → api_file_download
  • For example:/download.action → download

Output format

Strictly follow the fill-in template in references/OUTPUT_TEMPLATE.md to generate the output file.

  • File name format: {project_name}_file_read_audit_{YYYYMMDD_HHMMSS}.md
  • Do not modify the template structure, do not add or remove sections, and do not adjust the order
  • All [fill in] placeholders must be replaced with actual content
  • General specification reference: java-shared/OUTPUT_STANDARD.md
  • Vulnerability aggregation rule reference: java-shared/VULNERABILITY_GROUPING.md, multiple entry points with the same root cause are merged into one vulnerability ID and the "affected entry points" are listed; entry points with different conditions are split.

Verification checklist

Before marking the audit as complete, the following checks must be performed:

Code analysis checks

  • All Controller classes have been analyzed
  • All Service/Util classes have been analyzed
  • Every file operation has a path source annotation

Execution condition checks (CRITICAL)

  • Path validation logic has been checked
  • Code path reachability has been checked
  • The exploitability status of each vulnerability has been annotated

Vulnerability detection checks

  • All file read methods have been detected
  • All path concatenation patterns have been detected
  • All parameter sources have been traced

Report completeness checks

  • The comprehensive audit report has been generated and has passed the self-check list at the end of OUTPUT_TEMPLATE.md
  • The decompiled output file paths have been annotated

References