Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tuannguyen29/814f1dd74fc47cd1c72f162b57c7d789 to your computer and use it in GitHub Desktop.
Save tuannguyen29/814f1dd74fc47cd1c72f162b57c7d789 to your computer and use it in GitHub Desktop.
Tìm hiểu PHP Security từ cơ bản đến nâng

Tìm hiểu PHP Security từ cơ bản đến nâng cao

Tìm hiểu PHP Security từ cơ bản đến nâng cao

Dưới đây là chi tiết chuyên sâu về phần “Hiểu sâu PHP bảo mật”, được thiết kế theo cấp độ từ cơ bản đến nâng cao, kèm ví dụ thực tế và bài tập thực hành:


1. SQL Injection (SQLi)

Cấp độ 1: Phòng chống cơ bản

  • Sử dụng PDO Prepared Statements:

    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");$stmt->execute(['email' => $userInput]);
  • Tránh sử dụng mysql_* functions (đã deprecated từ PHP 5.5).

Cấp độ 2: Phòng chống nâng cao

  • ORM Security:

    • Sử dụng Query Builder (ví dụ: Phalcon Query Builder) với auto-escaping
    $users = Users::query()
      ->where("email = :email:")
      ->bind(["email" => $userInput])
      ->execute();
  • White-list Input Validation:

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      throw new InvalidArgumentException("Invalid email format");}

Bài tập thực hành:

  • Fix đoạn code vulnerable:

    // Vulnerable code$query = "SELECT * FROM products WHERE category = '" . $_GET['cat'] . "'";
  • Tạo SQLi lab với UNION-based attack.


2. Cross-Site Scripting (XSS)

Phòng chống theo Context:

  • HTML Context:

    echo htmlspecialchars($userContent, ENT_QUOTES, 'UTF-8');
  • JavaScript Context:

    $jsonData = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS);
  • CSS Context:

    $css = preg_replace('/[^a-z0-9\-]/i', '', $userInput);
  • Bảo mật một request/response ajax/api

  • Get php array in javascript (clean DOM) ex: var resData = <?php echo json_encode($data['calendarItems']) ?>

  • Link tham khảo thêm, tấn công XSS là vô hạn: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

Nâng cao:

  • Content Security Policy (CSP):

    header("Content-Security-Policy: default-src 'self'; script-src 'nonce-".$random."'");
  • Sanitize với HTML Purifier:

    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
    $cleanHtml = $purifier->purify($dirtyHtml);

3. Cross-Site Request Forgery (CSRF)

Triển khai:

  • Token Generation:

    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
  • Token Validation:

    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
      die('CSRF validation failed');}

Nâng cao:

  • Double Submit Cookie Pattern

  • Integrate với Frameworks:

    // Trong Phalcon$this->security->checkToken();

4. File Upload Security

Quy trình validate:

  1. Kiểm tra MIME Type:

    $finfo = new finfo(FILEINFO_MIME_TYPE);$mime = $finfo->file($_FILES['file']['tmp_name']);
  2. Đổi tên file:

    $newName = bin2hex(random_bytes(16)) . '.' . $allowedExtension;
  3. Giới hạn quyền:

    chmod($filePath, 0644);
  4. Ngoài validate check file type, rename file thì:

  1. Cách Phòng chống Directory traversal, sử dụng realpath(), method POST ex: https://stackoverflow.com/a/4205278

Bài tập:

  • Viết class xử lý upload ảnh với các chức năng:
    • Resize ảnh
    • EXIF data stripping
    • Virus scanning (sử dụng ClamAV API)

5. Authentication & Session Security

Best Practices:

  • Password Hashing:

    $hash = password_hash($password, PASSWORD_ARGON2ID);
  • Session Fixation Protection:

    session_regenerate_id(true);
  • 2FA Implementation:

    • Sử dụng TOTP (Google Authenticator)

Session Configuration:

ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Strict');

6. Security Headers

Các headers bắt buộc:

header("X-Content-Type-Options: nosniff");header("X-Frame-Options: DENY");header("Strict-Transport-Security: max-age=31536000; includeSubDomains");

7. Error Handling & Logging

Cấu hình Production:

ini_set('display_errors', 0);ini_set('log_errors', 1);

Secure Logging:

// Tránh log sensitive data$logger->info('Login attempt', [
  'username' => $username,  'ip' => $_SERVER['REMOTE_ADDR'],  // KHÔNG log password]);

8. Security Tools Integration

  • Static Analysis:
    • Sử dụng PHPStan với security rules
    • Psalm với plugin security
  • Dynamic Analysis:
    • OWASP ZAP scanning
    • Nikto vulnerability scanner

9. Secure Coding Practices

  • Input Validation:

    $userId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
  • Output Encoding

  • Principle of Least Privilege

  • Regular Dependency Auditing:

    composer audit

10. Hidden Error

  • Kiểm tra config xem đã tắt hiển thị lỗi (error_reporting) khi đang ở production chưa ex: https://stackoverflow.com/a/34789044/16363268
  • Để hạn chế các lỗi ngoài view thì nên:
    • check data trước khi in ra view (check empty/isset các params ...)
    • test kỹ app trước khi deploy để tránh xảy ngoại lệ (exception errors)
  • exception errors:
    • Không nên show message từ "throw exception", mà nên trả về một message kèm một code để biết vị trí
      • ví dụ "Có lỗi xảy ra, vui lòng liên hệ admin. (1001)"
      • Còn message từ "throw exception" thì log vào file
    • Một số trường hợp có thể sử dụng try/catch:
      • Get data từ nguồn khác (curl/api ...)
      • Get data từ file
      • DB-exception

Lab thực hành tổng hợp:

  1. Vulnerable Web App: Cho intern fix 1 ứng dụng có chủ đích chứa các lỗ hổng:
    • SQLi trong search form
    • XSS trong comment section
    • CSRF trong password change function
    • File upload vulnerability
  2. Capture The Flag (CTF):
    • Tạo các challenge bảo mật PHP để exploit và patch

Tài nguyên tham khảo:

  1. OWASP PHP Security Cheat Sheet
  2. Sách:
    • “PHP Security” by O’Reilly
    • “Web Application Security” by Andrew Hoffman
  3. Labs:
    • PortSwigger Web Security Academy
    • Hack The Box (PHP challenges)

Checklist đánh giá code review:

  • Tất cả user input được validate/sanitize
  • Không có raw SQL queries
  • Session cookies được config secure flags
  • Không hardcode credentials
  • Error messages không expose thông tin nhạy cảm
  • Mật khẩu được hash bằng algorithm mạnh (Argon2id/bcrypt)

Bằng cách kết hợp giữa lý thuyết về các attack vectors và thực hành fix vulnerabilities trong môi trường controlled lab, bạn sẽ phát triển được tư duy bảo mật chủ động (security mindset) thay vì chỉ học thuộc các biện pháp phòng thủ.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment