Stay Hungry,Stay Foolish!

textarea与XSS攻击

textarea用法

一般是用来接收用户输入,用于提交到服务器端,例如 网站的评论框。

如果此框也用于显示服务器端回传的内容,则有如下两种用法

法1 后台直接插入

<textarea><%=serverString;%></textarea>

法2 使用JS DOM接口赋值

textareaDom.value = "<%=serverString;%>"

 

textarea content特性

即法1特性, 即使将html代码段插入textarea, html代码段不会执行, 仅仅将其作为普通文本显示。

<html>
<head>

</head>
<body>
<textarea>

<script>alert("aa")</script>
<div>bbb</div>

</textarea>
</body>
</html>

将HTML代码贴到此网站的编辑框中,点击运行看效果。

http://www.tool.la/WebEditor02/

 

textarea 仍然可遭受XSS攻击

不同于其他标签,例如div, 其内容内嵌script脚本,会被执行,

尽管textarea不会执行script,其仍然可遭受XSS攻击。

在插入textarea内容时候,提前关闭标签,然后输出script脚本,如下

<html>
<head> 

</head> 
<body>
<textarea>

</
textarea><script>alert("aa")</script>

</textarea> </body> </html>

 

HTML规范要求,内容中不能有闭合标签。

http://www.w3.org/TR/html-markup/syntax.html#contents

An end tag that is not contained within the same contents as its start tag is said to be a misnested tag.

规范上要求的 textarea content 内容为 replaceable character data

http://www.w3.org/TR/html-markup/textarea.html

这种字符类型,要求内容中不能有标签闭合的字符:

http://www.w3.org/TR/html-markup/syntax.html#replaceable-character-data

must not contain any occurrences of the string "</" followed by characters that are a case-insensitive match for the tag name of the element containing the replaceable character data (for example, "</title" or "</textarea"), followed by a space character, ">", or "/".

 

 

textarea 防XSS攻击方法

对于法1 需要实施HTML转码,将</sss>转换为 &lt;

<textarea><%=encodeHTML(serverString);%></textarea>

对于法2 需要实施JS转码

textareaDom.value = "<%=encodeJS(serverString);%>"

 

如果您的后台不支持转码,可以使用法2+ajax获取方式:

1、 将显示的数据存储为后台文件(logstr.txt), 例如文件内容为,含有攻击脚本,使用法1会构成XSS攻击:

        </textarea>
            <div>aa</div>
            <script>alert("aa")</script>

2、使用ajax获取此文件内容, 后调用法2接口给textarea赋值。

<html>
<head>
    <script src="./jquery.js"></script>
</head>
<body>
        <textarea id="test">
        </textarea>
        <script type="text/javascript">
           
            $.get("./logstr.txt", {Action:"get",Name:"lulu"}, function (data, textStatus){
                document.getElementById("test").value = data;
            });
           
        </script>
</body>
</html>

 

posted @ 2015-03-22 08:45  lightsong  阅读(3929)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel