Django給表單添加honeypot驗(yàn)證增加安全性
如果你的網(wǎng)站中允許匿名用戶通過POST方式提交表單, 比如用戶注冊(cè)表, 評(píng)論表或者留下用戶聯(lián)系方式的表單,你一定要防止機(jī)器人或爬蟲程序惡意提交大量的垃圾數(shù)據(jù)到你的數(shù)據(jù)庫(kù)中。這種情況不是可能會(huì)發(fā)生,而是一定會(huì)發(fā)生。一種解決這種問題的方式就是在表單中加入人機(jī)交互驗(yàn)證碼(CAPTCHA), 另一種方式就是在表單中加入honeypot隱藏字段,然后在視圖中對(duì)隱藏字段的值進(jìn)行驗(yàn)證。兩種驗(yàn)證方式的目的都是一樣,防止機(jī)器人或程序通過偽裝成人來提交數(shù)據(jù)。今天我們就來詳細(xì)介紹下如何在表單中添加honeypot增加安全性。
Honeypot的工作原理Honeypot又名蜜罐,其實(shí)本質(zhì)上是種陷阱。我們?cè)诒韱沃泄室馔ㄟ^CSS隱藏一些字段, 這些字段一般人是不可見的。然而機(jī)器人或程序會(huì)以為這些字段也是必需的字段(required), 所以會(huì)補(bǔ)全后提交表單,這就中了我們的陷阱。在視圖中我們可以通過裝飾器對(duì)用戶提交的表單數(shù)據(jù)進(jìn)行判斷,來驗(yàn)證表單的合法性。比如honeypot字段本來應(yīng)該為空的,現(xiàn)在居然有內(nèi)容了,顯然這是機(jī)器人或程序提交的數(shù)據(jù),我們可以拒絕其請(qǐng)求。
Django中如何實(shí)現(xiàn)表單honeypot驗(yàn)證?Django表單中添加honeypot,一共分兩步:
1. 編寫模板標(biāo)簽(templatetags),在包含模板的表單中生成honeypot字段。
2. 編寫裝飾器(decorators.py), 對(duì)POST請(qǐng)求發(fā)送來的表單數(shù)據(jù)進(jìn)行驗(yàn)證。
由于honeypot的功能所有app都可以用到,我們創(chuàng)建了一個(gè)叫common的app。整個(gè)項(xiàng)目的目錄結(jié)構(gòu)如下所示。只有標(biāo)藍(lán)色的4個(gè)文件,是與honeypot相關(guān)的。
我們?cè)赾ommon目錄下新建templatetags目錄(包含一個(gè)空的__init__.py),然后在新建common_tags_filters.py, 添加如下代碼。
from django import templatefrom django.conf import settingsfrom django.template.defaultfilters import stringfilterregister = template.Library()# used to render honeypot field@register.inclusion_tag(’common/snippets/honeypot_field.html’)def render_honeypot_field(field_name=None): '''Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME). ''' if not field_name:field_name = getattr(settings, ’HONEYPOT_FIELD_NAME’, ’name1’) value = getattr(settings, ’HONEYPOT_VALUE’, ’’) if callable(value):value = value() return {’fieldname’: field_name, ’value’: value}
我們現(xiàn)在來看下上面這段代碼如何工作的。我們創(chuàng)建了一個(gè)名為render_honeypot_field的模板標(biāo)簽,用于在模板中生成honeypot字段。honeypot字段名是settings.py里HONEYPOT_FIELD_NAME,如果沒有此項(xiàng)設(shè)置,默認(rèn)值為name1。honeypot字段的默認(rèn)值是HONEYPOT_VALUE, 如果沒有此項(xiàng)設(shè)置,默認(rèn)值為空字符串’’。然后這個(gè)函數(shù)將fieldname和value傳遞給如下模板片段。
# common/snippets/honeypot_field.html
<div style='display: none;'><label><input type='text' name='{{ fieldname }}' value='{{ value }}' /> </label></div>
在Django模板的表單中生成honeypot字段只需按如下操作:
{% load common_tags_filters %}{% load static %}<form method='post' action=''> {% csrf_token %} {% render_honeypot_field %} {% form.as_p %}</form>編寫裝飾器
在common文件下新建decorators.py, 添加如下代碼。我們編寫了check_honeypot和honeypot_exempt兩個(gè)裝飾器,前者給需要對(duì)honeypot字段進(jìn)行驗(yàn)證的視圖函數(shù)使用,后者給不需要對(duì)honeypot字段進(jìn)行驗(yàn)證的視圖函數(shù)使用。
#common/decorators.py
from functools import wrapsfrom django.conf import settingsfrom django.http import HttpResponseBadRequest, HttpResponseForbidden, HttpResponseRedirectfrom django.template.loader import render_to_stringfrom django.contrib.auth.decorators import user_passes_testdef honeypot_equals(val): '''Default verifier used if HONEYPOT_VERIFIER is not specified.Ensures val == HONEYPOT_VALUE or HONEYPOT_VALUE() if it’s a callable. ''' expected = getattr(settings, ’HONEYPOT_VALUE’, ’’) if callable(expected):expected = expected() return val == expecteddef verify_honeypot_value(request, field_name): '''Verify that request.POST[field_name] is a valid honeypot.Ensures that the field exists and passes verification according toHONEYPOT_VERIFIER. ''' verifier = getattr(settings, ’HONEYPOT_VERIFIER’, honeypot_equals) if request.method == ’POST’:field = field_name or settings.HONEYPOT_FIELD_NAMEif field not in request.POST or not verifier(request.POST[field]): response = render_to_string(’common/snippets/honeypot_error.html’, {’fieldname’: field}) return HttpResponseBadRequest(response)def check_honeypot(func=None, field_name=None): '''Check request.POST for valid honeypot field.Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME ifnot specified. ''' # hack to reverse arguments if called with str param if isinstance(func, str):func, field_name = field_name, func def wrapper(func):@wraps(func)def inner(request, *args, **kwargs): response = verify_honeypot_value(request, field_name) if response:return response else:return func(request, *args, **kwargs)return inner if func is None:def decorator(func): return wrapper(func)return decorator return wrapper(func)def honeypot_exempt(func): '''Mark view as exempt from honeypot validation ''' # borrowing liberally from django’s csrf_exempt @wraps(func) def wrapper(*args, **kwargs):return func(*args, **kwargs) wrapper.honeypot_exempt = True return wrapper
上面代碼最重要的就是verify_honeypot_value函數(shù)了。如果用戶通過POST方式提交的表單里沒有honeypot字段或該字段的值不等于settings.py中的默認(rèn)值,則驗(yàn)證失敗并返回如下錯(cuò)誤:
# common/snippets/honeypot_error.html
<!DOCTYPE html><html lang='en'> <body> <h1>400 Bad POST Request</h1> <p>We have detected a suspicious request. Your request is aborted.</p> </body></html>
定義好裝飾器后,我們對(duì)需要處理POST表單的視圖函數(shù)加上@check_honeypot就行了,是不是很簡(jiǎn)單?
from common.decorators import check_honeypot@check_honeypotdef signup(request): if request.method == 'POST':form = SignUpForm(request.POST)if form.is_valid(): user = form.save() login(request, user) return HttpResponseRedirect(reverse(’users:profile’)) else:form = SignUpForm() return render(request, 'users/signup.html', {'form': form, })參考
本文核心代碼參考了James Sturk的Django-honeypot項(xiàng)目。原項(xiàng)目地址如下所示:
https://github.com/jamesturk/django-honeypot/
以上就是Django給表單添加honeypot驗(yàn)證增加安全性的詳細(xì)內(nèi)容,更多關(guān)于Django 添加honeypot驗(yàn)證的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. PHP函數(shù)原理理解詳談2. ASP中常用的22個(gè)FSO文件操作函數(shù)整理3. Vue+elementUI下拉框自定義顏色選擇器方式4. React+umi+typeScript創(chuàng)建項(xiàng)目的過程5. SharePoint Server 2019新特性介紹6. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究7. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析8. ASP的Global.asa文件技巧用法9. ASP中if語句、select 、while循環(huán)的使用方法10. html清除浮動(dòng)的6種方法示例
