起因
近期對線上項目進行安全掃描時,發現某系統存在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.