owasp

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OWASP Security - Quick Reference

OWASP安全 - 快速参考

When to Use This Skill

适用场景

  • Identify common vulnerabilities
  • Implement security controls
  • Code review for security issues
  • 识别常见漏洞
  • 实施安全控制措施
  • 针对安全问题进行代码评审

When NOT to Use This Skill

不适用场景

  • OWASP Top 10:2025 - Use
    owasp-top-10
    skill for latest 2025 standards
  • Secrets management - Use
    secrets-management
    skill for credentials handling
  • Supply chain security - Use
    supply-chain
    skill for dependency issues
  • JWT/OAuth security - Use authentication skills for protocol-specific issues
Deep Knowledge: Use
mcp__documentation__fetch_docs
with technology:
owasp
for comprehensive documentation.
  • OWASP Top 10:2025 - 针对2025年最新标准,请使用
    owasp-top-10
    技能
  • 密钥管理 - 处理凭证相关问题,请使用
    secrets-management
    技能
  • 供应链安全 - 依赖项相关问题,请使用
    supply-chain
    技能
  • JWT/OAuth安全 - 协议相关问题,请使用身份验证类技能
深度知识获取:使用
mcp__documentation__fetch_docs
工具并指定technology为
owasp
,可获取完整文档。

OWASP Top 10 (2021)

OWASP Top 10 (2021)

A01: Broken Access Control

A01: 访问控制失效

java
// BAD - Direct object reference
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
    return userRepository.findById(id);
}

// GOOD - Check authorization
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id, Authentication auth) {
    User user = userRepository.findById(id);
    if (!user.getId().equals(auth.getPrincipal().getId())) {
        throw new AccessDeniedException("Not authorized");
    }
    return user;
}
java
// 不良示例 - 直接对象引用
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
    return userRepository.findById(id);
}

// 良好示例 - 检查授权
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id, Authentication auth) {
    User user = userRepository.findById(id);
    if (!user.getId().equals(auth.getPrincipal().getId())) {
        throw new AccessDeniedException("Not authorized");
    }
    return user;
}

A02: Cryptographic Failures

A02: 加密机制失效

java
// BAD - Weak hashing
String hash = DigestUtils.md5Hex(password);

// GOOD - Strong hashing with salt
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String hash = encoder.encode(password);
java
// 不良示例 - 弱哈希算法
String hash = DigestUtils.md5Hex(password);

// 良好示例 - 带盐的强哈希算法
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String hash = encoder.encode(password);

A03: Injection

A03: 注入攻击

java
// BAD - SQL Injection
String query = "SELECT * FROM users WHERE name = '" + name + "'";

// GOOD - Parameterized query
@Query("SELECT u FROM User u WHERE u.name = :name")
User findByName(@Param("name") String name);
java
// 不良示例 - SQL注入
String query = "SELECT * FROM users WHERE name = '" + name + "'";

// 良好示例 - 参数化查询
@Query("SELECT u FROM User u WHERE u.name = :name")
User findByName(@Param("name") String name);

A04: Insecure Design

A04: 不安全设计

  • Threat modeling during design phase
  • Security requirements in user stories
  • Defense in depth architecture
  • 设计阶段开展威胁建模
  • 用户故事中明确安全需求
  • 采用纵深防御架构

A05: Security Misconfiguration

A05: 安全配置错误

yaml
undefined
yaml
undefined

Spring Security - disable defaults carefully

Spring Security - 谨慎禁用默认配置

spring: security: headers: content-security-policy: "default-src 'self'" x-frame-options: DENY x-content-type-options: nosniff
undefined
spring: security: headers: content-security-policy: "default-src 'self'" x-frame-options: DENY x-content-type-options: nosniff
undefined

A06: Vulnerable Components

A06: 易受攻击的组件

bash
undefined
bash
undefined

Check for vulnerabilities

检查漏洞

npm audit mvn dependency-check:check pip-audit
undefined
npm audit mvn dependency-check:check pip-audit
undefined

A07: Auth Failures

A07: 身份验证失效

java
// Implement rate limiting
@RateLimiter(name = "login", fallbackMethod = "loginFallback")
public AuthResponse login(LoginRequest request) {
    // ...
}

// Account lockout
if (failedAttempts >= 5) {
    lockAccount(user);
}
java
undefined

A08: Software Integrity

实现速率限制

  • Verify signatures of dependencies
  • Use lock files (package-lock.json, pom.xml)
  • CI/CD pipeline security
@RateLimiter(name = "login", fallbackMethod = "loginFallback") public AuthResponse login(LoginRequest request) { // ... }

A09: Logging Failures

账户锁定

java
// Log security events
log.info("Login attempt", Map.of(
    "user", username,
    "ip", request.getRemoteAddr(),
    "success", authenticated
));

// DON'T log sensitive data
log.info("Password: {}", password);  // NEVER!
if (failedAttempts >= 5) { lockAccount(user); }
undefined

A10: SSRF

A08: 软件完整性问题

java
// Validate URLs
private boolean isAllowedUrl(String url) {
    URL parsed = new URL(url);
    return allowedHosts.contains(parsed.getHost());
}
  • 验证依赖项签名
  • 使用锁定文件(package-lock.json、pom.xml)
  • CI/CD流水线安全

Security Headers

A09: 日志记录失效

java
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) {
        return http
            .headers(headers -> headers
                .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))
                .frameOptions(frame -> frame.deny())
                .xssProtection(xss -> xss.disable())
            )
            .build();
    }
}
java
undefined

Anti-Patterns

记录安全事件

Anti-PatternWhy It's BadCorrect Approach
Direct object references without authIDOR vulnerability (A01)Always verify ownership before access
Using MD5/SHA1 for passwordsEasily crackedUse bcrypt/argon2 with salt
String concatenation in SQLSQL injectionUse parameterized queries/ORMs
Exposing stack traces in prodInformation disclosureGeneric error messages only
No rate limiting on loginBrute force attacksImplement rate limiting + account lockout
Storing secrets in codeCredential exposureUse environment variables/vaults
log.info("Login attempt", Map.of( "user", username, "ip", request.getRemoteAddr(), "success", authenticated ));

Quick Troubleshooting

禁止记录敏感数据

IssueLikely CauseSolution
403 Forbidden on valid requestCORS misconfigurationCheck allowed origins in CORS config
Session not persistingSameSite cookie issueSet
SameSite=Lax
or
None
with HTTPS
JWT token rejectedClock skew or expiredAdd clock skew tolerance (5min)
File upload failsCSP blockingAdd upload domain to CSP directives
API returns 401 unexpectedlyMissing/invalid Authorization headerCheck Bearer token format
log.info("Password: {}", password); // 绝对禁止!
undefined

A10: SSRF(服务器端请求伪造)

java
undefined

验证URL合法性

private boolean isAllowedUrl(String url) { URL parsed = new URL(url); return allowedHosts.contains(parsed.getHost()); }
undefined

安全头配置

java
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) {
        return http
            .headers(headers -> headers
                .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))
                .frameOptions(frame -> frame.deny())
                .xssProtection(xss -> xss.disable())
            )
            .build();
    }
}

反模式

反模式危害正确做法
无授权的直接对象引用存在IDOR漏洞(属于A01)访问前始终验证所有权
用MD5/SHA1存储密码易被破解使用bcrypt/argon2带盐哈希
SQL语句字符串拼接存在SQL注入风险使用参数化查询/ORM框架
生产环境暴露堆栈跟踪信息泄露仅返回通用错误信息
登录无速率限制暴力破解攻击实现速率限制+账户锁定
代码中存储密钥凭证泄露使用环境变量/密钥管理服务

快速故障排查

问题可能原因解决方案
合法请求返回403 ForbiddenCORS配置错误检查CORS配置中的允许源
会话无法持久化SameSite Cookie问题设置
SameSite=Lax
None
(需配合HTTPS)
JWT令牌被拒绝时钟偏差或令牌过期添加时钟偏差容忍(如5分钟)
文件上传失败CSP阻止将上传域名添加到CSP指令
API意外返回401Authorization头缺失/无效检查Bearer令牌格式