Trung cấpHướng dẫnClaude ChatNguồn: Anthropic

API Security — Claude review code theo OWASP Top 10

Nghe bài viết
00:00

Điểm nổi bật

Nhấn để đến mục tương ứng

  1. 1 Theo báo cáo của Gartner, đến 2025 hơn 50% các vụ đánh cắp dữ liệu xảy ra qua API không được bảo vệ đúng cách.
  2. 2 Review theo từng OWASP category một — thay vì hỏi "check all", tập trung từng category sẽ cho kết quả sâu hơn.
  3. 3 Claude có thể review code API của bạn theo từng tiêu chí OWASP, phát hiện lỗ hổng và đề xuất cách khắc phục cụ thể.
  4. 4 Phiên bản mới nhất (2023) bao gồm: API1 — Broken Object Level Authorization (BOLA): Người dùng truy cập được dữ liệu của người khác bằng cách thay đổi ID trong request.
  5. 5 API3 — Broken Object Property Level Authorization: API trả về quá nhiều dữ liệu hoặc cho phép sửa fields không nên sửa.
Man gives robot bottles on a tray

API là mục tiêu tấn công số 1 trong ứng dụng web hiện đại. Theo báo cáo của Gartner, đến 2025 hơn 50% các vụ đánh cắp dữ liệu xảy ra qua API không được bảo vệ đúng cách. OWASP (Open Web Application Security Project) đã công bố danh sách Top 10 API Security Risks giúp developers nhận diện và phòng tránh các lỗ hổng phổ biến nhất. Claude có thể review code API của bạn theo từng tiêu chí OWASP, phát hiện lỗ hổng và đề xuất cách khắc phục cụ thể.

OWASP API Security Top 10 là gì?

OWASP API Security Top 10 là danh sách 10 rủi ro bảo mật nghiêm trọng nhất cho API, được cập nhật định kỳ bởi cộng đồng bảo mật toàn cầu. Phiên bản mới nhất (2023) bao gồm:

  1. API1 — Broken Object Level Authorization (BOLA): Người dùng truy cập được dữ liệu của người khác bằng cách thay đổi ID trong request.
  2. API2 — Broken Authentication: Lỗi trong cơ chế xác thực — token không hết hạn, password yếu, thiếu rate limit login.
  3. API3 — Broken Object Property Level Authorization: API trả về quá nhiều dữ liệu hoặc cho phép sửa fields không nên sửa.
  4. API4 — Unrestricted Resource Consumption: API không giới hạn tài nguyên — cho phép upload file quá lớn, query quá nhiều records.
  5. API5 — Broken Function Level Authorization: Người dùng thường truy cập được API admin.
  6. API6 — Unrestricted Access to Sensitive Business Flows: Attacker tự động hóa business flow (mua hàng, đăng ký) gây thiệt hại.
  7. API7 — Server Side Request Forgery (SSRF): API fetch URL do user cung cấp mà không validate, cho phép tấn công hệ thống nội bộ.
  8. API8 — Security Misconfiguration: CORS sai, error message lộ thông tin, thiếu security headers.
  9. API9 — Improper Inventory Management: API cũ không được vô hiệu hóa, tài liệu API không cập nhật.
  10. API10 — Unsafe Consumption of APIs: Ứng dụng trust dữ liệu từ third-party API mà không validate.

Prompt template: Full OWASP review

Dưới đây là prompt toàn diện để Claude review code API theo tất cả 10 tiêu chí OWASP.

Review code API sau theo OWASP API Security Top 10 (2023).

Tech stack: [Node.js/Express hoặc Python/FastAPI hoặc ...]
Authentication: [JWT / Session / API Key / OAuth]
Database: [PostgreSQL / MongoDB / ...]

Code cần review:
[Dán toàn bộ code API — routes, controllers, middleware, models]

Với mỗi OWASP category (API1-API10):
1. Status: PASS / FAIL / WARNING / NOT APPLICABLE
2. Findings: Mô tả cụ thể lỗ hổng tìm thấy (file, dòng code)
3. Severity: Critical / High / Medium / Low
4. Exploit scenario: Cách attacker có thể khai thác
5. Fix: Code sửa đổi cụ thể
6. Test: Cách verify rằng fix hoạt động

Output format:
## API1: Broken Object Level Authorization
Status: FAIL
Severity: Critical

Finding: Endpoint GET /api/users/:id không kiểm tra user chỉ có thể truy cập record của chính mình.
File: routes/users.js, dòng 15

Exploit: Attacker gửi GET /api/users/2 với token của user 1, nhận được thông tin user 2.

Fix:
// BEFORE (vulnerable)
router.get('/users/:id', auth, async (req, res) => {
  const user = await User.findById(req.params.id);
  res.json(user);
});

// AFTER (fixed)
router.get('/users/:id', auth, async (req, res) => {
  if (req.params.id !== req.user.id && !req.user.isAdmin) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  const user = await User.findById(req.params.id);
  res.json(user);
});

Test: Gửi request với token user A đến endpoint user B, expect 403.

Cuối cùng: Tóm tắt bảng tổng hợp tất cả 10 categories và overall risk score.

API1: Broken Object Level Authorization (BOLA)

BOLA là lỗ hổng phổ biến nhất và nguy hiểm nhất. Xảy ra khi API không kiểm tra người dùng có quyền truy cập object được yêu cầu hay không. Claude có thể scan code để phát hiện pattern BOLA.

Scan code sau tìm lỗ hổng BOLA (Broken Object Level Authorization).

[Dán code routes/controllers]

Kiểm tra từng endpoint:
1. Có endpoint nào dùng user-supplied ID mà không verify ownership không?
   Pattern nguy hiểm: req.params.id sử dụng trực tiếp trong DB query
   mà không kiểm tra req.user.id

2. Tìm tất cả endpoints dạng:
   - GET /resource/:id
   - PUT /resource/:id
   - DELETE /resource/:id
   Với mỗi endpoint: Có authorization check cho object-level không?

3. Mass assignment: Có endpoint nào cho phép user update fields
   không nên update (isAdmin, role, balance)?

4. IDOR trong file/image access: URL dạng /uploads/invoice_123.pdf
   có ai cũng download được không?

Với mỗi finding, viết test case để verify:
- HTTP method + URL
- Headers (Authorization)
- Expected vs. Actual response
- Test cho cả positive case (owner) và negative case (non-owner)

API2: Broken Authentication

Lỗi xác thực có thể cho phép attacker đăng nhập vào tài khoản bất kỳ. Claude kiểm tra toàn bộ authentication flow.

Review authentication implementation trong code sau.

[Dán code auth middleware, login endpoint, token generation]

Kiểm tra:
1. Password handling:
   - Có hash password trước khi lưu không? Dùng algorithm nào?
   - bcrypt/argon2 = OK, md5/sha1 = CRITICAL
   - Salt có unique per user không?
   - Password policy: Có yêu cầu complexity không?

2. Token/Session management:
   - JWT secret có đủ mạnh không? Có hardcode không?
   - Token có expiration không? Thời gian bao lâu?
   - Refresh token flow có an toàn không?
   - Token có bị revoke khi đổi password/logout không?

3. Rate limiting:
   - Login endpoint có rate limit không?
   - Có lockout sau N lần fail không?
   - Rate limit có bypass được bằng cách thay IP/headers không?

4. Multi-factor authentication:
   - Có support MFA không?
   - OTP có expiration đủ ngắn không?
   - Có backup codes không?

5. Session fixation/hijacking:
   - Session ID có regenerate sau login không?
   - Cookies có HttpOnly, Secure, SameSite flags không?

Đánh giá overall authentication strength: Strong/Medium/Weak

API3: Broken Object Property Level Authorization

Lỗ hổng này gồm 2 vấn đề: Excessive Data Exposure (API trả về quá nhiều thông tin) và Mass Assignment (API cho phép sửa fields không nên sửa). Claude kiểm tra cả response schema và request handling.

Kiểm tra API responses và request handling cho Excessive Data Exposure
và Mass Assignment.

[Dán code API endpoints + models/schemas]

Kiểm tra Excessive Data Exposure:
1. API response có trả về fields nhạy cảm không?
   - password/hash
   - internal IDs
   - email/phone của user khác
   - financial data không cần thiết
   - admin flags
2. Có dùng serialization/DTO để kiểm soát output không?
3. GraphQL: Có introspection query bật ở production không?

Kiểm tra Mass Assignment:
1. Có endpoint nào dùng trực tiếp req.body để update model không?
   Pattern nguy hiểm: Model.findByIdAndUpdate(id, req.body)
2. Whitelist approach: Có explicitly cho phép chỉ các fields nhất định?
3. Có thể gửi { "role": "admin" } trong request body để tự nâng quyền?

Với mỗi finding:
- Code before (vulnerable)
- Code after (fixed) - dùng whitelist pattern
- Curl command để test

API4-API5: Resource Consumption và Function Level Authorization

Review API cho Unrestricted Resource Consumption (API4)
và Broken Function Level Authorization (API5).

[Dán code]

API4 - Resource Consumption:
1. Pagination: Có giới hạn page size không? Ai đó có thể request ?limit=999999?
2. File upload: Giới hạn file size? File type validation?
3. Query complexity: GraphQL có query depth limit không?
4. Rate limiting: Có global rate limit cho tất cả endpoints không?
5. Timeout: API calls đến third-party có timeout không?
6. Regex: Có regex nào dễ bị ReDoS (catastrophic backtracking) không?

API5 - Function Level Authorization:
1. Admin endpoints có riêng middleware check role không?
2. Có endpoint nào chỉ check authentication mà không check authorization?
   Ví dụ: Mọi logged-in user đều truy cập được /api/admin/users
3. HTTP method-based: GET an toàn nhưng DELETE cùng path thì sao?
4. Có API documentation nào expose admin endpoints cho public không?

Tạo bảng tổng hợp: Endpoint | Method | Auth Required | Role Required | Status

API7: Server Side Request Forgery (SSRF)

SSRF xảy ra khi API fetch URL do user cung cấp mà không validate. Attacker có thể dùng server của bạn để tấn công hệ thống nội bộ — đọc metadata cloud, truy cập internal services.

Tìm lỗ hổng SSRF trong code sau.

[Dán code]

Tìm tất cả chỗ code fetch/request URL từ user input:
1. fetch(userInput) hoặc axios.get(userInput)
2. Image proxy: /api/image?url=...
3. Webhook registration: User đăng ký URL callback
4. Import from URL: CSV/JSON import từ URL user cung cấp
5. PDF generation: HTML-to-PDF với URL references

Với mỗi finding:
1. Exploit scenario:
   - Đọc AWS metadata: http://169.254.169.254/latest/meta-data/
   - Port scanning internal network: http://internal-service:8080
   - Đọc file local: file:///etc/passwd
2. Fix:
   - URL validation: whitelist domains, block private IPs
   - Dùng allowlist thay vì blocklist
   - DNS rebinding protection
3. Code example fix:

const { URL } = require('url');
const dns = require('dns');
const ipaddr = require('ipaddr.js');

async function validateUrl(inputUrl) {
  const parsed = new URL(inputUrl);
  // Only allow HTTPS
  if (parsed.protocol !== 'https:') throw new Error('HTTPS only');
  // Resolve DNS and check for private IPs
  const addresses = await dns.promises.resolve4(parsed.hostname);
  for (const addr of addresses) {
    const ip = ipaddr.parse(addr);
    if (ip.range() !== 'unicast') {
      throw new Error('Private IP not allowed');
    }
  }
  return inputUrl;
}

API8: Security Misconfiguration

Misconfiguration là lỗi dễ mắc nhất nhưng cũng dễ fix nhất. Claude có thể scan configuration files và server setup.

Review security configuration cho API server.

[Dán các file config: app.js/server.js, package.json, nginx.conf, .env.example]

Kiểm tra:
1. CORS configuration:
   - Origin có set cụ thể hay dùng * (wildcard)?
   - Credentials có enabled cùng wildcard origin không? (Dangerous!)
   - Methods và headers có restrict không?

2. Security headers:
   - Helmet.js (Node) hoặc tương đương có dùng không?
   - Content-Security-Policy
   - X-Content-Type-Options: nosniff
   - X-Frame-Options
   - Strict-Transport-Security

3. Error handling:
   - Error responses có lộ stack trace ở production không?
   - Database error messages có hiển thị cho user không?
   - 404 response có khác nhau giữa "not found" vs "no permission" không?
     (Information disclosure qua response differentiation)

4. Dependencies:
   - Phân tích package.json: Có package nào có known vulnerabilities không?
   - Có lock file (package-lock.json) không?
   - Node version có up-to-date không?

5. Environment:
   - DEBUG mode có tắt ở production không?
   - API docs (Swagger) có expose ở production không?
   - Default credentials có bị thay đổi chưa?

Output: Bảng config items, current value, recommended value, severity

Xây dựng Secure Coding Checklist cho team

Sau khi review code, bước tiếp theo là xây dựng checklist để team áp dụng cho mọi PR/code review trong tương lai.

Dựa trên kết quả OWASP review ở trên, tạo Secure Coding Checklist
cho team development.

Yêu cầu:
1. Checklist cho DEVELOPER (trước khi tạo PR):
   - 15-20 items, chia theo category
   - Mỗi item: checkbox + mô tả ngắn + ví dụ code
   - Ưu tiên theo severity

2. Checklist cho CODE REVIEWER (khi review PR):
   - 10-15 items focus vào security
   - Red flags cần tìm trong code
   - Patterns nguy hiểm phổ biến

3. Automated checks (có thể add vào CI/CD):
   - ESLint/Semgrep rules cho common vulnerabilities
   - Dependency scanning commands
   - Docker security scanning

4. Security testing templates:
   - 5 test cases cho BOLA
   - 5 test cases cho authentication bypass
   - 5 test cases cho injection

Format: Markdown, sẵn sàng commit vào repo làm SECURITY.md

Tích hợp Claude vào PR review workflow

Thay vì review thủ công, bạn có thể tích hợp Claude vào workflow code review để tự động kiểm tra security issues trong mỗi pull request. Cách đơn giản nhất là tạo script chạy Claude trên code diff và comment kết quả vào PR.

# Script review PR security (simplified)
# Chạy: ./security-review.sh 

#!/bin/bash
PR_NUMBER=$1

# Get PR diff
DIFF=$(gh pr diff $PR_NUMBER)

# Get changed files
FILES=$(gh pr diff $PR_NUMBER --name-only)

# Filter only API-related files
API_FILES=$(echo "$FILES" | grep -E "(routes|controllers|middleware|api)/")

if [ -z "$API_FILES" ]; then
  echo "No API files changed in this PR"
  exit 0
fi

# Get full content of changed files
CONTENT=""
for file in $API_FILES; do
  CONTENT="$CONTENT

--- File: $file ---
$(cat $file)"
done

# Call Claude API for review
# (In practice, use the API directly)
echo "Reviewing files: $API_FILES"
echo "Diff size: $(echo "$DIFF" | wc -l) lines"

# Post review comment to PR
# gh pr comment $PR_NUMBER --body "$REVIEW_RESULT"

API10: Unsafe Consumption of APIs

Lỗ hổng này thường bị bỏ qua — khi ứng dụng của bạn gọi third-party API và trust response mà không validate. Attacker có thể compromise third-party API hoặc thực hiện man-in-the-middle attack để inject dữ liệu độc hại.

Kiểm tra code cho Unsafe API Consumption (OWASP API10).

[Dán code gọi third-party APIs]

Tìm:
1. Trust without validation:
   - Có nơi nào dùng trực tiếp response từ external API mà không validate schema?
   - Có nơi nào inject response vào SQL/HTML mà không sanitize?
   - Có parse JSON từ external source mà không handle malformed data?

2. Missing error handling:
   - Nếu third-party API trả về unexpected data, app xử lý thế nào?
   - Timeout handling khi third-party API chậm
   - Retry logic có an toàn không (idempotency)?

3. Security of connections:
   - Có verify SSL certificates khi gọi external APIs không?
   - Có dùng HTTPS cho mọi external calls không?
   - API keys cho third-party services có được bảo vệ đúng cách?

4. Data leakage:
   - Có gửi sensitive data cho third-party API mà không cần thiết?
   - Logging có ghi lại responses chứa sensitive data?

Với mỗi finding: Code hiện tại, code đã fix, và test case verify.

Mẹo review security code với Claude

  • Cung cấp đầy đủ context — tech stack, framework, database. Claude cho kết quả chính xác hơn nhiều khi biết bạn dùng Express vs. FastAPI.
  • Review theo từng OWASP category một — thay vì hỏi "check all", tập trung từng category sẽ cho kết quả sâu hơn.
  • Cung cấp cả middleware/auth code — nhiều lỗ hổng chỉ phát hiện khi thấy middleware chain đầy đủ.
  • Yêu cầu exploit scenarios — không chỉ "có lỗi gì" mà "attacker khai thác thế nào". Giúp team hiểu severity thực sự.
  • Kết hợp với automated tools — Claude tốt cho logic flaws, nhưng static analysis tools (Semgrep, Snyk) tốt hơn cho pattern matching at scale.
  • Review cả test code — test có cover security cases không? Nếu không, Claude có thể viết test bổ sung.

Bước tiếp theo

Bạn đã nắm được cách dùng Claude để review API security theo chuẩn OWASP Top 10. Từ phát hiện BOLA, authentication flaws đến SSRF và misconfiguration — Claude giúp bạn nhận diện lỗ hổng trước khi attacker làm. Tiếp theo, hãy tìm hiểu cách tích hợp Claude Code Security vào CI/CD pipeline để tự động hóa security review. Khám phá thêm tại Thư viện Ứng dụng Claude.

Tính năng liên quan:OWASP Top 10API SecurityCode ReviewVulnerability Detection

Bai viet co huu ich khong?

Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.

Bình luận (0)
Ảnh đại diện
Đăng nhập để bình luận...
Đăng nhập để bình luận
  • Đang tải bình luận...

Đăng ký nhận bản tin

Nhận bài viết hay nhất về sản phẩm và vận hành, gửi thẳng vào hộp thư của bạn.

Bảo mật thông tin. Hủy đăng ký bất cứ lúc nào. Chính sách bảo mật.