检测到目标URL存在http host头攻击漏洞?Django项目中危漏洞解决方案实操

起因

近期对线上项目进行安全扫描时,发现某系统存在host头攻击漏洞。
检测到目标URL存在http host头攻击漏洞

背景

上述问题出现的原因为在项目开发中如果想知道上线后运行的域名不是一件简单或者说比较常规的事,如果用一个固定的URI来作为域名又会带来各种麻烦,开发人员一般是依赖HTTP Host header,而这个header很多情况下是靠不住的。很容易遭遇到两种常见的攻击:缓存污染密码重置1
缓存污染是指攻击者通过控制一个缓存系统来将一个恶意站点的页面返回给用户。密码重置这种攻击主要是因为发送给用户的内容是可以污染的,也就是说可以间接的劫持邮件发送内容。
Django官方在2013年的二月通过强制使用一个host白名单来修复了此问题。

解决方案

具体的解决方案就是在项目上线后,将settings.py中的ALLOWED_HOSTS列表进行改动,添加线上域名,同时关闭debug模式

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['example.ZeroChia.com']

扩展

ALLOWED_HOSTS表示当下这个Django站点可以提供的host/domain(主机/域名)。这是一种安全措施,通过使用伪造的HTTP主机标头提交请求来防止攻击者中毒缓存并触发带有恶意主机链接的密码重置电子邮件。2

通俗点说就是限定了请求中的host值,只有在列表中的host才能访问,以防止黑客构造包来发送请求。

当使用*通配符配置ALLOWED_HOSTS时,代表所有地址都可以访问该服务,服务是无保护状态,项目上线必须限定此列表。

DEBUG设置为False的时候必须配置ALLOWED_HOSTS列表。否则会抛出异常。

Django官方文档中关于ALLOWED_HOSTS的部分:

ALLOWED_HOSTS¶
Default: [] (Empty list)

A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations.

Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE).

Django also allows the fully qualified domain name (FQDN) of any entries. Some browsers include a trailing dot in the Host header which Django strips when performing host validation.

If the Host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) does not match any value in this list, the django.http.HttpRequest.get_host() method will raise SuspiciousOperation.

When DEBUG is True and ALLOWED_HOSTS is empty, the host is validated against ['localhost', '127.0.0.1', '[::1]'].

This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection.

Changed in Django 1.10.3:
In older versions, ALLOWED_HOSTS wasn’t checked if DEBUG=True. This was also changed in Django 1.9.11 and 1.8.16 to prevent a DNS rebinding attack.


  1. 利用HTTP host头攻击的技术 – 龙臣 ↩︎

  2. django配置(setting)之ALLOWED_HOSTS ↩︎

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章