標籤:
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>轉換為 <;
<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>
textarea與XSS攻擊