面试-XSS攻击

xss攻击:----->web注入

定义:

  xss跨站脚本攻击(Cross site script,简称xss)是一种“HTML注入”,由于攻击的脚本多数时候是跨域的,所以称之为“跨域脚本”。
  我们常常听到“注入”(Injection),如SQL注入,那么到底“注入”是什么?注入本质上就是把输入的数据变成可执行的程序语句。SQL注入是如此,XSS也如此,只不过XSS一般注入的是恶意的脚本代码,这些脚本代码可以用来获取合法用户的数据,如Cookie信息。
  PS: 把用户输入的数据以安全的形式显示,那只能是在页面上显示字符串。
    django框架中给数据标记安全方式显示(但这种操作是不安全的!):
      - 模版页面上对拿到的数据后写上safe. ----> {{XXXX|safe}}
      - 在后台导入模块:from django.utils.safestring import mark_safe
        把要传给页面的字符串做安全处理 ----> s = mark_safe(s)

 如果网站存在允许攻击者将任意脚本馈送到Web应用程序中的漏洞,
则攻击者可以利用该漏洞并在用户的Web浏览器上执行恶意脚本
1、攻击者发送带有虚假链接的电子邮件 ,用户访问网站时没有意识到这个陷阱
2、用户点击链接,在不知不觉中发送脚本嵌入字符串
3、应用程序输出脚本嵌入的网页
4、脚本在用户的web浏览器上执行
5、目标信息(cookie)泄露

实施XSS攻击需要具备两个条件:

  一、需要向web页面注入恶意代码;

  二、这些恶意代码能够被浏览器成功的执行。

解决办法:

  1、一种方法是在表单提交或者url参数传递前,对需要的参数进行过滤。
  2、在后台对从数据库获取的字符串数据进行过滤,判断关键字。
  3、设置安全机制。
  django框架:内部机制默认阻止了。它会判定传入的字符串是不安全的,就不会渲染而以字符串的形式显示。如果手贱写了safe,那就危险了,若想使用safe,那就必须在后台对要渲染的字符串做过滤了。所以在开发的时候,一定要慎用安全机制。尤其是对用户可以提交的并能渲染的内容!!!

- 示例:

复制代码
comment.html :
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form method="POST" action="/comment/">
        <h4>评论</h4>
        <input type="text" name="content"/>
        <input type="submit" value="提交" />{{ error }}
    </form>
</body>
</html>
comment.html :评论提交页面
复制代码
复制代码
index.html 评论显示页面:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>评论内容</h1>
    {% for item in msg %}
        <div>{{ item|safe }}</div>
    {% endfor %}
</body>
</html>
index.html 评论显示页面:
复制代码
复制代码
from django.shortcuts import render
msg = []
def comment(request):
        if request.method == "GET":
        return render(request,'comment.html')
    else:
        v = request.POST.get('content')
        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}
views.py 后台处理
复制代码
from django.shortcuts import render
msg = []
def comment(request):
        if request.method == "GET":
        return render(request,'comment.html')
    else:
        v = request.POST.get('content')
        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}
原文地址:https://www.cnblogs.com/fan-1994716/p/11905114.html