Day46 of learning python --xss攻击

一、XSS攻击全称跨站脚本攻击

-慎用 salf 和 mark_safe
-非要用,一定要过滤关键字

在Django中默认把提交到后台的字符串渲染在html时,默认是字符串。当需要把提交到前端的字符串进行渲染时,要在后端进行字符串过滤,再在前端用safe或者后端使用mark_safe上标记该字符串为安全

模拟一个评论系统

urls.py

from django.contrib import admin
from django.urls import path,re_path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^comment.html$',views.comment),  # 输入评论
    re_path('^index.html$',views.index),   # 显示评论
    re_path('^test.html$', views.test),     # 测试
]

views.py

from django.shortcuts import render

# Create your views here.
msg = []   # 纪录评论的内容
def comment(request):
    if request.method == 'GET':
        return render(request,'comment.html')
    else:
        v = request.POST.get('comment')
        if "script" in v:   # 判断是否有敏感的字符串
            return render(request,'comment.html',{'error':'小兔崽子还想黑我'})
        else:
            msg.append(v)
            return render(request,'comment.html')


def index(request):
    return render(request,'index.html',{'msg':msg})

def test(request):
    from django.utils.safestring import mark_safe
    temp = "<a href='http://www.baidu.com'>百度</a>"
    newtemp = mark_safe(temp)
    return render(request,'test.html',{'temp':newtemp})  # 在前端显示时,就会渲染成一个a标签

commnet.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>comment</title>
</head>
<body>
<form action="/comment.html" method="post">
    <input type="text" name="comment">
    <input type="submit" value="提交">{{ error }}
</form>

</body>
</html>

index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>index</title>

</head>
<body>
<h1>评论</h1>
{% for row in msg %}
    <p>{{ row | safe}}</p>
{% endfor %}

</body>
</html>

test.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>test</title>

</head>
<body>

{{ temp }}
</body>
</html>

在comment.html添加的字符串是:<script>alert("你好帅")</script>

posted on 2019-02-20 18:32  smile大豆芽  阅读(228)  评论(0)    收藏  举报