AgentSkillsCN

OWASP Top 10

深入理解并有效应对OWASP所界定的十大Web应用安全风险,包括访问控制失效、加密机制缺陷、注入攻击以及不安全的设计等高危隐患。

SKILL.md
--- frontmatter
name: OWASP Top 10
description: Understanding and mitigating the top 10 most critical security risks to web applications as defined by OWASP, including broken access control, cryptographic failures, injection, and insecure design.

OWASP Top 10

Current Level: Intermediate
Domain: Security / Application Security


Overview

The OWASP (Open Web Application Security Project) Top 10 is a standard awareness document representing a broad consensus about the most critical security risks to web applications. Updated every 3-4 years (2021 is the latest version), it provides a prioritized list of security risks and mitigation strategies.

What is OWASP Top 10

Why OWASP Top 10 Matters

BenefitImpact
Industry StandardWidely recognized security framework
PrioritizationFocus on most critical risks
ComplianceRequired by many security standards
EducationLearn common vulnerabilities
TestingGuide for security testing

A01: Broken Access Control

Description

Users can access resources or perform actions they shouldn't be able to, due to missing or ineffective access controls.

Examples

ScenarioDescription
View other users' dataAccess /user/123 when logged in as user 456
Access admin functionsAccess /admin without admin role
Modify others' dataUpdate /user/123/profile as user 456
Bypass authorizationAccess API endpoints without proper auth

Prevention

javascript
// Bad: No authorization check
app.get('/user/:id', (req, res) => {
    const user = getUser(req.params.id);
    res.json(user); // Anyone can view any user!
});

// Good: Check authorization
app.get('/user/:id', (req, res) => {
    if (req.params.id !== req.user.id && !req.user.isAdmin) {
        return res.status(403).json({ error: 'Forbidden' });
    }
    const user = getUser(req.params.id);
    res.json(user);
});

Best Practices

PracticeDescription
Deny by defaultExplicitly allow, deny everything else
Check server-sideNever trust client-side checks
Principle of least privilegeGrant minimum necessary access
Log accessTrack who accesses what
Regular auditReview access controls regularly

A02: Cryptographic Failures

Description

Sensitive data is exposed due to weak or missing encryption, or improper cryptographic practices.

Examples

ScenarioDescription
Passwords in plaintextStored without hashing
Weak hashingUsing MD5, SHA1 for passwords
Unencrypted transmissionHTTP instead of HTTPS
Hardcoded keysEncryption keys in source code
Weak algorithmsUsing DES, RC4

Prevention

javascript
// Bad: Weak password hashing
const hash = md5(password); // MD5 is broken

// Good: Strong password hashing
const hash = await bcrypt.hash(password, 10);

// Bad: Hardcoded key
const apiKey = 'sk_live_1234567890';

// Good: Environment variable
const apiKey = process.env.API_KEY;

// Bad: No encryption in transit
http.createServer((req, res) => { ... }); // HTTP

// Good: Use HTTPS
https.createServer(options, (req, res) => { ... });

Best Practices

PracticeDescription
Encrypt at restUse AES-256 for sensitive data
Encrypt in transitUse TLS (HTTPS)
Strong password hashingUse bcrypt, Argon2, scrypt
Never store plaintext passwordsAlways hash passwords
Key managementUse secure key management service
Update algorithmsUse current, strong algorithms

A03: Injection

Description

Malicious data is sent to an interpreter as part of a command or query, allowing attackers to execute unintended commands.

SQL Injection

Example Attack:

sql
-- Vulnerable query
SELECT * FROM users WHERE username = '$username' AND password = '$password';

-- Attack payload
username: ' OR '1'='1
password: anything

-- Resulting query (always true)
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = 'anything'

Prevention

javascript
// Bad: String concatenation
const query = `SELECT * FROM users WHERE username = '${username}'`;

// Good: Parameterized query
const query = 'SELECT * FROM users WHERE username = $1';
await db.query(query, [username]);

// Good: Using ORM
const user = await User.findOne({ where: { username } });

Other Injection Types

TypeExamplePrevention
NoSQL InjectionMongoDB query injectionUse parameterized queries
OS Command Injection; rm -rf /Use parameterized APIs
LDAP Injection*)(&Use parameterized queries
XPath Injection1' or '1'='1Use parameterized queries

Best Practices

PracticeDescription
Parameterized queriesNever concatenate user input
Use ORMLet ORM handle escaping
Input validationValidate and sanitize input
Least privilegeUse least-privileged DB user
Stored proceduresUse when appropriate

A04: Insecure Design

Description

Missing or ineffective security controls by design, not implementation.

Examples

ScenarioDescription
No rate limitingBrute force attacks possible
Weak password policyUsers can set weak passwords
No MFASingle-factor authentication
Insecure defaultsDefault admin/admin passwords
No security headersMissing CSP, HSTS

Prevention

javascript
// Bad: No rate limiting
app.post('/login', (req, res) => {
    // No rate limit, brute force possible
});

// Good: Rate limiting
const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 5 // limit each IP to 5 requests per windowMs
});

app.post('/login', limiter, (req, res) => {
    // Rate limited
});

// Good: Security headers
app.use(helmet());

Best Practices

PracticeDescription
Threat modelingIdentify threats during design
Secure design patternsUse proven patterns
Defense in depthMultiple security layers
Security by designBuild security from start
Regular reviewsReview design for security issues

A05: Security Misconfiguration

Description

Insecure default configurations, incomplete setups, open cloud storage, verbose error messages, etc.

Examples

ScenarioDescription
Default credentialsadmin/admin, root/password
Directory listingFiles visible at /files/
Verbose errorsStack traces exposed to users
Unnecessary servicesDebug mode enabled in production
Open cloud storageS3 bucket publicly accessible

Prevention

javascript
// Bad: Verbose error messages
app.use((err, req, res, next) => {
    res.status(500).json({
        error: err.message,
        stack: err.stack // Exposes internal details
    });
});

// Good: Generic error messages
app.use((err, req, res, next) => {
    console.error(err); // Log full error
    res.status(500).json({
        error: 'Internal server error'
    });
});

// Good: Disable directory listing
app.use(express.static('public', {
    index: false,
    showDir: false
}));

Best Practices

PracticeDescription
Hardening guidesFollow vendor hardening guides
Remove defaultsChange default credentials
Minimal installInstall only what's needed
Disable debugNever run debug in production
Automated scanningUse config scanning tools
Cloud securityReview cloud configurations

A06: Vulnerable and Outdated Components

Description

Using libraries, frameworks, or other software modules with known vulnerabilities.

Examples

ScenarioDescription
Old React versionKnown XSS vulnerability
Outdated OpenSSLHeartbleed vulnerability
Vulnerable npm packageMalicious code in dependency
Unpatched serverKnown exploit available

Prevention

bash
# Check for vulnerabilities
npm audit

# Update dependencies
npm update

# Use Snyk
snyk test

# Use Dependabot (GitHub)
# Automatically creates PRs for vulnerable dependencies

Best Practices

PracticeDescription
Dependency scanningRegularly scan for vulnerabilities
Keep updatedUpdate dependencies regularly
Remove unusedDelete unused dependencies
Use lockfilesPin dependency versions
Monitor CVEsWatch for new vulnerabilities
Automated updatesUse Dependabot, Renovate

A07: Identification and Authentication Failures

Description

Broken authentication mechanisms allowing attackers to compromise user identities.

Examples

ScenarioDescription
Weak passwords allowedNo password complexity requirements
No MFAOnly password required
Session fixationAttacker sets session ID
Credential stuffingReuse of compromised credentials
Password reset flawsWeak reset tokens

Prevention

javascript
// Bad: Weak password validation
if (password.length < 6) {
    return 'Password too short';
}

// Good: Strong password validation
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
if (!passwordRegex.test(password)) {
    return 'Password must be 8+ chars with uppercase, lowercase, and number';
}

// Good: MFA
app.post('/login', async (req, res) => {
    const { username, password, totpCode } = req.body;

    // Verify password
    const user = await verifyPassword(username, password);
    if (!user) return res.status(401).json({ error: 'Invalid credentials' });

    // Verify MFA
    if (!verifyTOTP(user.totpSecret, totpCode)) {
        return res.status(401).json({ error: 'Invalid MFA code' });
    }

    // Create session
    req.session.userId = user.id;
    res.json({ success: true });
});

Best Practices

PracticeDescription
Strong password policyEnforce complexity
MFA requiredRequire 2FA for sensitive actions
Secure session managementUse secure session tokens
Rate limitingLimit login attempts
Secure password resetUse time-limited, single-use tokens
Credential stuffing protectionDetect and block reused credentials

A08: Software and Data Integrity Failures

Description

Code or infrastructure without integrity verification, allowing supply chain attacks or unauthorized modifications.

Examples

ScenarioDescription
Supply chain attackMalicious npm package
Unsigned updatesNo verification of updates
Insecure CI/CDUnauthorized code changes
Missing code signingExecutables not signed
Subresource integrityCDN resources not verified

Prevention

bash
# Verify package integrity
npm install --package-lock-only

# Use npm audit
npm audit

# Use SRI (Subresource Integrity)
<script src="https://cdn.example.com/script.js"
        integrity="sha384-abc123..."
        crossorigin="anonymous"></script>

Best Practices

PracticeDescription
Code signingSign executables and packages
Verify dependenciesCheck lockfiles
Secure CI/CDRequire approvals, sign artifacts
Supply chain securityVet dependencies
SRIUse subresource integrity for CDN resources
Immutable infrastructureDon't modify running systems

A09: Security Logging and Monitoring Failures

Description

Insufficient logging, lack of alerting on suspicious activity, or missing audit trails.

Examples

ScenarioDescription
No login loggingCan't detect unauthorized access
No error loggingCan't diagnose issues
No alertingAttacks go unnoticed
Insufficient logsMissing critical events
Logs not reviewedAttacks detected but ignored

Prevention

javascript
// Good: Comprehensive logging
const winston = require('winston');

const logger = winston.createLogger({
    level: 'info',
    format: winston.format.json(),
    transports: [
        new winston.transports.File({ filename: 'error.log', level: 'error' }),
        new winston.transports.File({ filename: 'combined.log' })
    ]
});

// Log security events
app.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const ip = req.ip;

    try {
        const user = await verifyPassword(username, password);
        if (user) {
            logger.info('Login successful', { username, ip, userId: user.id });
            req.session.userId = user.id;
            res.json({ success: true });
        } else {
            logger.warn('Login failed', { username, ip });
            res.status(401).json({ error: 'Invalid credentials' });
        }
    } catch (error) {
        logger.error('Login error', { username, ip, error: error.message });
        res.status(500).json({ error: 'Internal error' });
    }
});

Best Practices

PracticeDescription
Log security eventsLogins, failures, privilege changes
SIEM integrationCentralize logs
Real-time alertingAlert on suspicious activity
Log retentionKeep logs for investigation
Log reviewRegularly review logs
Audit trailsTrack who did what

A10: Server-Side Request Forgery (SSRF)

Description

Application fetches remote resource without validating user-supplied URL, allowing attackers to access internal resources.

Examples

ScenarioDescription
Internal network accessAccess internal APIs
Cloud metadataRead cloud instance metadata
Port scanningScan internal network
File accessAccess internal files

Prevention

javascript
// Bad: No URL validation
app.get('/fetch', async (req, res) => {
    const url = req.query.url;
    const response = await axios.get(url); // Fetches any URL!
    res.json(response.data);
});

// Good: URL whitelist
const ALLOWED_HOSTS = ['api.example.com', 'cdn.example.com'];

app.get('/fetch', async (req, res) => {
    const url = req.query.url;
    const parsed = new URL(url);

    if (!ALLOWED_HOSTS.includes(parsed.hostname)) {
        return res.status(400).json({ error: 'Invalid URL' });
    }

    const response = await axios.get(url);
    res.json(response.data);
});

// Good: Use URL library for validation
const { URL } = require('url');

app.get('/fetch', async (req, res) => {
    const url = req.query.url;
    const parsed = new URL(url);

    // Block private IPs
    if (parsed.hostname.startsWith('192.168.') ||
        parsed.hostname.startsWith('10.') ||
        parsed.hostname.startsWith('127.')) {
        return res.status(400).json({ error: 'Invalid URL' });
    }

    const response = await axios.get(url);
    res.json(response.data);
});

Best Practices

PracticeDescription
URL whitelistOnly allow specific hosts
Validate URLsParse and validate URLs
Network segmentationRestrict outbound access
Disable unnecessary protocolsBlock file://, ftp://
Use allowlistAllow only what's needed
Cloud metadata protectionBlock metadata endpoints

Testing for OWASP Top 10

Manual Testing

Test TypeWhat to Check
Access controlTry accessing others' data
InjectionTry SQL injection payloads
AuthenticationTest weak passwords, no MFA
SSRFTry internal URLs
MisconfigurationCheck for default credentials

Automated Scanning

ToolTypeWhat It Finds
OWASP ZAPDASTWeb vulnerabilities
Burp SuiteDASTWeb vulnerabilities
NessusVulnerability scannerKnown vulnerabilities
SonarQubeSASTCode vulnerabilities
SnykDependency scannerVulnerable dependencies

Code Review

What to Look For:

  • User input handling
  • Authentication/authorization checks
  • Cryptographic usage
  • Error handling
  • Logging

Prevention Checklist

Input Validation

PracticeStatus
[ ] Validate all user input
[ ] Use allowlists (not blocklists)
[ ] Sanitize input for context
[ ] Validate data types
[ ] Check input length

Output Encoding

PracticeStatus
[ ] Encode HTML output (prevent XSS)
[ ] Encode URL parameters
[ ] Encode JSON output
[ ] Use template engines with auto-escaping

Parameterized Queries

PracticeStatus
[ ] Never concatenate SQL
[ ] Use parameterized queries
[ ] Use ORM when possible
[ ] Use least-privileged DB user

Authentication and Authorization

PracticeStatus
[ ] Check auth on every request
[ ] Implement authorization checks
[ ] Use strong password hashing
[ ] Require MFA for sensitive actions
[ ] Implement rate limiting

HTTPS Everywhere

PracticeStatus
[ ] Use HTTPS everywhere
[ ] Redirect HTTP to HTTPS
[ ] Use HSTS
[ ] Use strong TLS configuration

Security Headers

HeaderPurpose
Content-Security-PolicyPrevent XSS
Strict-Transport-SecurityForce HTTPS
X-Content-Type-OptionsPrevent MIME sniffing
X-Frame-OptionsPrevent clickjacking
X-XSS-ProtectionXSS protection
javascript
// Using Helmet.js
const helmet = require('helmet');

app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            defaultSrc: ["'self'"],
            scriptSrc: ["'self'", "'unsafe-inline'"],
            styleSrc: ["'self'", "'unsafe-inline'"],
            imgSrc: ["'self'", "data:", "https:"],
        },
    },
    hsts: {
        maxAge: 31536000,
        includeSubDomains: true,
        preload: true
    }
}));

Secure Coding Practices

Principles

PrincipleDescription
Principle of least privilegeGrant minimum necessary access
Defense in depthMultiple security layers
Fail securelyErrors don't expose info
Keep it simpleComplexity = bugs
Don't trust inputValidate and sanitize

Secure Coding Examples

javascript
// Bad: Trust user input
const filename = req.params.filename;
fs.readFile(`/uploads/${filename}`, (err, data) => {
    // Path traversal vulnerability!
});

// Good: Validate and sanitize
const filename = req.params.filename;
const safeFilename = path.basename(filename); // Remove path traversal
const safePath = path.join('/uploads', safeFilename);
fs.readFile(safePath, (err, data) => {
    // Safe!
});

Developer Security Training

Training Topics

TopicDescription
OWASP Top 10Understand common vulnerabilities
Secure codingLearn secure coding practices
Common patternsRecognize vulnerability patterns
ToolsLearn to use security tools
UpdatesStay current on threats

Training Methods

MethodFrequency
WorkshopsQuarterly
Online coursesOngoing
Code reviewsContinuous
Security newslettersWeekly
ConferencesAnnually

Tools for OWASP Top 10

SAST (Static Application Security Testing)

ToolDescriptionPricing
SonarQubeCode quality + securityFree/$
CheckmarxEnterprise SAST$$$
FortifyEnterprise SAST$$$
SemgrepOpen-source SASTFree

DAST (Dynamic Application Security Testing)

ToolDescriptionPricing
OWASP ZAPFree DAST toolFree
Burp SuiteProfessional DAST$$$
AcunetixWeb vulnerability scanner$$$
NetsparkerWeb vulnerability scanner$$$

Dependency Scanning

ToolDescriptionPricing
SnykDependency vulnerability scannerFree/$
DependabotGitHub dependency scanningFree
WhiteSourceDependency scanning$$
npm auditNode.js dependency scanningFree

Real Vulnerability Examples

Example 1: SQL Injection in Login Form

Vulnerable Code:

javascript
app.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const query = `SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`;
    const user = await db.query(query);
    // SQL injection possible!
});

Attack:

code
username: ' OR '1'='1
password: anything

Fix:

javascript
app.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const query = 'SELECT * FROM users WHERE username = $1 AND password = $2';
    const user = await db.query(query, [username, password]);
    // Safe!
});

Example 2: XSS in Comment Section

Vulnerable Code:

javascript
app.get('/comments', async (req, res) => {
    const comments = await db.query('SELECT * FROM comments');
    res.render('comments', { comments }); // No escaping!
});

Attack:

code
<script>alert('XSS')</script>

Fix:

javascript
app.get('/comments', async (req, res) => {
    const comments = await db.query('SELECT * FROM comments');
    res.render('comments', { comments }); // Template engine auto-escapes
});

Example 3: Broken Access Control in API

Vulnerable Code:

javascript
app.get('/api/user/:id', async (req, res) => {
    const user = await db.query(`SELECT * FROM users WHERE id = ${req.params.id}`);
    res.json(user); // No authorization check!
});

Attack:

code
GET /api/user/123  // Access user 123's data as user 456

Fix:

javascript
app.get('/api/user/:id', async (req, res) => {
    if (req.params.id !== req.user.id && !req.user.isAdmin) {
        return res.status(403).json({ error: 'Forbidden' });
    }
    const user = await db.query(`SELECT * FROM users WHERE id = ${req.params.id}`);
    res.json(user);
});

Summary Checklist

Before Development

  • Understand OWASP Top 10
  • Learn secure coding practices
  • Set up security tools
  • Review threat model

During Development

  • Validate all input
  • Use parameterized queries
  • Implement auth/authz
  • Add logging
  • Use security headers

Before Deployment

  • Run SAST scan
  • Run DAST scan
  • Check dependencies
  • Review configuration
  • Test security
code

---

## Quick Start

### OWASP Top 10 (2021) Overview

1. **A01: Broken Access Control** - Validate authorization
2. **A02: Cryptographic Failures** - Use strong encryption
3. **A03: Injection** - Use parameterized queries
4. **A04: Insecure Design** - Security by design
5. **A05: Security Misconfiguration** - Secure defaults
6. **A06: Vulnerable Components** - Update dependencies
7. **A07: Authentication Failures** - Strong authentication
8. **A08: Software and Data Integrity** - Verify integrity
9. **A09: Security Logging Failures** - Comprehensive logging
10. **A10: SSRF** - Validate server requests

### Prevent Injection

```javascript
// ❌ Bad - SQL injection
const query = `SELECT * FROM users WHERE id = ${userId}`

// ✅ Good - Parameterized query
const query = 'SELECT * FROM users WHERE id = ?'
db.query(query, [userId])

Production Checklist

  • Access Control: Validate all authorization checks
  • Encryption: Use strong encryption for sensitive data
  • Parameterized Queries: Prevent injection attacks
  • Security Design: Security by design principles
  • Configuration: Secure default configurations
  • Dependencies: Keep dependencies updated
  • Authentication: Strong authentication mechanisms
  • Integrity: Verify software and data integrity
  • Logging: Comprehensive security logging
  • SSRF Protection: Validate server-side requests
  • Security Testing: Regular security scans
  • Training: Team security training

Anti-patterns

❌ Don't: Broken Access Control

javascript
// ❌ Bad - No authorization check
app.get('/api/users/:id', (req, res) => {
  const user = db.getUser(req.params.id)  // Anyone can access!
  res.json(user)
})
javascript
// ✅ Good - Authorization check
app.get('/api/users/:id', authenticate, (req, res) => {
  if (req.user.id !== req.params.id && !req.user.isAdmin) {
    return res.status(403).json({ error: 'Forbidden' })
  }
  const user = db.getUser(req.params.id)
  res.json(user)
})

❌ Don't: SQL Injection

javascript
// ❌ Bad - String concatenation
const query = `SELECT * FROM users WHERE email = '${email}'`
javascript
// ✅ Good - Parameterized query
const query = 'SELECT * FROM users WHERE email = ?'
db.query(query, [email])

Integration Points

  • Secure Coding (24-security-practices/secure-coding/) - Secure coding practices
  • Security Audit (24-security-practices/security-audit/) - Security reviews
  • Vulnerability Management (24-security-practices/vulnerability-management/) - Vulnerability handling

Further Reading

After Deployment

  • Monitor logs
  • Set up alerts
  • Regular security scans
  • Stay updated on vulnerabilities
  • Incident response plan ready