John Davidson

How to prevent Host Header Injection in PHP and Apache

0 comments
Message:


I want my website to prevent host header injection, to achieve this I applied the following code in PHP.



$allowed_hosts = [
"127.0.0.1",
"localhost",
"10.x.x.28"
];

if (isset($_SERVER['HTTP_HOST']) && !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
http_response_code(403);
die();
}

if (isset($_SERVER['SERVER_NAME']) && !in_array($_SERVER['SERVER_NAME'], $allowed_hosts)) {
http_response_code(403);
die();
}


When I check it using BurpSuite it works fine for http://localhost/mysite/ (with a trailing slash)
but when I access http://localhost/mysite (without a trailing slash) with manipulated host header above code does not make any effect.


Please suggest to me that if I have to configure the server or have to write code.



My Answer:
To prevent host header injection in Apache, you can use the following configuration in your virtual host file:



ServerName example.com
ServerAlias www.example.com
UseCanonicalName On



This configuration will ensure that the server uses the ServerName directive as the canonical name for the server, preventing host header injection attacks.

Additionally, you can also use the mod_headers module in Apache to block requests with manipulated host headers. You can add the following configuration to your virtual host file:



Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "no-referrer-when-downgrade"
Header always set Content-Security-Policy "default-src 'self'"



This configuration will add security headers to your responses, helping to prevent various types of attacks including host header injection.

In addition to the server-side configurations, it's also important to validate and sanitize user input in your PHP code to prevent host header injection attacks. The code you provided in your question is a good start, but you may need to further enhance it based on your specific requirements and use cases.

Rate this post

5 of 5 based on 9790 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us