【问题标题】:Prevent html Injections with Javascript/Typescript使用 Javascript/Typescript 防止 html 注入
【发布时间】:2019-12-15 08:23:31
【问题描述】:

所以我有一个简单的应用程序,用户可以在其中将 URL 插入 iframe 窗口。问题是这允许 html 注入,这会破坏显示。

有没有一种简单的方法可以防止这种情况发生?像正则表达式转义函数等?

iframe 窗口的 TS/JS 代码:

public renderPlot(): void {
    let ht: string = '';

    let url: string = this.configPBg[EConfigPKeys.IFrameAddress];

    if (url == undefined || url.length === 0) {
        this.renderWarningMessage('No valid address configured');
        return;
    }

    // auto stream with url like this : https://www.youtube.com/embed/jdnhfg?&autoplay=1&mute=1
    ht += '<iframe width="' + this.chartWindowSize.width + '" height="' + this.chartWindowSize.plotHeight + '" ';
    ht += 'src="' + url + '" ';
    ht += 'frameborder="0" ';
    ht += '>';
    ht += '</iframe>';

我尝试添加此内容,但未能捕捉到任何内容:

url.replace(/</g, "&lt;").replace(/>/g, "&gt;");

URL 输入表单如下所示:

【问题讨论】:

  • 除了使用the sandbox attribute,您可能不想从字符串构建您的 iframe 内容,而是使用 DOM 操作函数,在其中创建一个 iframe 元素,然后使用 DOM 为其分配内容尽可能多地构建功能和属性分配?
  • 检查 DOMPurify 库以清理元素 github.com/cure53/DOMPurify

标签: javascript html regex typescript code-injection


【解决方案1】:

我会从 URL 变量中删除 all html:

url = url.replace( /<(?:(?:(?:(script|style|object|embed|applet|noframes|noscript|noembed)(?:\s+(?:"[\S\s]*?"|'[\S\s]*?'|(?:(?!\/>)[^>])?)+)?\s*>)[\S\s]*?<\/\1\s*(?=>))|(?:\/?[\w:]+\s*\/?)|(?:[\w:]+\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+\s*\/?)|\?[\S\s]*?\?|(?:!(?:(?:DOCTYPE[\S\s]*?)|(?:\[CDATA\[[\S\s]*?\]\])|(?:--[\S\s]*?--)|(?:ATTLIST[\S\s]*?)|(?:ENTITY[\S\s]*?)|(?:ELEMENT[\S\s]*?))))>/g,
             "");

https://regex101.com/r/qwEyED/1

然后对 URL 进行验证:

var patURL = /^(?!mailto:)(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/[^\s]*)?$/;

var res = patURL.test( url );
if ( res != true )
    // bad url

【讨论】:

  • 谢谢,这几乎可以工作,但是当我在 URL 字段中输入 "&lt;/span&gt; 时最终看起来像这样:link 如何告诉正则表达式在第一次出现字符 @ 时也匹配987654327@ 然后什么都不替换?
  • Thanks, this almost works but ends up looking like this when I enter "&lt;/span&gt; into the URL 好吧,伙计,这就是为什么我把这个链接放在我的答案regex101.com/r/qwEyED/1 这样没有人能回来说出我刚才引用你的话。很酷吧?
  • 对不起,我不明白。我遇到的问题是我在用户输入字段开头输入的" 字符会关闭html 中的&lt;input type="text" value=",这会导致程序出现故障。 (参见上面链接图片中的示例)
  • @dragonfury2 - 你不明白,html 将被 STRIPPED 你输入的 ***。你的问题是关于什么,双引号?
猜你喜欢
  • 2017-09-05
  • 2014-01-18
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 2011-04-12
  • 2016-11-16
  • 2015-09-27
  • 1970-01-01
相关资源
最近更新 更多