Trang chủ
QA Learning Hub
Chương 09 · Security Testing
Chương 09 Trung Cấp

Security Testing

Hiểu OWASP Top 10, thực hiện manual security test cases, sử dụng ZAP và Burp Suite để phát hiện lỗ hổng bảo mật trước khi attacker tìm ra.

🛡️OWASP Top 10 — 2023

OWASP Top 10 là danh sách các rủi ro bảo mật web phổ biến và nguy hiểm nhất, được cập nhật định kỳ. Là QA, bạn không cần exploit như hacker, nhưng phải biết cách verify rằng application có được bảo vệ khỏi các class lỗi này không.

A01 — Broken Access Control (Kiểm soát truy cập bị phá vỡ)

Đây là lỗi #1 phổ biến nhất. Xảy ra khi user có thể truy cập tài nguyên/chức năng ngoài quyền hạn của họ.

  • Mô tả: User A xem được dữ liệu của User B; user thường truy cập được trang admin; thay đổi ID trong URL để truy cập record của người khác (IDOR).
  • Test thủ công: Đăng nhập user thường, copy URL của trang admin, mở tab ẩn danh với user thường và paste URL đó. Nếu truy cập được → lỗi. Thay ?id=123 thành ?id=124 (ID của user khác).
  • Payload ví dụ: GET /api/users/456/profile khi bạn đang login là user ID 123. DELETE /api/orders/789 với order của người khác.
  • Verify đã fix: Request trả về 403 Forbidden hoặc 404 Not Found. Response body không chứa dữ liệu của user khác. Server log ghi nhận unauthorized access attempt.

A02 — Cryptographic Failures (Lỗi mã hóa)

  • Mô tả: Dữ liệu nhạy cảm (password, credit card, PII) không được mã hóa hoặc dùng thuật toán yếu (MD5, SHA1 không salt).
  • Test thủ công: Dùng browser DevTools → Network tab, kiểm tra response có chứa plain text password/card number không. Kiểm tra cookie có flag SecureHttpOnly không. Verify HTTPS redirect từ HTTP.
  • Payload ví dụ: Tạo account, request GET /api/profile, xem response — password field có bị hash không? Hay trả về plain text?
  • Verify đã fix: Password field không xuất hiện trong response. Cookie có cả hai flag. http:// redirect về https:// với status 301.

A03 — Injection (SQL, NoSQL, Command Injection)

  • Mô tả: User input được truyền trực tiếp vào query database hoặc command shell mà không được sanitize.
  • Test thủ công — SQL Injection: Nhập ' (single quote) vào search field. Nếu app báo database error → dấu hiệu vulnerable. Thử ' OR '1'='1 trong login form.
  • Payload ví dụ: Username: admin'-- | Password: bất kỳ. Hoặc trong search: ' UNION SELECT username,password FROM users--
  • Verify đã fix: App trả về lỗi validation thông thường, không hiện database error message. Login với payload trên bị từ chối. WAF log ghi nhận attack attempt.

A07 — Identification & Authentication Failures

  • Mô tả: Weak passwords được chấp nhận, không có brute-force protection, session token không expire, "remember me" tồn tại quá lâu.
  • Test thủ công: Thử đăng nhập sai 10 lần liên tiếp → có bị lockout không? Thử password "password123", "123456" → có được chấp nhận không? Đăng xuất, copy session cookie, paste lại → có hoạt động không?
  • Payload ví dụ: Brute-force simulation: dùng Burp Intruder với wordlist password phổ biến. Kiểm tra session token sau logout vẫn valid.
  • Verify đã fix: Account lockout sau 5 lần sai. Password policy enforce uppercase + số + ký tự đặc biệt. Session token invalid sau logout.

A10 — Server-Side Request Forgery (SSRF)

  • Mô tả: App fetch URL do user cung cấp, attacker lợi dụng để scan internal network hoặc access internal services.
  • Test thủ công: Nếu app có tính năng "import from URL" hoặc "fetch avatar from URL", thử nhập http://169.254.169.254/latest/meta-data/ (AWS metadata) hoặc http://localhost:8080/admin.
  • Payload ví dụ: {"avatar_url": "http://internal-api.company.com/admin/users"}
  • Verify đã fix: App từ chối URL trỏ đến private IP ranges (10.x.x.x, 192.168.x.x, 172.16.x.x, 169.254.x.x). Response không chứa internal data.
Lưu ý quan trọng
Chỉ test security trên môi trường được authorized (staging, dev). Không bao giờ test trên production mà không có written approval. Mọi security testing phải có scope rõ ràng trong test plan.
📋Manual Security Test Cases — 35 Checklist Items

Checklist toàn diện cho security testing thủ công, phân theo category:

Authentication (Xác thực)

  • Thử đăng nhập với username đúng nhưng password sai — thông báo lỗi có tiết lộ "username tồn tại" không?
  • Brute-force 10+ lần login sai — có account lockout không? Lockout bao lâu?
  • Forgot password: link reset có expire sau 15-30 phút không? Dùng được một lần rồi invalid không?
  • Password reset link có chứa user ID/email trong URL không (phải hash/token thay thế)?
  • Multi-factor authentication: bypass được bằng cách skip URL không?
  • Đổi password: có yêu cầu nhập password cũ không? Có invalidate các session khác không?
  • "Remember me" cookie: expire sau bao lâu? Có revoke được không khi đổi password?

Authorization (Phân quyền)

  • IDOR: thay ID trong URL/request body → có truy cập được data của user khác không?
  • Horizontal privilege escalation: user A thực hiện action trên resource của user B.
  • Vertical privilege escalation: user thường truy cập endpoint của admin.
  • Direct URL access: copy URL từ admin session, paste vào user session.
  • API endpoint: gọi API admin endpoint với user token → 403 hay 200?
  • Mass assignment: POST request với extra fields như "role":"admin" có được accept không?

Session Management

  • Session fixation: session ID có thay đổi sau khi đăng nhập thành công không?
  • Session timeout: sau 30 phút không hoạt động, session có tự expire không?
  • Concurrent sessions: đăng nhập 2 tab cùng lúc — cả hai đều active? Có option "đăng xuất thiết bị khác" không?
  • Logout hoàn toàn: sau logout, back button có vào được app không? Cookie đã bị xóa chưa?
  • Session cookie: có Secure, HttpOnly, SameSite attribute không?

Input Validation

  • XSS reflected: nhập <script>alert(1)</script> vào search/comment field → có execute không?
  • XSS stored: lưu payload vào profile/comment, reload page → có execute không?
  • SQL Injection: nhập ' vào mọi input field → có database error không?
  • Path traversal: ../../../etc/passwd trong file download parameter.
  • HTML injection: nhập <h1>Hacked</h1> vào field hiển thị trong email → có render thành HTML không?
  • Integer overflow: nhập số rất lớn (999999999) hoặc số âm (-1) vào quantity field.
  • Special characters: !@#$%^&*() trong text fields — app crash không?

File Upload

  • Upload file .php, .jsp, .aspx được rename thành .jpg — server có execute không?
  • Upload file vượt quá size limit — proper error hay server crash?
  • Upload SVG chứa XSS payload (<svg onload="alert(1)">).
  • Upload file với double extension: shell.php.jpg.
  • Upload path traversal: filename ../../../index.html.

API Security

  • Gọi API không có Authorization header → 401 hay data trả về?
  • Dùng expired token → 401 Unauthorized?
  • Rate limiting: gọi API 100 lần/phút → có bị throttle không?
  • Response có chứa thông tin nhạy cảm thừa (password hash, internal IDs, stack trace) không?
  • OPTIONS request: kiểm tra CORS configuration có quá rộng (*) không?

HTTPS & Transport

  • HTTP → HTTPS redirect hoạt động đúng (301 Permanent, không phải 302 Temporary).
  • HSTS header (Strict-Transport-Security) có được set không?
  • Mixed content: page HTTPS có load resource HTTP không?
  • Certificate: expired? Self-signed? Wildcard đúng domain không?
OWASP ZAP — Automated Security Scanning

OWASP ZAP (Zed Attack Proxy) là công cụ open-source để automated security testing. Phù hợp để QA tích hợp vào CI pipeline và chạy daily scan.

Cài đặt ZAP

  1. Download ZAP từ zaproxy.org → chọn Cross Platform Package (JAR) hoặc installer cho OS của bạn.
  2. Cài Java 11+ nếu chưa có (java -version để kiểm tra).
  3. Chạy ZAP, chọn "Yes, I want to persist this ZAP Session" khi được hỏi.
  4. Configure proxy: ZAP default là localhost:8080. Set browser proxy về đây.
  5. Với HTTPS: download ZAP CA certificate từ Tools → Options → Dynamic SSL Certificates → Save. Import vào browser.

Automated Scan

  1. Quick Scan: Nhập URL vào "URL to attack" field → "Attack". ZAP sẽ tự chạy Spider + Active Scan.
  2. Spider: ZAP crawl tất cả links, forms, endpoints. Kết quả hiện trong Sites tree bên trái.
  3. Ajax Spider: Dùng cho SPA (React, Angular). Tools → Ajax Spider. Cho phép ZAP interact với dynamic content.
  4. Active Scan: ZAP gửi attack payloads đến mọi parameter. Chọn target trong Sites tree → Click "Active Scan". Cảnh báo: Active Scan có thể gây load cao và modify data — chỉ dùng trên test environment.
  5. Xem kết quả trong Alerts tab. Mỗi alert có Risk Level: High/Medium/Low/Informational.

Đọc hiểu Alerts

Risk LevelÝ nghĩaVí dụAction
HighLỗ hổng nghiêm trọng, có thể bị exploit ngaySQL Injection, XSS storedBlock release, fix immediately
MediumRủi ro đáng kể, cần fix trước releaseCSRF, Missing security headersFix trong sprint hiện tại
LowRủi ro thấp, best practiceX-Content-Type-Options missingFix khi có time
InformationalKhông phải lỗi, chỉ thông tinCookie without SameSiteReview, decide action

Passive Scan vs Active Scan

Khi nào dùng Passive Scan
Passive Scan chỉ quan sát traffic, không gửi thêm requests. An toàn cho production (đọc-only). Cách dùng: Duyệt app bình thường qua ZAP proxy — ZAP tự phân tích. Phát hiện: missing headers, sensitive data in response, insecure cookies.
Khi nào dùng Active Scan
Active Scan gửi attack payloads — chỉ dùng trên staging/dev environment. Có thể tạo ra dữ liệu rác, lock accounts, gây load cao. Luôn thông báo team trước khi chạy Active Scan.

ZAP trong CI/CD

# GitHub Actions - ZAP Baseline Scan - name: ZAP Baseline Scan uses: zaproxy/action-baseline@v0.11.0 with: target: 'https://staging.yourapp.com' rules_file_name: '.zap/rules.tsv' cmd_options: '-a'
🔬Burp Suite Community — Manual Interception

Burp Suite Community Edition là công cụ không thể thiếu cho manual security testing. Cho phép intercept, modify, và replay HTTP requests.

Setup Burp Proxy

  1. Mở Burp Suite → Proxy tab → Options → Proxy Listener: 127.0.0.1:8080.
  2. Cài FoxyProxy extension cho Firefox. Add profile: HTTP Proxy 127.0.0.1:8080.
  3. Vào http://burpsuite (khi proxy đang bật) → Download Burp CA certificate.
  4. Firefox: Settings → Certificates → Import → chọn file CA vừa download. Trust cho websites.
  5. Bật proxy trong FoxyProxy → Duyệt app → Burp sẽ intercept requests.

Intercept Request

  1. Proxy → Intercept → "Intercept is on". Duyệt app → request bị chặn lại trong Burp.
  2. Xem raw request: method, headers, cookies, body. Modify trực tiếp ở đây.
  3. "Forward" để gửi request đã modify. "Drop" để hủy. "Action → Send to Repeater" để test nhiều lần.

Repeater — Test IDOR

  1. Intercept request GET /api/users/123/orders (với Authorization header của user A).
  2. Send to Repeater (Ctrl+R). Trong Repeater tab, thay 123 thành ID của user khác (ví dụ 124).
  3. Click Send. Nếu response trả về orders của user 124 → IDOR vulnerability.
  4. Thử thay thêm: 124, 125, 1, admin-user-id.
  5. Expected behavior: 403 Forbidden hoặc orders của chính user A (không phải 124).

Decoder — Phân tích Token

  1. Copy JWT token từ Authorization header (phần sau "Bearer ").
  2. Decoder tab → Paste token → "Decode as Base64". JWT có 3 phần ngăn cách bởi dấu chấm.
  3. Phần 2 (payload) sau khi decode sẽ hiện claims: user ID, role, expiry time.
  4. Kiểm tra: role có "admin"? exp còn valid không? Signature algorithm là "none" không (vulnerable)?

Manipulate Request Parameters

Use Case: Price Manipulation
Intercept POST request khi add to cart. Body: {"product_id": 5, "quantity": 1, "price": 299.99}. Thay price thành 0.01 và Forward. Nếu order được tạo với giá 0.01 → lỗi nghiêm trọng. Server phải luôn tính giá từ database, không tin giá từ client.
🔑API Security Testing

API là attack surface lớn nhất trong modern applications. QA cần verify authentication, authorization, và data protection trên tất cả API endpoints.

Authentication Schemes

  • API Key (Header)Header: X-API-Key: abc123. Test: remove header → 401? Dùng key của user khác → truy cập được data của họ không? Key có expire không?
  • API Key (Query)URL: /api/data?api_key=abc123. Nguy hiểm: key xuất hiện trong server logs, browser history, Referer header. Test: key có trong logs không?
  • Bearer TokenHeader: Authorization: Bearer eyJhbGc.... Test: dùng token sau khi logout → 401? Token expire đúng thời gian không?
  • OAuth 2.0Authorization Code flow cho web apps; Client Credentials cho M2M. Test: state parameter có được validate không (CSRF protection)? Redirect URI có bị manipulate không?
  • Basic AuthHeader: Authorization: Basic base64(user:pass). Test: decode Base64 → credentials plain text. Chỉ chấp nhận trên HTTPS. Không phù hợp cho user-facing APIs.

Rate Limiting Verification

  1. Identify endpoints cần rate limit: login, forgot password, API calls, OTP verification.
  2. Dùng Postman Collection Runner hoặc script đơn giản: gọi endpoint 100 lần trong 1 phút.
  3. Sau khi vượt limit, response phải trả về 429 Too Many Requests.
  4. Verify header Retry-After hoặc X-RateLimit-Reset có trong response 429 không.
  5. Test bypass: đổi IP (nếu rate limit theo IP), đổi User-Agent, thêm header X-Forwarded-For.

Sensitive Data trong Response

Review mọi API response và tìm:

  • Password hoặc password hash trong response (dù đã hashed, không nên expose)
  • Full credit card number (chỉ được show 4 số cuối)
  • Social Security Number / CMND / CCCD đầy đủ
  • Internal system IDs, server paths, technology stack info
  • Stack trace trong error response (production phải trả về generic error)
  • Other users' PII khi query chỉ của mình
# Test rate limiting với curl loop for i in {1..20}; do curl -s -o /dev/null -w "%{http_code}\n" \ -X POST https://api.example.com/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"test@test.com","password":"wrong"}' done # Expect: 401 x N lần, sau đó 429
⚖️Khi nào cần Pentest chuyên sâu vs QA Security Testing

Đây là câu hỏi quan trọng mà QA và management thường nhầm lẫn. Hiểu rõ sự khác biệt giúp bạn communicate đúng với stakeholders.

Tiêu chíQA Security TestingProfessional Pentest
Mục tiêuVerify known vulnerabilities được fix; regression testDiscover unknown vulnerabilities; simulate real attacker
Người thực hiệnQA Engineer với security knowledgeCertified penetration tester (OSCP, CEH, GPEN)
FrequencyMỗi sprint / release cycleAnnually, hoặc sau major releases
ScopeChecklist-driven, known attack vectorsBlack/grey/white box, creative exploitation
ToolsZAP, Burp Community, PostmanMetasploit, custom exploits, social engineering
OutputTest report với pass/fail cho từng checklist itemDetailed pentest report với CVSS scores, exploit chains
Chi phíThời gian QA (internal)$10,000–$50,000+ per engagement
ComplianceKhông đủ cho PCI-DSS, SOC 2, ISO 27001Bắt buộc cho nhiều compliance frameworks

Khi nào cần Professional Pentest:

  • Trước khi launch sản phẩm xử lý dữ liệu nhạy cảm (tài chính, y tế, payment)
  • Compliance requirements: PCI-DSS Level 1-2, SOC 2 Type II, HIPAA
  • Sau major architecture changes (migration to cloud, new auth system)
  • Sau khi có security incident để verify remediation
  • Khi có M&A (acquirer muốn assess security posture)

QA Security Testing đủ khi:

  • Internal tools, low-risk features
  • Regression test cho known vulnerabilities đã được fix
  • Sprint-level verification của security requirements
  • OWASP checklist compliance cho standard features
Senior Insight — Security trong CI Pipeline

Integrate security testing vào CI/CD để catch issues sớm. Pipeline stages: (1) SAST — static analysis với Semgrep hoặc SonarQube ngay khi code được push; (2) Dependency scanning — check known CVEs trong packages với Snyk hoặc OWASP Dependency-Check; (3) DAST — ZAP baseline scan sau khi deploy lên staging; (4) Secret scanning — GitLeaks ngăn chặn credential bị commit vào repo.

Threat modeling basics — trước khi code, hỏi 4 câu: (1) What are we building? (2) What can go wrong? — STRIDE model (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege); (3) What do we do about it? (4) Did we do a good enough job? QA tham gia threat modeling giúp identify test cases trước khi code được viết.

✏️Bài Tập
Bài tập thực hành

Bài 1 — IDOR Test: Đăng nhập với 2 account khác nhau. Từ account A, copy API request GET /api/profile với auth token của A. Dùng Burp Repeater, thay user ID trong URL bằng ID của account B. Document: response trả về gì? Có phải 403 không?

Bài 2 — ZAP Passive Scan: Setup ZAP proxy, duyệt qua toàn bộ app (login, thực hiện 5 actions chính). Xem Alerts tab. List tất cả Medium+ alerts với mô tả và evidence.

Bài 3 — Input Validation: Tạo security test matrix cho một registration form (5 fields). Mỗi field: 3 injection payloads khác nhau. Document expected behavior vs actual behavior.

Bài 4 — API Security Checklist: Lấy bất kỳ public API hoặc internal API. Chạy qua 10 items trong API Security checklist ở trên. Write test cases cho 3 items quan trọng nhất.

  1. Setup Burp Suite, configure browser proxy, intercept một login request
  2. Decode JWT token trong Decoder tab, giải thích các claims trong payload
  3. Test 5 OWASP checklist items trên một ứng dụng test (DVWA hoặc Juice Shop)
  4. Chạy ZAP baseline scan, tạo report với top 3 issues cần fix
  5. Viết test cases security cho API authentication của dự án bạn đang làm

Interview Q&A

Sự khác biệt giữa Authentication và Authorization là gì? Làm sao test cả hai?
Authentication = xác minh bạn là ai (login). Authorization = xác minh bạn được phép làm gì. Test Authentication: thử login với credential sai, test session management, brute-force protection. Test Authorization: sau khi login, cố truy cập resource của user khác (IDOR), cố truy cập admin endpoint với user role thường, kiểm tra mọi API endpoint đều enforce authorization không chỉ trang web.
OWASP Top 10 là gì và tại sao QA cần biết?
OWASP Top 10 là danh sách 10 rủi ro bảo mật web phổ biến và nguy hiểm nhất, được OWASP (Open Web Application Security Project) publish. QA cần biết vì: (1) cung cấp framework để plan security test cases; (2) common language với developers và security team; (3) giúp prioritize security testing effort; (4) nhiều companies yêu cầu OWASP compliance.
Làm sao test SQL Injection mà không gây hại cho database?
Test trên staging environment, không bao giờ production. Bắt đầu với passive probing: nhập single quote ' và xem response — database error = dấu hiệu vulnerable. Dùng ZAP passive scan (không modify data). Nếu cần xác nhận sâu hơn, dùng time-based blind SQLi payloads với harmless functions như SLEEP(1) trên staging. Document evidence (error messages) không cần exploit thực sự.
Bạn tìm thấy một critical security vulnerability trong production. Quy trình xử lý như thế nào?
Immediate escalation: thông báo ngay Security Lead hoặc Engineering Manager — không post lên chat public hay Jira mà mọi người đọc được. Document evidence (screenshots, request/response) nhưng minimize exposure. Tham gia incident response meeting. Verify remediation trên staging trước khi deploy fix. Viết post-mortem và add test case vào regression suite. Không disclose externally cho đến khi fix được deploy (responsible disclosure).
Passive scan và Active scan trong ZAP khác nhau thế nào? Bạn dùng cái nào khi nào?
Passive scan chỉ observe và analyze traffic qua proxy, không gửi thêm requests. An toàn cho mọi môi trường kể cả production. Phát hiện: missing security headers, sensitive data in response, insecure cookies. Active scan gửi attack payloads đến mọi parameter — có thể modify data, lock accounts, gây load cao. Chỉ dùng trên isolated test environment với sự đồng ý của team. Rule: Passive = daily/staging/production monitoring. Active = sprint-end security testing trên dedicated test environment.