gpt4 book ai didi

ruby-on-rails - 处理用户输入的代码 - 安全

转载 作者:数据小太阳 更新时间:2023-10-29 07:33:35 26 4
gpt4 key购买 nike

我的应用程序允许用户输入任何语言(python、c、java、ruby 等)的代码,我使用 PrismJS作为语法荧光笔。 Rails 是否处理 xss 和注入(inject),或者我是否需要进一步清理/验证代码?

安全处理用户输入代码(如 stackoverflow)的正确方法是什么?

表单输入

<div class="form-group">
<label>Code Snippet</label>
<%= f.text_area :body, class: "end-field form-control", placeholder: "", rows: 8 %>
</div>

查看

<pre><code class="language-<%= snippet.language %> line-numbers"><%= snippet.body %></code></pre>

目前没有进行任何 sanitizer 或验证。

输出:

enter image description here

最佳答案

OWASP (XXS prevention cheat sheet, Rule #1)建议您使用以下替换来清理两个标签之间的代码:

 & --> &amp;
< --> &lt;
> --> &gt;
" --> &quot;
' --> &#x27; &apos; not recommended because its not in the HTML spec (See: section 24.4.1) &apos; is in the XML and XHTML specs.
/ --> &#x2F; forward slash is included as it helps end an HTML entity

这是他们的说法:

Rule #1 is for when you want to put untrusted data directly into the HTML body somewhere. This includes inside normal tags like div, p, b, td, etc. Most web frameworks have a method for HTML escaping for the characters detailed below. However, this is absolutely not sufficient for other HTML contexts. You need to implement the other rules detailed here as well.

`<body>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</body>`   
`<div>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</div>`

any other normal HTML elements

Escape the following characters with HTML entity encoding to prevent switching into any execution context, such as script, style, or event handlers. Using hex entities is recommended in the spec. In addition to the 5 characters significant in XML (&, <, >, ", '), the forward slash is included as it helps to end an HTML entity.

& --> &amp;
< --> &lt;
> --> &gt;
" --> &quot;
' --> &#x27; &apos; not recommended because its not in the HTML spec (See: section 24.4.1) &apos; is in the XML and XHTML specs.
/ --> &#x2F; forward slash is included as it helps end an HTML entity

See the ESAPI reference implementation of HTML entity escaping and unescaping.

String safe = ESAPI.encoder().encodeForHTML( request.getParameter("input" ) );

我的示例实现(并非绝对安全)

def sanitize_inside_tags(text)
{"&"=>"amp",
"<"=>"lt",
">"=>"gt",
"\""=>"quot",
"'"=>"#x27",
"/"=>"#x2F"}.each do |char,replacement|
text = text.gsub(char,"&#{replacement};")
end
return text
end

Rails 清理方法

这可能是您的最佳选择,因为它不仅是一个使用良好且经过测试的卫生库,而且还允许使用一些标签,例如 <b>和 friend ,以便您的用户实际上可以安全地使用一些 html 标记。

在回答您的问题时,是的,您可以安全地使用 rails sanitation 库,这可能是适合您情况的正确选择。

如果您想去除所有标签或允许更少的标签,您可以查看自定义 here .

语法高亮

正如@ImranAli 在他的评论中所建议的那样,查看 this post并尝试查看列出的所有库。

关于ruby-on-rails - 处理用户输入的代码 - 安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37334304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com