简体   繁体   English

Node、Express 和 MongoDB 中的 HTML 注入。 (EJS 模板引擎)

[英]HTML injection in Node, Express and MongoDB. (EJS templating engine)

I am new to web development.我是网络开发的新手。 I know very little about security.我对安全知之甚少。 I have made a forum in which users can choose to converse anonymously.我创建了一个论坛,用户可以在其中选择匿名交谈。 So am not registering or asking users to login.所以我不注册或要求用户登录。

I have a huge flaw in my application.The moment someone types HTML/CSS/JS into my input field, the changes get rendered onto the actual website.我的应用程序有一个巨大的缺陷。当有人在我的输入字段中输入 HTML/CSS/JS 时,更改就会呈现到实际网站上。 I have been brainstorming over this but am unable to find a solution to this problem.我一直在为此进行头脑风暴,但无法找到解决此问题的方法。

How can I detect whether a user is typing in HTML or CSS and how can I overcome this malpractice of the user.我如何检测用户是在输入 HTML 还是 CSS,以及如何克服用户的这种不当行为。 As the typed in content is saved into the database, it is rendered every time.由于输入的内容已保存到数据库中,因此每次都会呈现。 Please help guys!请帮助伙计们! Let the solutions pour in.让溶液倾泻而下。

Thank you in advance.先感谢您。

EJS already have built-in mechanism to protect against HTML injection. EJS 已经有内置机制来防止 HTML 注入。 The <%= tag escapes HTML. <%=标记转义 HTML。 For example:例如:

<% var x = '<div>HTML Injection!</div>' %>
<%= x %>

Will render something similar to:将呈现类似于:

&lt;HTML Injection!&gt;

So the output should be safe even though it will look like someone is typing code.因此,即使看起来有人在键入代码,输出也应该是安全的。

The only way HTML injection can work in EJS is if you deliberately allow it by using <%- instead of <%= or by redefining the escape option. HTML 注入可以在 EJS 中工作的唯一方法是,如果您故意使用<%-而不是<%=或通过重新定义escape选项来允许它。

If you really need to use <%- then EJS will stop protecting you from HTML injection and assume you know what you are doing.如果你真的需要使用<%-那么 EJS 将停止保护你免受 HTML 注入并假设你知道你在做什么。 In which case avoiding HTML injection becomes your responsibility.在这种情况下,避免 HTML 注入成为您的责任。 You can manually do what EJS does for you by replacing < with &lt;您可以通过将<替换为&lt;来手动执行 EJS 为您执行的操作&lt; and > with &gt;>&gt; or by deleting HTML tags completely from user input:或者通过从用户输入中完全删除 HTML 标签:

const some_input = req.query.some_data;

escaped_html_input = some_input.replace(/</g, '&lt;').replace(/>/g, '&gt;');

deleted_html_input = some_input.replace(/<.+?>/g, '');

save(escaped_html_input);

// or save(deleted_html_input);

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

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