检查字符串是否包含正则表达式&没有js

Check if string contains a regex & no js

本文关键字:amp 没有 js 正则表达式 字符串 是否 包含 检查      更新时间:2023-09-26

我有一个字符串,我需要确保它只包含一个正则表达式,不包含javascript,因为我正在用这个字符串创建一个新脚本,所以javascript片段会有安全风险。

确切场景:

  1. mozilla插件中的JS通过HTTPrequest将配置加载为json(json包含{"something":"^(?:http|https)://(?:.*)"}
  2. JS创建了一个pac文件(代理配置脚本),该文件使用配置中的"something"regex

你知道如何在不破坏正则表达式的情况下转义字符串吗?

您可以使用正则表达式来拆分JavaScript正则表达式。

然后,您应该将正则表达式转换为一个在词汇上更简单的JavaScript子集,以避免/含义的所有非上下文无关的怪异之处,以及输入正则表达式中的任何不规则之处。

var REGEXP_PARTS = "(?:"
    // A regular character
    + "[^/'r'n'u2028'u2029''['''']"
    // An escaped character, charset reference or backreference
    + "|''''[^'r'n'u2028'u2029]"
    // A character set
    + "|''[(?!''])(?:[^'']'''']|''''[^'r'n'u2028'u2029])+'']"
    + ")";
var REGEXP_REGEXP = new RegExp(
    // A regex starts with a slash
    "^[/]"
    // It cannot be lexically ambiguous with a line or block comemnt
    + "(?![*/])"
    // Capture the body in group 1
    + "(" + REGEXP_PARTS + "+)"
    // The body is terminated by a slash
    + "[/]"
    // Capture the flags in group 2
    + "([gmi]{0,3})$");
 var match = myString.match(REGEXP_REGEXP);
 if (match) {
   var ctorExpression =
       "(new RegExp("
         // JSON.stringify escapes special chars in the body, so will
         // preserve token boundaries.
         + JSON.stringify(match[1])
         + "," + JSON.stringify(match[2])
       + "))";
   alert(ctorExpression);
 }

这将导致在JavaScript的一个众所周知的子集中的表达式。

上面的复杂正则表达式不在TCB中。为了保持安全性,唯一需要正确工作的部分是ctorExpression,包括使用JSON.stringify

似乎大多数标准JavaScript功能都可用(源代码),所以您只需执行以下操作:

try {
    RegExp(json.something+'');
    pacFile += 'RegExp(' + JSON.stringify(json.something+'') + ')';
} catch(e) {/*handle invalid regexp*/}

不用担心,因为RegExp("console.log('test')")只会生成有效的/console.log('test')/正则表达式,而不会执行任何内容。