Applicable Scenarios
- Security review: Perform security code review on Python, C++, Shell, and Markdown files
- Code Review: Check for security vulnerabilities during code review
- New code writing: Write secure code and avoid common vulnerabilities
- Compliance check: Meet security compliance requirements (CWE, CERT, OWASP)
- CI/CD integration: Integrate security scanning tools into the pipeline
Review Workflow
When performing a security review, proceed with the following steps:
- Determine the review scope: Identify the language type of the target code (Python/C++/Shell/Markdown)
- Load the corresponding reference: Read the detailed review guide under
references/according to the language - Check item by item: Execute according to the review points and checklists for each language below
- Consult historical experience: For inference-service-related code, read
references/lessons-learned.mdto troubleshoot known issue patterns - Generate a review report: Generate a CSV report according to the output specification at the end of this document
Python Security Review
Detailed code examples and secure/insecure comparisons: read
references/python.md
The 10 key areas covered by the review:
| # | Area | Core risk | Key search pattern |
|---|---|---|---|
| 1 | Code injection | Arbitrary code execution | eval(, exec(, shell=True |
| 2 | SQL injection | Data leakage/tampering | f"SELECT, cursor.execute(f" |
| 3 | Deserialization | RCE | pickle.loads, yaml.load( (no safe_load) |
| 4 | Path traversal | Arbitrary file read | os.path.join( + user input, no realpath validation |
| 5 | Sensitive information leakage | Key exposure | Hardcoded API_KEY=, PASSWORD=, logger.*(password |
| 6 | assert misuse | Permission bypass | assert user.is_admin, assert.*auth |
| 7 | Temporary files | Race/symlink attacks | open("/tmp/ (not using tempfile) |
| 8 | ReDoS | CPU exhaustion | (a+)+, (.*)*, nested quantifiers |
| 9 | JSON nesting depth | Stack overflow/resource exhaustion | json.loads( no depth limit (CWE-674, CWE-400) |
| 10 | Special token injection | Process crash/DoS | np.where(np.equal(input_ids, no pairing validation (CWE-129, CWE-248) |
Python security tools:
| Tool | Purpose | Command |
|---|---|---|
| bandit | Static security analysis | bandit -r src/ |
| pip-audit | Dependency vulnerability scanning | pip-audit |
| pylint | Code quality + partial security rules | pylint src/ |
| mypy | Type checking to prevent type confusion | mypy src/ |
| semgrep | Custom security rules | semgrep --config=p/python |
C++ Security Review
Detailed code examples and secure/insecure comparisons: read
references/cpp.md
The 11 key areas covered by the review:
| # | Domain | Core Risk | Key Search Pattern |
|---|---|---|---|
| 1 | Buffer Overflow | Code Execution | strcpy(, sprintf(, gets( |
| 2 | Memory Management | UAF/Double-free | new/delete (non-smart pointer), raw pointer |
| 3 | Integer Overflow | Buffer Allocation Error | new char[size] No bounds checking |
| 4 | Format String | Memory Read/Write | printf(user_input), fprintf(stderr, var) |
| 5 | Uninitialized Variable | Undefined Behavior | Use after declaration without assignment |
| 6 | RAII/Resource Leak | Resource Exhaustion | fopen/fclose, mutex.lock()/.unlock() |
| 7 | Thread Safety | Data Race | Non- atomic cross-thread variables, lock-free shared data |
| 8 | Type Casting | Type Confusion | C-style cast (Type*)ptr, especially downcasting |
| 9 | JSON Nesting Depth | Stack Overflow | nlohmann::json::parse( No depth limit (CWE-674) |
| 10 | Service Resource Limits | OOM | Configuration parameter combination peak memory exceeds physical memory (CWE-400, CWE-770) |
| 11 | Special Token Injection | Segmentation Fault/Crash | Token pairing assumption, fixed offset access (CWE-129, CWE-248) |
C++ security tools:
| Tool | Purpose | Command/Usage |
|---|---|---|
| AddressSanitizer | Memory Error Detection | -fsanitize=address |
| ThreadSanitizer | Data Race Detection | -fsanitize=thread |
| UBSanitizer | Undefined Behavior Detection | -fsanitize=undefined |
| Valgrind | Memory Leak Detection | valgrind --leak-check=full ./app |
| cppcheck | Static Analysis | cppcheck --enable=all src/ |
| clang-tidy | Linter + Security Rules | clang-tidy -checks='*' src/*.cpp |
| Coverity | Enterprise-grade Static Analysis | CI Integration |
Shell Security Review
Detailed code examples and secure/insecure comparison: Read
references/shell.md
The 8 key areas covered by the review:
| # | Domain | Core Risk | Key Search Pattern |
|---|---|---|---|
| 1 | Script Header | Silent Failure | Missing set -euo pipefail |
| 2 | Variable Reference | Command Injection/Accidental Deletion | $var (not using "$var") |
| 3 | Command Injection | Arbitrary Command Execution | eval "$user_input" |
| 4 | Temporary File | Race Condition | > /tmp/fixed_name (not using mktemp) |
| 5 | Permissions | Unauthorized Access | chmod 777, chmod 666 |
| 6 | PATH Safety | Path Hijacking | Critical commands not using absolute paths |
| 7 | Signal Handling | Resource Leak | Missing trap cleanup EXIT |
| 8 | Input Validation | Path Traversal | Unvalidated $filename directly cat |
Shell security tools:
| Tool | Purpose | Command |
|---|---|---|
| ShellCheck | Shell Script Static Analysis | shellcheck script.sh |
| shfmt | Shell Formatting | shfmt -d script.sh |
Markdown Security Review
Detailed code examples and secure/insecure comparison: Read
references/markdown.md
The 4 key areas covered by the review:
| # | Domain | Core Risk | Key Search Pattern |
|---|---|---|---|
| 1 | XSS injection | Script execution | <script>, <iframe>, onerror=, onmouseover= |
| 2 | Link security | XSS/phishing | javascript:, data:, vbscript: |
| 3 | Sensitive information | Key leakage | sk-, ghp_, AKIA, internal IP/URL |
| 4 | Image security | Tracking/DoS | External tracking pixels, oversized images |
Historical security issue experience database
Complete case analysis and troubleshooting checklist: read
references/lessons-learned.md
When reviewing inference service engine code, focus on investigating the following known issue patterns:
| No. | Issue | Severity | Key lesson |
|---|---|---|---|
| SEC-EXP-001 | Configuration parameter combination causes OOM | CRITICAL | 峰值内存 = maxReqs × bodyLimit × JSON放大系数, each parameter is individually reasonable but the combination exceeds physical memory |
| SEC-EXP-002 | <|begin_of_image|> no <|end_of_image|> causes DoS |
CRITICAL | Assumes special tokens appear in pairs, uses hard indexing without validation |
| SEC-EXP-003 | <|vision_start|><|video_pad|><|vision_end|> breaks format assumptions |
CRITICAL | Assumes token sequences follow a private protocol format, using fixed offsets to retrieve values causes out-of-bounds |
General security constraints (Constraints)
Must comply (MUST)
- Input validation: Validate all external input, never trust user data
- Parameterized queries: Use parameterized queries to prevent injection attacks
- Least privilege: Processes, files, and users use the minimum necessary privileges
- Secure defaults: Variable initialization and error handling use secure default values
- Dependency auditing: Regularly scan dependencies for known vulnerabilities
- Sensitive information protection: Keys, passwords, and Tokens are managed through environment variables
- Log masking: Do not record sensitive information such as passwords and keys in logs
- Error handling: Error messages do not leak internal implementation details
- JSON nesting depth validation: Validate nesting depth for all external JSON requests before/during parsing to prevent stack overflow and resource exhaustion attacks (CWE-674, CWE-400)
- Service-based request resource upper limit validation: The peak memory after combining service configuration parameters (maximum concurrency, request body upper limit, request header upper limit, etc.) must be less than the available memory of the deployment environment; the memory amplification factor of deserialization libraries such as JSON/XML must be considered (CWE-400, CWE-770)
- Special Token input validation: Special Tokens in scenarios such as multimodal/multi-turn dialogue (such as begin/end_of_image, vision_start/end, etc.) must validate pairing completeness and sequence format validity; implicit format assumptions about Token sequences are prohibited; the framework layer must provide a fallback to catch IndexError/out_of_range to prevent process crashes (CWE-129, CWE-248, CWE-20)
Prohibitions (MUST NOT)
- Prohibit eval-type functions: Python
eval()/exec()、Shelleval, C++ has no equivalent but dynamic code generation is prohibited - Prohibit hardcoded keys: Do not hardcode passwords, API Keys, or Tokens in code
- Prohibit committing sensitive files:
.env, private keys and certificates must not be committed to version control - Prohibit ignoring errors: Do not silently swallow exceptions or ignore return values
- Prohibit overly broad permissions: Do not use
chmod 777、0.0.0.0unrestricted listening - Prohibit the use of deprecated insecure functions:
gets(),sprintf(),strcpy(), etc.
Security Review Checklist
Python
- [ ] 无 eval()/exec() 使用不受信任的输入
- [ ] 无 pickle.loads() 加载不受信任的数据
- [ ] 使用 yaml.safe_load() 替代 yaml.load()
- [ ] subprocess 调用不使用 shell=True
- [ ] SQL 查询使用参数化方式
- [ ] 文件路径操作有路径遍历防护
- [ ] 无硬编码的密钥/密码
- [ ] 日志不记录敏感信息
- [ ] 未使用 assert 进行安全/权限相关检查
- [ ] 依赖已通过 pip-audit/bandit 扫描
- [ ] 正则表达式无 ReDoS 风险
- [ ] 临时文件使用 tempfile 模块
- [ ] JSON 请求解析入口有嵌套深度限制(建议 ≤ 32 层)
- [ ] 递归遍历 JSON 数据结构有深度保护
- [ ] 多模态特殊 Token(begin/end_of_image、vision_start/end 等)校验了配对完整性,不假设成对出现
- [ ] 推理请求处理路径有框架层 IndexError/ValueError/KeyError 兜底捕获,防止单请求异常导致进程崩溃
C++
- [ ] 无缓冲区溢出风险 (strcpy → strncpy/std::string)
- [ ] 使用智能指针管理内存
- [ ] 无 use-after-free / double-free
- [ ] 整数运算有溢出检查
- [ ] printf 系列函数使用固定格式字符串
- [ ] 所有变量在使用前初始化
- [ ] 资源管理遵循 RAII 原则
- [ ] 多线程代码无数据竞争
- [ ] 使用 C++ 风格类型转换 (static_cast/dynamic_cast)
- [ ] 编译启用安全选项 (-Wall -Werror -fsanitize=address)
- [ ] JSON 请求解析入口有嵌套深度限制(建议 ≤ 32 层)
- [ ] 递归遍历 JSON 数据结构有深度参数并设上限
- [ ] 服务配置参数组合后峰值内存不超过部署环境可用内存(考虑 JSON 放大系数)
- [ ] 存在运行时内存水位监控或请求准入控制机制
- [ ] 多模态特殊 Token(boi/eoi、vision_start/end 等)校验了配对完整性和序列格式,不做隐式格式假设
- [ ] model forward / pre-processing 路径有框架层 std::out_of_range/std::invalid_argument 兜底 catch,防止进程崩溃
Shell
- [ ] 脚本使用 set -euo pipefail
- [ ] 所有变量使用双引号包裹 ("$var")
- [ ] 无 eval 使用用户输入
- [ ] 临时文件使用 mktemp
- [ ] 文件权限不超过 755(脚本)/ 644(配置)
- [ ] 关键命令使用绝对路径
- [ ] 有 trap 清理机制
- [ ] 输入经过验证和过滤
- [ ] 通过 ShellCheck 无警告
- [ ] 不使用 . 或空目录在 PATH 中
Markdown
- [ ] 无内嵌 <script>/<iframe> 标签
- [ ] 无 javascript:/data: 协议链接
- [ ] 无硬编码密钥/密码/Token
- [ ] 无内部 IP 地址或内部 URL 泄露
- [ ] 外部图片来源可信
- [ ] 无追踪像素
Summary of Recommended Tools
| Language | Tool | Type | Description |
|---|---|---|---|
| Python | bandit | Static Analysis | Python security vulnerability detection |
| Python | pip-audit | Dependency Scanning | Python dependency vulnerability check |
| Python | semgrep | Rule Engine | Custom security rule matching |
| Python | mypy | Type Checking | Type safety, preventing type confusion |
| C++ | AddressSanitizer | Runtime Detection | Memory error detection |
| C++ | ThreadSanitizer | Runtime Detection | Data race detection |
| C++ | cppcheck | Static Analysis | C/C++ static analysis |
| C++ | clang-tidy | Linter | Code quality + security rules |
| C++ | Valgrind | Runtime Detection | Memory leak detection |
| Shell | ShellCheck | Static Analysis | Shell script security analysis |
| General | git-secrets | Pre-commit Hook | Prevent committing secrets |
| General | trufflehog | Secret Scanning | Scan code for secrets |
| General | gitleaks | Secret Scanning | Git repository secret leak detection |
| Markdown | markdownlint | Linter | Markdown format check |
Reference Standards
- CWE Top 25
- OWASP Top 10
- CERT C++ Secure Coding
- CERT C Secure Coding
- Bandit Documentation
- ShellCheck Wiki
Review Result Output (Output)
Review Process Requirements
When using this Skill to perform a security review on a code repository (i.e., the parameters include review keyword), after completing all reviews, automatically save the results as a CSV file. This is the final required step of the review process.
CSV Output Specification
Filename: security_code_review_report.csv
Save location: In the root directory of the code repository under review (i.e., review <path> in <path> under)
Encoding: UTF-8
The CSV must contain the following 9 columns (fixed header):
编号,严重级别,漏洞类别,语言,文件路径,行号,问题描述,风险说明,建议修复方案
| Column Name | Description | Example Value |
|---|---|---|
| ID | Unique ID, format is 严重级别首字母-序号 |
C-01, H-05, M-12, L-03 |
| Severity Level | Four levels:CRITICAL / HIGH / MEDIUM / LOW |
CRITICAL |
| Vulnerability Category | Security vulnerability classification name | 命令注入, 不安全反序列化, 线程安全, 路径遍历 |
| Language | Code language/file type | Python, C++, Shell, Markdown, Docker, Config |
| File Path | File path relative to the repository root directory | src/utils/file_utils.py |
| Line Number | Line number where the problematic code is located, multiple lines separated by commas | 79, 40-44, 220-232 |
| Issue Description | Concisely describe the discovered issue | pickle.loads() 反序列化来自共享内存的数据 |
| Risk Description | Explain the security risk that the issue may cause | 攻击者可注入恶意 pickle payload 实现 RCE |
| Suggested Fix | Specific fix suggestions and code examples | 用 json.loads() 替代 pickle.loads() |
CSV Format Requirements
- Comma-separated, field values containing commas are wrapped in double quotes
- Double quotes inside field values are escaped with two double quotes (
"") - The first row is the header row, and each subsequent row is one finding
- Sort by severity level: CRITICAL → HIGH → MEDIUM → LOW
- Within the same level, sort by number order
- File paths use relative paths (relative to the repository root directory)
Output process
After the review is complete, perform the following steps:
- Aggregate all findings: Collect the results from all review agents/scans
- Deduplicate and merge: Merge duplicate findings to ensure each record is unique
- Generate CSV: Generate the CSV file according to the above specification and write it to the target path
- Validate CSV: Use the Python csv module to verify that the file format is correct and that the number of rows matches the number of findings
- Output summary: Report the file location and the statistical counts for each severity level to the user
Example output
编号,严重级别,漏洞类别,语言,文件路径,行号,问题描述,风险说明,建议修复方案
C-01,CRITICAL,不安全反序列化,Python,src/utils/share_memory.py,79,"pickle.loads() 反序列化来自共享内存的数据","攻击者可注入恶意 pickle payload 实现 RCE","用 json.loads() 替代 pickle.loads()"
H-01,HIGH,命令注入,Shell,scripts/run.sh,52,"eval 执行含用户输入的命令字符串","模型路径含 shell 元字符时可注入任意命令","改用 bash 数组构建命令, 消除 eval"
M-01,MEDIUM,线程安全,C++,src/thread_pool.h,45,"m_shutdown 为非原子 bool 跨线程读写","数据竞争导致工作线程可能无法退出","改为 std::atomic<bool>"
L-01,LOW,临时文件安全,Python,tests/test_utils.py,30,"硬编码 /tmp 路径","共享 CI 环境中符号链接攻击风险","使用 tempfile.mkdtemp()"
Notes
- Even if the review finds no issues, a CSV file should still be generated (containing only the header row), and the user should be informed that "no security issues were found"
- The CSV file is for manual review,descriptions must be clear and specific, avoiding vague statements
- If the review targets only a specific file rather than the entire repository, save the CSV to the directory containing that file
- After generating the CSV, use a Python script to validate the format to ensure it can be opened correctly by Excel/WPS
Metadata
- Version: 2.0.0
- Last updated: 2026-04-24
- Languages: Python, C++, Shell/Bash, Markdown
- Tags:
#security#code-review#python#cpp#shell#markdown#OWASP#CWE