在進行網頁開發的時候,可能會需要將使用者輸入的資料顯示在 HTML 網頁上,此時的網頁就會暴露在 XSS (Cross-Site Scripting)攻擊的危險下。如果網頁不做任何檢查,將使用者輸入的資料嵌入至網頁中的話,輸入資料中的 HTML 語法就會直接影響到網頁,就會使得網頁爛掉或是藏有惡意的連結和腳本。為了讓使用者輸入的資料不會被當作是一般的 HTML 語法,需要將特定的保留字元進行跳脫處理,像是 < 要跳脫成 &lt;。如此一來,就算使用者輸入 <script>,在網頁上就會直接顯示 <script>,而不會有 <script> 標籤的功能。

這雖然是蠻基本的功能,但是在 crates.io 上卻沒有好用的套件,只好自己實作一個了。

HTML Escape

「HTML Escape」是筆者開發的套件,可以快速地編碼(跳脫)或是解碼(反跳脫)HTML 的特殊字元。

Crates.io

Cargo.toml

html-escape = "*"

使用方法

編碼

html_escape 這個 crate 提供了一些 encode_ 函數,可以針對不同的使用情境編碼 HTML 文字。

例如,要在 <foo> 標籤和 </foo> 之間插入文字的話,可以使用 encode_text 函數來跳脫文字中的 &、< 和 > 字元。

assert_eq!("a &gt; b &amp;&amp; a &lt; c", html_escape::encode_text("a > b && a < c"));

以 _to_writer、_to_vec 或 _to_string 為名稱後綴的函數可以方便用來產生 HTML。

let mut html = String::from("<input value=");
assert_eq!("Hello&#x20;world&#x21;", html_escape::encode_unquoted_attribute_to_string("Hello world!", &mut html));
html.push_str(" placeholder=\"");
assert_eq!("The default value is &quot;Hello world!&quot;.", html_escape::encode_double_quoted_attribute_to_string("The default value is \"Hello world!\".", &mut html));
html.push_str("\"/><script>alert('");
assert_eq!(r"<script>\'s end tag is <\/script>", html_escape::encode_script_single_quoted_text_to_string("<script>'s end tag is </script>", &mut html));
html.push_str("');</script>");

assert_eq!("<input value=Hello&#x20;world&#x21; placeholder=\"The default value is &quot;Hello world!&quot;.\"/><script>alert(\'<script>\\\'s end tag is <\\/script>\');</script>", html);
解碼
assert_eq!("Hello world!", html_escape::decode_html_entities("Hello&#x20;world&#x21;"));
assert_eq!("alert('<script></script>');", html_escape::decode_script(r"alert('<script><\/script>');"));