Javascript XSS预防 [英] Javascript XSS Prevention

查看:98
本文介绍了Javascript XSS预防的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个Node.js项目用于清理数据,还有一个用于JavaScript的OWASP库,用于处理清理过程以防止XSS.

There is a Node.js project that sanitizes data and there is an OWASP library for JavaScript that handles sanitization to prevent XSS.

我一直在对这些库进行基准测试,它们非常密集,甚至可能是一个过大的杀伤力,我的应用程序不需要任何动态HTML(由用户,bbtags提交,甚至根本不需要,都不需要),所以为什么不这样做呢? :

I have been benchmarking these libraries, and they are pretty intensive and maybe an overkill, my application does not need any dynamic HTML (submitted by users, bbtags or what ever, not required at all) so why not do it like this:

  1. 禁用"<"和">"字符,请勿替换它们或其他任何字符,只需禁用它们,如果用户提交了这些字符,则向他们发出警告,指出它们已被禁用(客户端和服务器端)验证)
  2. & => &amp;
  3. " => &quot;
  4. ' => &#x27;
  5. / => /
  6. 编码提交的URL(获取参数等)
  7. 涵盖了基于DOM的XSS,因为我的应用程序使用HTML5 PushState,并且后端与前端完全隔离.
  1. Disable "<" and ">" characters, don't replace them or anything, just disable them, if the user submits these, give them a warning that these are disabled (client- and server-side validation)
  2. & => &amp;
  3. " => &quot;
  4. ' => &#x27;
  5. / => /
  6. Encode submitted URLs (GET parameters etc.)
  7. DOM based XSS is covered since my application uses HTML5 PushState and the backend is fully separated from the frontend.

这足以保护自己,就像我说的那样,我的应用程序不需要用户提交的任何HTML,因此我完全不需要<>标记.

Would this be enough to protect myself, as I said, my application does not require any HTML submitted by users, so I don't need the < and > tags at all.

感谢所有反馈,这就是我现在所使用的:

Thanks for all the feedback, this is what I use right now:

var pattern = /<(.*)>/;

function hasHtmlTags(string) {
    return pattern.test(string);
};

if (hasHtmlTags(userData)) {
    // Do something?
} else {
    // Create entity.
}

因此用户仍然可以使用其表情符号:<等等,并且仅当<的组合时才触发该函数.和>被找到.因此,无需昂贵的正则表达式等,只需禁用<和>结合起来,我们应该没事.

So users can still use their emoticons :< and such, and the function only gets triggered if a combination of < and > is found. So no expensive regular expressions and such, just disable < and > in combination and we should be fine.

推荐答案

这是一个通用的编码过程:

Here is a general encode procedure:

var lt = /</g, 
    gt = />/g, 
    ap = /'/g, 
    ic = /"/g;
value = value.toString().replace(lt, "&lt;").replace(gt, "&gt;").replace(ap, "&#39;").replace(ic, "&#34;");

如果您的用户未向服务器提交任何内容,则您甚至不需要以上内容.如果用户提交并且您正在使用用户输入,则以上内容应该是安全的.只要是<"和'>'已全局清除,并且括号也很不错.

If your user doesn't submit anything to your server you don't even need the above. If the user submits and you are using the user input then the above should be safe. As long as the '<' and '>' are globally sanitized and the parenthesis also are you are good to go.

这篇关于Javascript XSS预防的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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