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:
-
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).
-
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");}
-
Fix đoạn code vulnerable:
// Vulnerable code$query = "SELECT * FROM products WHERE category = '" . $_GET['cat'] . "'";
-
Tạo SQLi lab với UNION-based attack.
-
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
-
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);
-
Token Generation:
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
-
Token Validation:
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { die('CSRF validation failed');}
-
Double Submit Cookie Pattern
-
Integrate với Frameworks:
// Trong Phalcon$this->security->checkToken();
-
Kiểm tra MIME Type:
$finfo = new finfo(FILEINFO_MIME_TYPE);$mime = $finfo->file($_FILES['file']['tmp_name']);
-
Đổi tên file:
$newName = bin2hex(random_bytes(16)) . '.' . $allowedExtension;
-
Giới hạn quyền:
chmod($filePath, 0644);
-
Ngoài validate check file type, rename file thì:
- có thể giới hạn dung lượng đc up lên server (file size)
- có thể nén file size mà ko làm giảm chất lượng hình ảnh. Full example: https://docs.php.earth/security/uploading/
- Cách Phòng chống
Directory traversal
, sử dụngrealpath()
, methodPOST
ex: https://stackoverflow.com/a/4205278
- 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)
-
Password Hashing:
$hash = password_hash($password, PASSWORD_ARGON2ID);
-
Session Fixation Protection:
session_regenerate_id(true);
-
2FA Implementation:
- Sử dụng TOTP (Google Authenticator)
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Strict');
header("X-Content-Type-Options: nosniff");header("X-Frame-Options: DENY");header("Strict-Transport-Security: max-age=31536000; includeSubDomains");
ini_set('display_errors', 0);ini_set('log_errors', 1);
// Tránh log sensitive data$logger->info('Login attempt', [
'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR'], // KHÔNG log password]);
- Static Analysis:
- Sử dụng PHPStan với security rules
- Psalm với plugin security
- Dynamic Analysis:
- OWASP ZAP scanning
- Nikto vulnerability scanner
-
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
- 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í
- 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
- Capture The Flag (CTF):
- Tạo các challenge bảo mật PHP để exploit và patch
- OWASP PHP Security Cheat Sheet
- Sách:
- “PHP Security” by O’Reilly
- “Web Application Security” by Andrew Hoffman
- Labs:
- PortSwigger Web Security Academy
- Hack The Box (PHP challenges)
- 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ủ.