SuperAPI AI Directory

external-gitcode-ascend-security-code-review

Security & auditing

View repository

Updated 10-15 17:19

About this skill

Multilingual Secure Code Review

Applicable Scenarios

  • Security Review: Perform secure code review on Python, C++, Shell, and Markdown files
  • Code Review: Check for security vulnerabilities during code review
  • Writing New Code: Write secure code and avoid common vulnerabilities
  • Compliance Checks: 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:

  1. Determine the review scope: Identify the language type of the target code (Python/C++/Shell/Markdown)
  2. Load the corresponding reference: Read the detailed review guide under references/ according to the language
  3. Check item by item: Execute according to the review focus and checklist for each language below
  4. Consult historical experience: For code related to inference services, read references/lessons-learned.md to troubleshoot known issue patterns
  5. Generate a review report: Generate a CSV report according to the output specification at the end of this file

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/ (did not use 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 Errors new char[size] No bounds checking
4 Format String Memory Read/Write printf(user_input), fprintf(stderr, var)
5 Uninitialized Variables Undefined Behavior Use without assignment after declaration
6 RAII/Resource Leaks 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 The combination of configuration parameters results in peak memory exceeding physical memory (CWE-400, CWE-770)
11 Special Token Injection Segmentation Fault/Crash Token pairing assumptions, 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 comparisons: Read references/shell.md

The 8 key areas covered by the review:

# Area Core Risk Key Search Pattern
1 Script Header Silent Failure Missing set -euo pipefail
2 Variable References Command Injection/Accidental Deletion $var (without "$var")
3 Command Injection Arbitrary Command Execution eval "$user_input"
4 Temporary Files Race Conditions > /tmp/fixed_name (without mktemp)
5 Permissions Unauthorized Access chmod 777, chmod 666
6 PATH Security Path Hijacking Critical commands not using absolute paths
7 Signal Handling Resource Leaks 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 comparisons: Read references/markdown.md

The 4 key areas covered by the review:

# Area 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 Base

Complete case analysis and inspection checklist: read references/lessons-learned.md

When reviewing inference service engine code, focus on 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, using hard indexing without validation
SEC-EXP-003 <|vision_start|><|video_pad|><|vision_end|> Breaks format assumptions CRITICAL Assumes the token sequence follows a private protocol format, and using fixed offsets to retrieve values causes out-of-bounds access

General Security Constraints (Constraints)

Must Comply (MUST)

  1. Input validation: validate all external input, never trust user data
  2. Parameterized queries: use parameterized queries to prevent injection attacks
  3. Least privilege: processes, files, and users use the minimum necessary privileges
  4. Secure defaults: use secure defaults for variable initialization and error handling
  5. Dependency audit: regularly scan dependencies for known vulnerabilities
  6. Sensitive information protection: manage keys, passwords, and Tokens through environment variables
  7. Log desensitization: do not record sensitive information such as passwords and keys in logs
  8. Error handling: error messages do not leak internal implementation details
  9. JSON nesting depth validation: validate nesting depth before/during parsing for all external JSON requests to prevent stack overflow and resource exhaustion attacks (CWE-674, CWE-400)
  10. Service request resource upper limit validation: the peak memory after combining service configuration parameters (maximum concurrency, request body limit, request header 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)
  11. Special Token input validation: special Tokens in scenarios such as multimodal/multi-turn dialogue (e.g., 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)

  1. Prohibit eval-type functions: Python eval()/exec()、Shell eval; C++ has no equivalent but dynamic code generation is prohibited
  2. Prohibit hardcoded keys: do not hardcode passwords, API Keys, or Tokens in code
  3. Prohibit committing sensitive files: .env, private keys and certificates must not be committed to version control
  4. Prohibit ignoring errors: exceptions must not be silently swallowed or return values ignored
  5. Prohibit overly broad permissions: do not use chmod 777、0.0.0.0 unrestricted listening
  6. 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 泄露
- [ ] 外部图片来源可信
- [ ] 无追踪像素

Recommended Tools Summary

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


Review Result Output

Review Process Requirements

When using this Skill to perform a security review on a code repository (i.e., the parameters include the 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

File name: security_code_review_report.csv Save location: In the root directory of the code repository being reviewed (i.e., under review <path> in <path> ) Encoding: UTF-8

The CSV must contain the following 9 columns (fixed headers):

编号,严重级别,漏洞类别,语言,文件路径,行号,问题描述,风险说明,建议修复方案
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 src/utils/file_utils.py
Line Number Line number where the problem code is located; separate multiple lines with commas 79, 40-44, 220-232
Problem Description Concisely describe the discovered problem pickle.loads() 反序列化来自共享内存的数据
Risk Description Explain the security risk that this problem may cause 攻击者可注入恶意 pickle payload 实现 RCE
Suggested Fix Specific fix suggestions and code examples 用 json.loads() 替代 pickle.loads()

CSV Format Requirements

  1. Comma-separated; field values containing commas must be wrapped in double quotes
  2. Double quotes inside field values must be escaped with two double quotes ("")
  3. The first row is the header row; each subsequent row is one finding
  4. Sort by severity level: CRITICAL → HIGH → MEDIUM → LOW
  5. Within the same level, arrange in numerical order
  6. File paths use relative paths (relative to the repository root directory)

Output process

After the review is complete, perform the following steps:

  1. Aggregate all findings: Collect the results of all review agents/scans
  2. Deduplicate and merge: Merge duplicate findings to ensure each record is unique
  3. Generate CSV: Generate the CSV file according to the above specification and write it to the target path
  4. 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
  5. Output summary: Report the file location and the statistical count 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 expressions
  • If the review targets only specific files rather than the entire repository, save the CSV to the directory where that file is located
  • 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