简体   繁体   English

文本框的 Javascript 注入攻击预防

[英]Javascript injection attack prevention for textboxes

say I have a textBox and a property to get and set its value:说我有一个 textBox 和一个属性来获取和设置它的值:

public SomeText
{
   get { return HttpUtility.HtmlEncode(textBox.Text); }
   set { textBox.Text = HttpUtility.HtmlEncode(value); }
}

I have used HtmlEncode to prevent Javascript injection attacks.我使用 HtmlEncode 来防止 Javascript 注入攻击。 After thinking about it though I'm thinking I only need the HtmlEncode on the getter.在考虑之后,虽然我认为我只需要 getter 上的 HtmlEncode。 The setter is only used by the system and can not be accessed by an external user. setter 仅供系统使用,外部用户无法访问。

Is this correct?这样对吗?

A couple points;几点;

First:第一的:

You should really only encode values when you display them, and not any other time.你真的应该只在你显示它们时编码值,而不是任何其他时间。 By encoding them as you get the value from the box, and also when you paste in, you could end up with a real mess, that will just get worse and worse any time someone edits the values.通过在从框中获取值以及粘贴时对它们进行编码,最终可能会弄得一团糟,只要有人编辑这些值,情况就会变得越来越糟。 You should not encode the values (against HTML/Javascript injection - you DO need to protect against SQL injection, of course) upon saving to the database in most cases, especially if that value could later be edited.在大多数情况下,在保存到数据库时,您不应该对值进行编码(防止 HTML/Javascript 注入 - 当然,您确实需要防止 SQL 注入),尤其是在以后可以编辑该值的情况下。 In such a case, you actually need to decode it upon loading it back... not encode it again.在这种情况下,您实际上需要在加载回时对其进行解码……而不是再次对其进行编码 But again;但是再次; it's much simpler only to encode when displaying it (which includes displaying for editing, btw)仅在显示时进行编码要简单得多(包括显示以供编辑,顺便说一句)

Second:第二:

HtmlEncode protects against injecting HTML - which can include a <script> block which would run Javascript, true. HtmlEncode防止注入 HTML - 它可以包含一个<script>块,它会运行 Javascript,真的。 But this also protects against generally malicious HTML that has nothing to do with Javascript.但这也可以防止与 Javascript 无关的恶意 HTML。 But protecting against Javascript injection is almost a different thing;但是防止 Javascript 注入几乎是另一回事; that is, if you might ever display something entered by the user in, say, a javascript alert('%VARIABLE');也就是说,如果您可能曾经在 javascript alert('%VARIABLE');显示用户输入的内容alert('%VARIABLE'); you have to do a totally different kind of encoding there than what you are doing.你必须在那里做一种与你正在做的完全不同的编码。

Yes.是的。 You only need to encode strings that you have accepted from the users and you have to show inside your pages.您只需要对您从用户那里接受的字符串进行编码,并且必须显示在您的页面中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM