在进行网页开发的时候,可能会需要将用户输入的数据显示在 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>');"));