构建输入文本区域以允许HTML,但防止安全/脚本攻击 [英] Building an input text area to allow HTML but prevent security / script attacks

查看:128
本文介绍了构建输入文本区域以允许HTML,但防止安全/脚本攻击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

平台:ASP.NET 4.0 MVC 4 C#jQuery

Platform: ASP.NET 4.0 MVC 4 C# jQuery

这就是我想要做的.

我正在为我的产品建立一个简单的论坛.我想给用户一个文本区域来输入他们的帖子或评论.

I'm building a simple forum for my product. I want to give users a text area to enter their posts or comments.

  1. 我希望允许使用基本文本格式设置HTML和链接-例如p,a,b,i
  2. 不需要任何其他html样式-即div,span等,等等.
  3. 不需要任何脚本访问权限

有一个聪明的方法可以做到这一点吗?例如,我可以允许不安全的文本并在服务器端对其进行检查,但我怀疑我是否能够正确清理它并可能会打开安全漏洞.

Is there a clever way to do this? I could, for e.g., allow unsafe text and examine it on the server side but I doubt I'd be able to clean it up correctly and might open security holes.

最好避免使用重型插件.

Preferably want to avoid heavy duty plugins.

谢谢!

(PS-我最糟糕的后退是我只允许使用安全文本,即保持ASP.NET安全性,然后对链接使用特殊的标记-例如[link] [b] [i])

(PS - my worst fallback is that I allow safe text only, i.e. keep the ASP.NET security on, and then use a special markup for links - like [link] [b] [i])

推荐答案

无论使用哪种方法,都需要假设输入该字段的所有内容都是恶意的,即不信任任何数据.

No matter what approach you use, you need to assume everything entered into the field is malicious, i.e. don't trust any data.

对于JavaScript/jQuery中的任何客户端验证,我都不会太在意.这会很复杂,只需要在服务器端重做即可.

I wouldn't bother too much with any client validation in JavaScript/jQuery. It'll be complex and only need to be redone server side.

您要采用白名单方法的服务器端,即,如果不在列表中,则该列表无效.您将无法使用XML处理器,因为用户的文本可能不会生成有效的XML,相反,您可能希望使用正则表达式.

Server side you want to take a whitelist approach, i.e. if it's not on the list, it's invalid. You wouldn't be able to use a XML processor because the user's text may not result in valid XML, instead you'd probably want to use a regular expression.

我将定义一组有效的标签(您说过p,a,b和i,但我对最后两个标签感到厌倦,因为您几乎永远不会在野生" html中获得它们),我然后将定义这些标签是否以及哪些属性有效.我猜您至少要在a上使用href.

I would define a set of tags that are valid (you've said p, a, b and i but I would be weary of the last two as you'd almost never get them in 'wild' html), I would then define if and which attributes are valid for these tags. I'm guessing you'd want at the very least a href on the a.

您可以删除标签中不匹配的任何文本...我的正则表达式技能不是很好,但是这似乎找到了您想要保留的所有标签,需要将其反转.

You could strip any text within tags that doesn't match... my regex skills aren't great, but this appears to find all the tags you want to keep, it needs to be inverted.

\<a\shref\=".[^\"]*\"\>|\</?[abip]\s?\>

这篇关于构建输入文本区域以允许HTML,但防止安全/脚本攻击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆