owasp-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OWASP Security Best Practices Skill

OWASP安全最佳实践技能

Apply these security standards when writing or reviewing code.
在编写或审查代码时应用这些安全标准。

Quick Reference: OWASP Top 10:2025

快速参考:OWASP Top 10:2025

#VulnerabilityKey Prevention
A01Broken Access ControlDeny by default, enforce server-side, verify ownership
A02Security MisconfigurationHarden configs, disable defaults, minimize features
A03Supply Chain FailuresLock versions, verify integrity, audit dependencies
A04Cryptographic FailuresTLS 1.2+, AES-256-GCM, Argon2/bcrypt for passwords
A05InjectionParameterized queries, input validation, safe APIs
A06Insecure DesignThreat model, rate limit, design security controls
A07Auth FailuresMFA, check breached passwords, secure sessions
A08Integrity FailuresSign packages, SRI for CDN, safe serialization
A09Logging FailuresLog security events, structured format, alerting
A10Exception HandlingFail-closed, hide internals, log with context
#漏洞类型核心防护措施
A01访问控制失效默认拒绝策略,服务器端强制校验,验证资源归属
A02安全配置错误加固配置,禁用默认设置,最小化功能模块
A03供应链故障锁定版本,校验完整性,审计依赖项
A04加密机制失效使用TLS 1.2+、AES-256-GCM,密码采用Argon2/bcrypt哈希
A05注入攻击参数化查询,输入校验,使用安全API
A06不安全设计威胁建模,速率限制,设计安全控制机制
A07身份验证故障多因素认证(MFA),检查泄露密码库,安全会话管理
A08完整性故障包签名,CDN资源使用SRI,安全序列化
A09日志记录故障记录安全事件,结构化格式,告警机制
A10异常处理不当故障闭合策略,隐藏内部细节,带上下文日志记录

Security Code Review Checklist

安全代码审查检查清单

When reviewing code, check for these issues:
审查代码时,需检查以下问题:

Input Handling

输入处理

  • All user input validated server-side
  • Using parameterized queries (not string concatenation)
  • Input length limits enforced
  • Allowlist validation preferred over denylist
  • 所有用户输入均在服务器端完成校验
  • 使用参数化查询(而非字符串拼接)
  • 强制限制输入长度
  • 优先使用白名单校验而非黑名单

Authentication & Sessions

身份验证与会话

  • Passwords hashed with Argon2/bcrypt (not MD5/SHA1)
  • Session tokens have sufficient entropy (128+ bits)
  • Sessions invalidated on logout
  • MFA available for sensitive operations
  • 密码使用Argon2/bcrypt哈希(而非MD5/SHA1)
  • 会话令牌具备足够熵值(128位以上)
  • 登出时销毁会话
  • 敏感操作支持多因素认证(MFA)

Access Control

访问控制

  • Authorization checked on every request
  • Using object references user cannot manipulate
  • Deny by default policy
  • Privilege escalation paths reviewed
  • 每个请求均校验授权
  • 使用用户无法篡改的对象引用
  • 采用默认拒绝策略
  • 审查权限提升路径

Data Protection

数据保护

  • Sensitive data encrypted at rest
  • TLS for all data in transit
  • No sensitive data in URLs/logs
  • Secrets in environment/vault (not code)
  • 敏感数据静态加密
  • 所有传输数据使用TLS
  • URL/日志中不包含敏感数据
  • 密钥存储在环境变量/密钥管理系统(而非代码中)

Error Handling

错误处理

  • No stack traces exposed to users
  • Fail-closed on errors (deny, not allow)
  • All exceptions logged with context
  • Consistent error responses (no enumeration)
  • 不向用户暴露堆栈跟踪
  • 错误时采用故障闭合策略(拒绝而非允许)
  • 所有异常均带上下文日志记录
  • 统一错误响应(避免信息枚举)

Secure Code Patterns

安全代码模式

SQL Injection Prevention

SQL注入防护

python
undefined
python
undefined

UNSAFE

UNSAFE

cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

SAFE

SAFE

cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
undefined
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
undefined

Command Injection Prevention

命令注入防护

python
undefined
python
undefined

UNSAFE

UNSAFE

os.system(f"convert {filename} output.png")
os.system(f"convert {filename} output.png")

SAFE

SAFE

subprocess.run(["convert", filename, "output.png"], shell=False)
undefined
subprocess.run(["convert", filename, "output.png"], shell=False)
undefined

Password Storage

密码存储

python
undefined
python
undefined

UNSAFE

UNSAFE

hashlib.md5(password.encode()).hexdigest()
hashlib.md5(password.encode()).hexdigest()

SAFE

SAFE

from argon2 import PasswordHasher PasswordHasher().hash(password)
undefined
from argon2 import PasswordHasher PasswordHasher().hash(password)
undefined

Access Control

访问控制

python
undefined
python
undefined

UNSAFE - No authorization check

UNSAFE - No authorization check

@app.route('/api/user/<user_id>') def get_user(user_id): return db.get_user(user_id)
@app.route('/api/user/<user_id>') def get_user(user_id): return db.get_user(user_id)

SAFE - Authorization enforced

SAFE - Authorization enforced

@app.route('/api/user/<user_id>') @login_required def get_user(user_id): if current_user.id != user_id and not current_user.is_admin: abort(403) return db.get_user(user_id)
undefined
@app.route('/api/user/<user_id>') @login_required def get_user(user_id): if current_user.id != user_id and not current_user.is_admin: abort(403) return db.get_user(user_id)
undefined

Error Handling

错误处理

python
undefined
python
undefined

UNSAFE - Exposes internals

UNSAFE - Exposes internals

@app.errorhandler(Exception) def handle_error(e): return str(e), 500
@app.errorhandler(Exception) def handle_error(e): return str(e), 500

SAFE - Fail-closed, log context

SAFE - Fail-closed, log context

@app.errorhandler(Exception) def handle_error(e): error_id = uuid.uuid4() logger.exception(f"Error {error_id}: {e}") return {"error": "An error occurred", "id": str(error_id)}, 500
undefined
@app.errorhandler(Exception) def handle_error(e): error_id = uuid.uuid4() logger.exception(f"Error {error_id}: {e}") return {"error": "An error occurred", "id": str(error_id)}, 500
undefined

Fail-Closed Pattern

故障闭合模式

python
undefined
python
undefined

UNSAFE - Fail-open

UNSAFE - Fail-open

def check_permission(user, resource): try: return auth_service.check(user, resource) except Exception: return True # DANGEROUS!
def check_permission(user, resource): try: return auth_service.check(user, resource) except Exception: return True # DANGEROUS!

SAFE - Fail-closed

SAFE - Fail-closed

def check_permission(user, resource): try: return auth_service.check(user, resource) except Exception as e: logger.error(f"Auth check failed: {e}") return False # Deny on error
undefined
def check_permission(user, resource): try: return auth_service.check(user, resource) except Exception as e: logger.error(f"Auth check failed: {e}") return False # Deny on error
undefined

Agentic AI Security (OWASP 2026)

Agentic AI安全(OWASP 2026版)

When building or reviewing AI agent systems, check for:
RiskDescriptionMitigation
ASI01: Goal HijackPrompt injection alters agent objectivesInput sanitization, goal boundaries, behavioral monitoring
ASI02: Tool MisuseTools used in unintended waysLeast privilege, fine-grained permissions, validate I/O
ASI03: Privilege AbuseCredential escalation across agentsShort-lived scoped tokens, identity verification
ASI04: Supply ChainCompromised plugins/MCP serversVerify signatures, sandbox, allowlist plugins
ASI05: Code ExecutionUnsafe code generation/executionSandbox execution, static analysis, human approval
ASI06: Memory PoisoningCorrupted RAG/context dataValidate stored content, segment by trust level
ASI07: Agent CommsSpoofing between agentsAuthenticate, encrypt, verify message integrity
ASI08: Cascading FailuresErrors propagate across systemsCircuit breakers, graceful degradation, isolation
ASI09: Trust ExploitationSocial engineering via AILabel AI content, user education, verification steps
ASI10: Rogue AgentsCompromised agents acting maliciouslyBehavior monitoring, kill switches, anomaly detection
构建或审查AI Agent系统时,需检查以下内容:
风险描述缓解措施
ASI01: 目标劫持Prompt注入篡改Agent目标输入清理、目标边界限制、行为监控
ASI02: 工具滥用工具被用于非预期场景最小权限原则、细粒度权限、校验输入输出
ASI03: 权限滥用Agent间凭证提升短生命周期范围令牌、身份验证
ASI04: 供应链风险受 compromise的插件/MCP服务器签名校验、沙箱环境、插件白名单
ASI05: 代码执行风险不安全的代码生成/执行沙箱执行、静态分析、人工审批
ASI06: 内存污染损坏的RAG/上下文数据校验存储内容、按信任级别分段
ASI07: Agent通信风险Agent间身份伪造身份验证、加密、消息完整性校验
ASI08: 级联故障错误在系统间传播熔断机制、优雅降级、隔离措施
ASI09: 信任利用通过AI实施社会工程AI内容标记、用户教育、验证步骤
ASI10: rogue Agent受 compromise的Agent执行恶意操作行为监控、终止开关、异常检测

Agent Security Checklist

Agent安全检查清单

  • All agent inputs sanitized and validated
  • Tools operate with minimum required permissions
  • Credentials are short-lived and scoped
  • Third-party plugins verified and sandboxed
  • Code execution happens in isolated environments
  • Agent communications authenticated and encrypted
  • Circuit breakers between agent components
  • Human approval for sensitive operations
  • Behavior monitoring for anomaly detection
  • Kill switch available for agent systems
  • 所有Agent输入均经过清理和校验
  • 工具以最小必要权限运行
  • 凭证为短生命周期且范围受限
  • 第三方插件经过验证并处于沙箱环境
  • 代码在隔离环境中执行
  • Agent通信经过身份验证和加密
  • Agent组件间配置熔断机制
  • 敏感操作需人工审批
  • 行为监控用于异常检测
  • Agent系统配备终止开关

ASVS 5.0 Key Requirements

ASVS 5.0核心要求

Level 1 (All Applications)

Level 1(所有应用)

  • Passwords minimum 12 characters
  • Check against breached password lists
  • Rate limiting on authentication
  • Session tokens 128+ bits entropy
  • HTTPS everywhere
  • 密码长度至少12位
  • 检查泄露密码库
  • 身份验证配置速率限制
  • 会话令牌熵值128位以上
  • 全站点使用HTTPS

Level 2 (Sensitive Data)

Level 2(敏感数据应用)

  • All L1 requirements plus:
  • MFA for sensitive operations
  • Cryptographic key management
  • Comprehensive security logging
  • Input validation on all parameters
  • 包含所有Level 1要求,额外要求:
  • 敏感操作需多因素认证(MFA)
  • 加密密钥管理
  • 全面安全日志
  • 所有参数均做输入校验

Level 3 (Critical Systems)

Level 3(关键系统)

  • All L1/L2 requirements plus:
  • Hardware security modules for keys
  • Threat modeling documentation
  • Advanced monitoring and alerting
  • Penetration testing validation
  • 包含所有Level 1/2要求,额外要求:
  • 密钥存储在硬件安全模块(HSM)
  • 威胁建模文档
  • 高级监控与告警
  • 渗透测试验证

Language-Specific Security Quirks

各语言特定安全注意事项

Important: The examples below are illustrative starting points, not exhaustive. When reviewing code, think like a senior security researcher: consider the language's memory model, type system, standard library pitfalls, ecosystem-specific attack vectors, and historical CVE patterns. Each language has deeper quirks beyond what's listed here.
Different languages have unique security pitfalls. Here are the top 20 languages with key security considerations. Go deeper for the specific language you're working in:

重要提示: 以下示例为说明性起点,并非详尽无遗。审查代码时,需以资深安全研究员的思维方式:考虑语言的内存模型、类型系统、标准库陷阱、生态系统特定攻击向量以及历史CVE模式。每种语言都有以下列出之外的更深层注意事项。
不同语言存在独特的安全陷阱。以下是20种主流语言的核心安全考量。针对你正在使用的语言深入研究:

JavaScript / TypeScript

JavaScript / TypeScript

Main Risks: Prototype pollution, XSS, eval injection
javascript
// UNSAFE: Prototype pollution
Object.assign(target, userInput)
// SAFE: Use null prototype or validate keys
Object.assign(Object.create(null), validated)

// UNSAFE: eval injection
eval(userCode)
// SAFE: Never use eval with user input
Watch for:
eval()
,
innerHTML
,
document.write()
, prototype chain manipulation,
__proto__

主要风险: 原型污染、XSS、eval注入
javascript
// UNSAFE: Prototype pollution
Object.assign(target, userInput)
// SAFE: Use null prototype or validate keys
Object.assign(Object.create(null), validated)

// UNSAFE: eval injection
eval(userCode)
// SAFE: Never use eval with user input
需关注:
eval()
innerHTML
document.write()
、原型链操作、
__proto__

Python

Python

Main Risks: Pickle deserialization, format string injection, shell injection
python
undefined
主要风险: Pickle反序列化、格式字符串注入、shell注入
python
undefined

UNSAFE: Pickle RCE

UNSAFE: Pickle RCE

pickle.loads(user_data)
pickle.loads(user_data)

SAFE: Use JSON or validate source

SAFE: Use JSON or validate source

json.loads(user_data)
json.loads(user_data)

UNSAFE: Format string injection

UNSAFE: Format string injection

query = "SELECT * FROM users WHERE name = '%s'" % user_input
query = "SELECT * FROM users WHERE name = '%s'" % user_input

SAFE: Parameterized

SAFE: Parameterized

cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
**Watch for:** `pickle`, `eval()`, `exec()`, `os.system()`, `subprocess` with `shell=True`

---
cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
**需关注:** `pickle`、`eval()`、`exec()`、`os.system()`、带`shell=True`的`subprocess`

---

Java

Java

Main Risks: Deserialization RCE, XXE, JNDI injection
java
// UNSAFE: Arbitrary deserialization
ObjectInputStream ois = new ObjectInputStream(userStream);
Object obj = ois.readObject();

// SAFE: Use allowlist or JSON
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, SafeClass.class);
Watch for:
ObjectInputStream
,
Runtime.exec()
, XML parsers without XXE protection, JNDI lookups

主要风险: 反序列化RCE、XXE、JNDI注入
java
// UNSAFE: Arbitrary deserialization
ObjectInputStream ois = new ObjectInputStream(userStream);
Object obj = ois.readObject();

// SAFE: Use allowlist or JSON
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, SafeClass.class);
需关注:
ObjectInputStream
Runtime.exec()
、未防护XXE的XML解析器、JNDI查找

C#

C#

Main Risks: Deserialization, SQL injection, path traversal
csharp
// UNSAFE: BinaryFormatter RCE
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(stream);

// SAFE: Use System.Text.Json
var obj = JsonSerializer.Deserialize<SafeType>(json);
Watch for:
BinaryFormatter
,
JavaScriptSerializer
,
TypeNameHandling.All
, raw SQL strings

主要风险: 反序列化、SQL注入、路径遍历
csharp
// UNSAFE: BinaryFormatter RCE
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(stream);

// SAFE: Use System.Text.Json
var obj = JsonSerializer.Deserialize<SafeType>(json);
需关注:
BinaryFormatter
JavaScriptSerializer
TypeNameHandling.All
、原生SQL字符串

PHP

PHP

Main Risks: Type juggling, file inclusion, object injection
php
// UNSAFE: Type juggling in auth
if ($password == $stored_hash) { ... }
// SAFE: Use strict comparison
if (hash_equals($stored_hash, $password)) { ... }

// UNSAFE: File inclusion
include($_GET['page'] . '.php');
// SAFE: Allowlist pages
$allowed = ['home', 'about']; include(in_array($page, $allowed) ? "$page.php" : 'home.php');
Watch for:
==
vs
===
,
include/require
,
unserialize()
,
preg_replace
with
/e
,
extract()

主要风险: 类型 juggling、文件包含、对象注入
php
// UNSAFE: Type juggling in auth
if ($password == $stored_hash) { ... }
// SAFE: Use strict comparison
if (hash_equals($stored_hash, $password)) { ... }

// UNSAFE: File inclusion
include($_GET['page'] . '.php');
// SAFE: Allowlist pages
$allowed = ['home', 'about']; include(in_array($page, $allowed) ? "$page.php" : 'home.php');
需关注:
==
vs
===
include/require
unserialize()
、带
/e
preg_replace
extract()

Go

Go

Main Risks: Race conditions, template injection, slice bounds
go
// UNSAFE: Race condition
go func() { counter++ }()
// SAFE: Use sync primitives
atomic.AddInt64(&counter, 1)

// UNSAFE: Template injection
template.HTML(userInput)
// SAFE: Let template escape
{{.UserInput}}
Watch for: Goroutine data races,
template.HTML()
,
unsafe
package, unchecked slice access

主要风险: 竞态条件、模板注入、切片越界
go
// UNSAFE: Race condition
go func() { counter++ }()
// SAFE: Use sync primitives
atomic.AddInt64(&counter, 1)

// UNSAFE: Template injection
template.HTML(userInput)
// SAFE: Let template escape
{{.UserInput}}
需关注: Goroutine数据竞争、
template.HTML()
unsafe
包、未校验的切片访问

Ruby

Ruby

Main Risks: Mass assignment, YAML deserialization, regex DoS
ruby
undefined
主要风险: 批量赋值、YAML反序列化、正则表达式DoS
ruby
undefined

UNSAFE: Mass assignment

UNSAFE: Mass assignment

User.new(params[:user])
User.new(params[:user])

SAFE: Strong parameters

SAFE: Strong parameters

User.new(params.require(:user).permit(:name, :email))
User.new(params.require(:user).permit(:name, :email))

UNSAFE: YAML RCE

UNSAFE: YAML RCE

YAML.load(user_input)
YAML.load(user_input)

SAFE: Use safe_load

SAFE: Use safe_load

YAML.safe_load(user_input)
**Watch for:** YAML.load, Marshal.load, eval, send with user input, .permit!

---
YAML.safe_load(user_input)
**需关注:** YAML.load、Marshal.load、eval、带用户输入的send、.permit!

---

Rust

Rust

Main Risks: Unsafe blocks, FFI boundary issues, integer overflow in release
rust
// CAUTION: Unsafe bypasses safety
unsafe { ptr::read(user_ptr) }

// CAUTION: Release integer overflow
let x: u8 = 255;
let y = x + 1; // Wraps to 0 in release!
// SAFE: Use checked arithmetic
let y = x.checked_add(1).unwrap_or(255);
Watch for:
unsafe
blocks, FFI calls, integer overflow in release builds,
.unwrap()
on untrusted input

主要风险: Unsafe块、FFI边界问题、发布版整数溢出
rust
// CAUTION: Unsafe bypasses safety
unsafe { ptr::read(user_ptr) }

// CAUTION: Release integer overflow
let x: u8 = 255;
let y = x + 1; // Wraps to 0 in release!
// SAFE: Use checked arithmetic
let y = x.checked_add(1).unwrap_or(255);
需关注:
unsafe
块、FFI调用、发布版整数溢出、不可信输入上的
.unwrap()

Swift

Swift

Main Risks: Force unwrapping crashes, Objective-C interop
swift
// UNSAFE: Force unwrap on untrusted data
let value = jsonDict["key"]!
// SAFE: Safe unwrapping
guard let value = jsonDict["key"] else { return }

// UNSAFE: Format string
String(format: userInput, args)
// SAFE: Don't use user input as format
Watch for: force unwrap (!), try!, ObjC bridging, NSSecureCoding misuse

主要风险: 强制解包崩溃、Objective-C互操作
swift
// UNSAFE: Force unwrap on untrusted data
let value = jsonDict["key"]!
// SAFE: Safe unwrapping
guard let value = jsonDict["key"] else { return }

// UNSAFE: Format string
String(format: userInput, args)
// SAFE: Don't use user input as format
需关注: 强制解包(!)、try!、ObjC桥接、NSSecureCoding误用

Kotlin

Kotlin

Main Risks: Null safety bypass, Java interop, serialization
kotlin
// UNSAFE: Platform type from Java
val len = javaString.length // NPE if null
// SAFE: Explicit null check
val len = javaString?.length ?: 0

// UNSAFE: Reflection
clazz.getDeclaredMethod(userInput)
// SAFE: Allowlist methods
Watch for: Java interop nulls (! operator), reflection, serialization, platform types

主要风险: 空安全绕过、Java互操作、序列化
kotlin
// UNSAFE: Platform type from Java
val len = javaString.length // NPE if null
// SAFE: Explicit null check
val len = javaString?.length ?: 0

// UNSAFE: Reflection
clazz.getDeclaredMethod(userInput)
// SAFE: Allowlist methods
需关注: Java互操作空值(!操作符)、反射、序列化、平台类型

C / C++

C / C++

Main Risks: Buffer overflow, use-after-free, format string
c
// UNSAFE: Buffer overflow
char buf[10]; strcpy(buf, userInput);
// SAFE: Bounds checking
strncpy(buf, userInput, sizeof(buf) - 1);

// UNSAFE: Format string
printf(userInput);
// SAFE: Always use format specifier
printf("%s", userInput);
Watch for:
strcpy
,
sprintf
,
gets
, pointer arithmetic, manual memory management, integer overflow

主要风险: 缓冲区溢出、悬垂引用、格式字符串
c
// UNSAFE: Buffer overflow
char buf[10]; strcpy(buf, userInput);
// SAFE: Bounds checking
strncpy(buf, userInput, sizeof(buf) - 1);

// UNSAFE: Format string
printf(userInput);
// SAFE: Always use format specifier
printf("%s", userInput);
需关注:
strcpy
sprintf
gets
、指针运算、手动内存管理、整数溢出

Scala

Scala

Main Risks: XML external entities, serialization, pattern matching exhaustiveness
scala
// UNSAFE: XXE
val xml = XML.loadString(userInput)
// SAFE: Disable external entities
val factory = SAXParserFactory.newInstance()
factory.setFeature("http://xml.org/sax/features/external-general-entities", false)
Watch for: Java interop issues, XML parsing,
Serializable
, exhaustive pattern matching

主要风险: XML外部实体、序列化、模式匹配完整性
scala
// UNSAFE: XXE
val xml = XML.loadString(userInput)
// SAFE: Disable external entities
val factory = SAXParserFactory.newInstance()
factory.setFeature("http://xml.org/sax/features/external-general-entities", false)
需关注: Java互操作问题、XML解析、
Serializable
、模式匹配完整性

R

R

Main Risks: Code injection, file path manipulation
r
undefined
主要风险: 代码注入、文件路径操纵
r
undefined

UNSAFE: eval injection

UNSAFE: eval injection

eval(parse(text = user_input))
eval(parse(text = user_input))

SAFE: Never parse user input as code

SAFE: Never parse user input as code

UNSAFE: Path traversal

UNSAFE: Path traversal

read.csv(paste0("data/", user_file))
read.csv(paste0("data/", user_file))

SAFE: Validate filename

SAFE: Validate filename

if (grepl("^[a-zA-Z0-9]+\.csv$", user_file)) read.csv(...)
**Watch for:** `eval()`, `parse()`, `source()`, `system()`, file path manipulation

---
if (grepl("^[a-zA-Z0-9]+\.csv$", user_file)) read.csv(...)
**需关注:** `eval()`、`parse()`、`source()`、`system()`、文件路径操纵

---

Perl

Perl

Main Risks: Regex injection, open() injection, taint mode bypass
perl
undefined
主要风险: 正则注入、open()注入、污染模式绕过
perl
undefined

UNSAFE: Regex DoS

UNSAFE: Regex DoS

$input =~ /$user_pattern/;
$input =~ /$user_pattern/;

SAFE: Use quotemeta

SAFE: Use quotemeta

$input =~ /\Q$user_pattern\E/;
$input =~ /\Q$user_pattern\E/;

UNSAFE: open() command injection

UNSAFE: open() command injection

open(FILE, $user_file);
open(FILE, $user_file);

SAFE: Three-argument open

SAFE: Three-argument open

open(my $fh, '<', $user_file);
**Watch for:** Two-arg `open()`, regex from user input, backticks, `eval`, disabled taint mode

---
open(my $fh, '<', $user_file);
**需关注:** 双参数`open()`、用户输入正则、反引号、`eval`、禁用污染模式

---

Shell (Bash)

Shell (Bash)

Main Risks: Command injection, word splitting, globbing
bash
undefined
主要风险: 命令注入、单词拆分、通配符
bash
undefined

UNSAFE: Unquoted variables

UNSAFE: Unquoted variables

rm $user_file
rm $user_file

SAFE: Always quote

SAFE: Always quote

rm "$user_file"
rm "$user_file"

UNSAFE: eval

UNSAFE: eval

eval "$user_command"
eval "$user_command"

SAFE: Never eval user input

SAFE: Never eval user input

**Watch for:** Unquoted variables, `eval`, backticks, `$(...)` with user input, missing `set -euo pipefail`

---
**需关注:** 未引号变量、`eval`、反引号、带用户输入的`$(...)`、缺失`set -euo pipefail`

---

Lua

Lua

Main Risks: Sandbox escape, loadstring injection
lua
-- UNSAFE: Code injection
loadstring(user_code)()
-- SAFE: Use sandboxed environment with restricted functions
Watch for:
loadstring
,
loadfile
,
dofile
,
os.execute
,
io
library, debug library

主要风险: 沙箱逃逸、loadstring注入
lua
-- UNSAFE: Code injection
loadstring(user_code)()
-- SAFE: Use sandboxed environment with restricted functions
需关注:
loadstring
loadfile
dofile
os.execute
io
库、debug库

Elixir

Elixir

Main Risks: Atom exhaustion, code injection, ETS access
elixir
undefined
主要风险: Atom耗尽、代码注入、ETS访问
elixir
undefined

UNSAFE: Atom exhaustion DoS

UNSAFE: Atom exhaustion DoS

String.to_atom(user_input)
String.to_atom(user_input)

SAFE: Use existing atoms only

SAFE: Use existing atoms only

String.to_existing_atom(user_input)
String.to_existing_atom(user_input)

UNSAFE: Code injection

UNSAFE: Code injection

Code.eval_string(user_input)
Code.eval_string(user_input)

SAFE: Never eval user input

SAFE: Never eval user input

**Watch for:** `String.to_atom`, `Code.eval_string`, `:erlang.binary_to_term`, ETS public tables

---
**需关注:** `String.to_atom`、`Code.eval_string`、`:erlang.binary_to_term`、ETS公共表

---

Dart / Flutter

Dart / Flutter

Main Risks: Platform channel injection, insecure storage
dart
// UNSAFE: Storing secrets in SharedPreferences
prefs.setString('auth_token', token);
// SAFE: Use flutter_secure_storage
secureStorage.write(key: 'auth_token', value: token);
Watch for: Platform channel data,
dart:mirrors
,
Function.apply
, insecure local storage

主要风险: 平台通道注入、不安全存储
dart
// UNSAFE: Storing secrets in SharedPreferences
prefs.setString('auth_token', token);
// SAFE: Use flutter_secure_storage
secureStorage.write(key: 'auth_token', value: token);
需关注: 平台通道数据、
dart:mirrors
Function.apply
、不安全本地存储

PowerShell

PowerShell

Main Risks: Command injection, execution policy bypass
powershell
undefined
主要风险: 命令注入、执行策略绕过
powershell
undefined

UNSAFE: Injection

UNSAFE: Injection

Invoke-Expression $userInput
Invoke-Expression $userInput

SAFE: Avoid Invoke-Expression with user data

SAFE: Avoid Invoke-Expression with user data

UNSAFE: Unvalidated path

UNSAFE: Unvalidated path

Get-Content $userPath
Get-Content $userPath

SAFE: Validate path is within allowed directory

SAFE: Validate path is within allowed directory

**Watch for:** `Invoke-Expression`, `& $userVar`, `Start-Process` with user args, `-ExecutionPolicy Bypass`

---
**需关注:** `Invoke-Expression`、`& $userVar`、带用户参数的`Start-Process`、`-ExecutionPolicy Bypass`

---

SQL (All Dialects)

SQL(所有方言)

Main Risks: Injection, privilege escalation, data exfiltration
sql
-- UNSAFE: String concatenation
"SELECT * FROM users WHERE id = " + userId

-- SAFE: Parameterized query (language-specific)
-- Use prepared statements in ALL cases
Watch for: Dynamic SQL,
EXECUTE IMMEDIATE
, stored procedures with dynamic queries, privilege grants

主要风险: 注入、权限提升、数据泄露
sql
-- UNSAFE: String concatenation
"SELECT * FROM users WHERE id = " + userId

-- SAFE: Parameterized query (language-specific)
-- Use prepared statements in ALL cases
需关注: 动态SQL、
EXECUTE IMMEDIATE
、含动态查询的存储过程、权限授予

Deep Security Analysis Mindset

深度安全分析思维

When reviewing any language, think like a senior security researcher:
  1. Memory Model: How does the language handle memory? Managed vs manual? GC pauses exploitable?
  2. Type System: Weak typing = type confusion attacks. Look for coercion exploits.
  3. Serialization: Every language has its pickle/Marshal equivalent. All are dangerous.
  4. Concurrency: Race conditions, TOCTOU, atomicity failures specific to the threading model.
  5. FFI Boundaries: Native interop is where type safety breaks down.
  6. Standard Library: Historic CVEs in std libs (Python urllib, Java XML, Ruby OpenSSL).
  7. Package Ecosystem: Typosquatting, dependency confusion, malicious packages.
  8. Build System: Makefile/gradle/npm script injection during builds.
  9. Runtime Behavior: Debug vs release differences (Rust overflow, C++ assertions).
  10. Error Handling: How does the language fail? Silently? With stack traces? Fail-open?
For any language not listed: Research its specific CWE patterns, CVE history, and known footguns. The examples above are entry points, not complete coverage.
审查任何语言时,需以资深安全研究员的思维方式思考:
  1. 内存模型: 该语言如何管理内存?托管式还是手动式?垃圾回收停顿是否可被利用?
  2. 类型系统: 弱类型是否导致类型混淆攻击?寻找强制转换漏洞。
  3. 序列化: 每种语言都有类似pickle/Marshal的机制,均存在风险。
  4. 并发: 竞态条件、TOCTOU、特定线程模型下的原子性故障。
  5. FFI边界: 原生互操作是类型安全的薄弱点。
  6. 标准库: 标准库中的历史CVE(Python urllib、Java XML、Ruby OpenSSL)。
  7. 包生态: 打字错误包、依赖混淆、恶意包。 8.构建系统: 构建过程中的Makefile/gradle/npm脚本注入。
  8. 运行时行为: Debug与Release版本差异(Rust溢出、C++断言)。
  9. 错误处理: 语言如何处理错误?静默失败?暴露堆栈跟踪?故障开放?
对于未列出的语言: 研究其特定CWE模式、CVE历史和已知陷阱。以上示例为入门点,并非完整覆盖。

When to Apply This Skill

何时使用本技能

Use this skill when:
  • Writing authentication or authorization code
  • Handling user input or external data
  • Implementing cryptography or password storage
  • Reviewing code for security vulnerabilities
  • Designing API endpoints
  • Building AI agent systems
  • Configuring application security settings
  • Handling errors and exceptions
  • Working with third-party dependencies
  • Working in any language - apply the deep analysis mindset above
在以下场景使用本技能:
  • 编写身份验证或授权代码
  • 处理用户输入或外部数据
  • 实现加密或密码存储功能
  • 审查代码中的安全漏洞
  • 设计API端点
  • 构建AI Agent系统
  • 配置应用安全设置
  • 处理错误和异常
  • 处理第三方依赖
  • 使用任何语言 - 应用上述深度分析思维