【问题标题】:XSS Protection HTML EntitiesXSS 保护 HTML 实体
【发布时间】:2020-08-03 04:42:44
【问题描述】:

如果用于过滤用户输入,您认为这些功能足以防止 XSS 吗?我真的应该自己制作或使用 XSS 库吗?请给我建设性的批评。谢谢大家。

/**
 * Escape HTML string to prevent XSS.
 */
export const escapeHtml = (string: string): string => {
    if (isString(string)) {
        const entityMap = {
            "&": "&",
            "<": "&lt;",
            ">": "&gt;",
            '"': "&quot;"
        };
        return string.slice(0, string.length).replace(/[&<>"]/g, (s: string): string => entityMap[s]);
    }
    return string;
};

/**
 * Loop over Object to escape each of its value to prevent XSS.
 */
export const escapeHtmlQueryObject = (obj: { [string]: string }): { [string]: string } => {
    let result = obj;
    if (obj && isObject(obj)) {
        result = Object.keys(obj).reduce((res: { [string]: string }, key: string): {
            [string]: string
        } => {
            res[key] = escapeHtml(obj[key]);
            return res;
        }, {});
    } else if (process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "test") {
        console.error(`FilterXSSQueryObject can't process ${obj.toString()}`);
    }
    return result;
};

【问题讨论】:

标签: javascript html security xss


【解决方案1】:

this answer 相比,您可能还想转义单引号。

也就是说,如果您想确保您的代码是安全的,最好依赖一个经过安全专家实战测试的库。

人们不喜欢为小事加载库,但这是一件重要的小事,所以我不会介意。

不相关:您似乎正在使用Object.keys 以迂回的方式遍历对象的键以访问其值,但您也可以只使用Object.values

【讨论】:

  • 您好,感谢您的回复。如果我已经转义了大多数“危险”字符,您能否给我一个为什么也需要转义单引号的原因?谢谢。
  • 不知道,大概是由于字符串注入到使用单引号声明的字符串中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
相关资源
最近更新 更多