textarea與XSS攻擊

textarea用法

通常是用來接收用戶輸入,用於提交到服務器端,例如 網站的評論框。javascript

若是此框也用於顯示服務器端回傳的內容,則有以下兩種用法html

法1 後臺直接插入java

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

法2 使用JS DOM接口賦值ajax

textareaDom.value = "<%=serverString;%>"服務器

 

textarea content特性

即法1特性, 即便將html代碼段插入textarea, html代碼段不會執行, 僅僅將其做爲普通文本顯示。網站

<html>
<head>

</head>
<body>
<textarea>ui

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

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

將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獲取方式:

一、 將顯示的數據存儲爲後臺文件(logstr.txt), 例如文件內容爲,含有攻擊腳本,使用法1會構成XSS攻擊:

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

二、使用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>
相關文章
相關標籤/搜索