脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Django给表单添加honeypot验证增加安全性

Django给表单添加honeypot验证增加安全性

2021-10-25 10:15大江狗 Python

这篇文章主要介绍了Django给表单添加honeypot验证增加安全性的方法,帮助大家更好的理解和学习使用Django框架,感兴趣的朋友可以了解下

如果你的网站中允许匿名用户通过post方式提交表单, 比如用户注册表, 评论表或者留下用户联系方式的表单,你一定要防止机器人或爬虫程序恶意提交大量的垃圾数据到你的数据库中。这种情况不是可能会发生,而是一定会发生。一种解决这种问题的方式就是在表单中加入人机交互验证码(captcha), 另一种方式就是在表单中加入honeypot隐藏字段,然后在视图中对隐藏字段的值进行验证。两种验证方式的目的都是一样,防止机器人或程序通过伪装成人来提交数据。今天我们就来详细介绍下如何在表单中添加honeypot增加安全性。

honeypot的工作原理

honeypot又名蜜罐,其实本质上是种陷阱。我们在表单中故意通过css隐藏一些字段, 这些字段一般人是不可见的。然而机器人或程序会以为这些字段也是必需的字段(required), 所以会补全后提交表单,这就中了我们的陷阱。在视图中我们可以通过装饰器对用户提交的表单数据进行判断,来验证表单的合法性。比如honeypot字段本来应该为空的,现在居然有内容了,显然这是机器人或程序提交的数据,我们可以拒绝其请求。

django中如何实现表单honeypot验证?

django表单中添加honeypot,一共分两步:

1. 编写模板标签(templatetags),在包含模板的表单中生成honeypot字段。

2. 编写装饰器(decorators.py), 对post请求发送来的表单数据进行验证。

由于honeypot的功能所有app都可以用到,我们创建了一个叫common的app。整个项目的目录结构如下所示。只有标蓝色的4个文件,是与honeypot相关的。

Django给表单添加honeypot验证增加安全性

编写模板标签

我们在common目录下新建templatetags目录(包含一个空的__init__.py),然后在新建common_tags_filters.py, 添加如下代码。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter
 
 
register = 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}

我们现在来看下上面这段代码如何工作的。我们创建了一个名为render_honeypot_field的模板标签,用于在模板中生成honeypot字段。honeypot字段名是settings.py里honeypot_field_name,如果没有此项设置,默认值为name1。honeypot字段的默认值是honeypot_value, 如果没有此项设置,默认值为空字符串''。然后这个函数将fieldname和value传递给如下模板片段。

# common/snippets/honeypot_field.html

?
1
2
3
4
<div class="form-control" style="display: none;">
        <label><input type="text" name="{{ fieldname }}" value="{{ value }}" />
    </label>
</div>

在django模板的表单中生成honeypot字段只需按如下操作:

?
1
2
3
4
5
6
7
8
{% 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两个装饰器,前者给需要对honeypot字段进行验证的视图函数使用,后者给不需要对honeypot字段进行验证的视图函数使用。

#common/decorators.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from functools import wraps
from django.conf import settings
from django.http import httpresponsebadrequest, httpresponseforbidden, httpresponseredirect
from django.template.loader import render_to_string
from django.contrib.auth.decorators import user_passes_test
 
 
def 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 == expected
 
 
def 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 to
        honeypot_verifier.
    """
    verifier = getattr(settings, 'honeypot_verifier', honeypot_equals)
    if request.method == 'post':
        field = field_name or settings.honeypot_field_name
        if 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 if
        not 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函数了。如果用户通过post方式提交的表单里没有honeypot字段或该字段的值不等于settings.py中的默认值,则验证失败并返回如下错误:

# common/snippets/honeypot_error.html

?
1
2
3
4
5
6
7
<!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>

定义好装饰器后,我们对需要处理post表单的视图函数加上@check_honeypot就行了,是不是很简单?

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from common.decorators import check_honeypot
 
 
@check_honeypot
def 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项目。原项目地址如下所示:

https://github.com/jamesturk/django-honeypot/

以上就是django给表单添加honeypot验证增加安全性的详细内容,更多关于django 添加honeypot验证的资料请关注服务器之家其它相关文章!

原文链接:https://mp.weixin.qq.com/s/tv-McIa4txj2VOg-mzJ5wg

延伸 · 阅读

精彩推荐