是否可以转义单引号以在 html 元素中注入 javascript?

发布于 2025-01-17 12:46:17 字数 738 浏览 3 评论 0原文

比较 2 个 html 元素

const htmlElement = `<p myAttr=${attackerValue}>Appended element!</p>`;

在这里注入 javascript 很容易,我可以使用

< 的 attackerValue /code>

但是,如果 htmlElement 中有单引号包裹 attackerValue ,是否仍然可以注入 javascript?

const htmlElement = `<p myAttr='${attackerValue}'>Appended element!</p>`;

Codesandbox: https://codesandbox.io/s/young -hill-4nww5k?file=/src/index.js

编辑:找到我的答案,我可以简单地使用输入转义字符串单引号,例如'

Comparing 2 html elements

const htmlElement = `<p myAttr=${attackerValue}>Appended element!</p>`;

It is easy to inject javascript here, I can use an attackerValue of </p><script>alert("injected JS") </script>

However, if the there are single quotes wrapping attackerValue in the htmlElement, is it still possible to inject javascript?

const htmlElement = `<p myAttr='${attackerValue}'>Appended element!</p>`;

Codesandbox: https://codesandbox.io/s/young-hill-4nww5k?file=/src/index.js

Edit: Found my answer, I can simply escape the string single quote by using an input such as '</p><script>alert("injected JS") </script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静水深流 2025-01-24 12:46:17

对于前端代码,是否可能无关紧要。 &lt; script/&gt;标签通过inninhtml插入的标签未执行:

<html>
    Example:
    <script>
        const injection = '<script>alert("hello")<\/script>';
        document.body.innerHTML += ` this is a test ${injection}`;

        // You will never see the "hello" alert because
        // browser ignores your script tag.
    </script>
</html>

浏览器忽略所有脚本标签插入到DOM中的所有脚本标签,以防止注射攻击。

可以通过document.write()

<html>
    Example: 
    <script>
        const injection = '<script>alert("hello")<\/script>';
        document.write(` this is a test ${injection}`);

        // You will see the "hello" alert!
    </script>
</html>

简单的解决方案注入脚本:不要使用document.write.write()

For front-end code it does not matter if it is possible. <script/> tags inserted via innerHTML are not executed:

<html>
    Example:
    <script>
        const injection = '<script>alert("hello")<\/script>';
        document.body.innerHTML += ` this is a test ${injection}`;

        // You will never see the "hello" alert because
        // browser ignores your script tag.
    </script>
</html>

The browser ignores all script tags inserted into the DOM for exactly this reason - to prevent an injection attack.

It is possible to inject scripts via document.write():

<html>
    Example: 
    <script>
        const injection = '<script>alert("hello")<\/script>';
        document.write(` this is a test ${injection}`);

        // You will see the "hello" alert!
    </script>
</html>

The solution to that is simple: don't use document.write().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文