Skip to main content

Insecure service configuration - Host verification

Need

Secure host verification and restrict incoming connections from unknown external hosts

Context

  • Usage of Python 3 for writing and executing Python code
  • Usage of Django for building web applications in Python

Description

Non compliant code

# In settings.py
ALLOWED_HOSTS = ['*']

In the Django settings file (settings.py), the ALLOWED_HOSTS variable is a security measure to prevent HTTP Host header attacks. It is a list of strings representing the host/domain names that the Django application can serve.

In the vulnerable code above, ALLOWED_HOSTS is set to ['*'], which means that the application can serve any host. This is insecure because it allows incoming connections from any unknown external hosts, exposing the application to potential attacks.

Attackers can exploit this by sending requests with a malicious Host header, causing various issues such as cache poisoning, password reset poisoning, or bypassing the same-origin policy.

To fix this vulnerability, you should only allow connections from trusted hosts. For example, if your application is hosted at mywebsite.com, you should set ALLOWED_HOSTS = ['mywebsite.com']. If you are in a development environment and need to allow all hosts, consider using a debug flag to only allow all hosts in development, not in production.

Steps

  • Identify the specific hosts that your application needs to communicate with.
  • Replace the wildcard '*' in the ALLOWED_HOSTS setting with a list of the identified hosts.
  • Ensure that the list only contains trusted hosts to prevent unauthorized access.
  • Test the application to ensure it still functions correctly with the new configuration.
  • Regularly review and update the ALLOWED_HOSTS setting as the list of trusted hosts may change over time.

Compliant code

# In settings.py
ALLOWED_HOSTS = ['host1.com', 'host2.com', 'localhost', '127.0.0.1']

The original code had a wildcard '*' in the ALLOWED_HOSTS setting, which means it would accept incoming connections from any host. This is a security vulnerability as it allows unauthorized external hosts to connect to the system.

The updated code replaces the wildcard '*' with a list of specific, trusted hosts ('host1.com', 'host2.com', 'localhost', '127.0.0.1'). This restricts incoming connections to only these trusted hosts, thereby mitigating the risk of unauthorized access.

It's important to note that the list of allowed hosts should be regularly reviewed and updated as necessary. If a new host needs to be allowed, it should be added to this list. Conversely, if a host is no longer trusted or necessary, it should be removed from the list.

After updating the ALLOWED_HOSTS setting, the application should be thoroughly tested to ensure it still functions correctly with the new configuration.

References