使用新功能是否被视为安全风险

Is using new Function considered a security risk?

本文关键字:安全 新功能 是否      更新时间:2023-09-26

我有一个函数可以帮助我创建临时对象并节省打字时间。

附加编辑:为了澄清这个函数,它只能位于一个anon函数中。

(function(){ // clarification of the functions location
var objectPump = function (props, defaults){
    var str;
    if(typeof defaults === "string"){
        defaults = defaults.split(",");
    }else    
    if(typeof defaults === "undefined" ||  !defaults.isArray){        
        defaults =[];
    }
    if(props !== undefined){
        if(typeof props === "string"){
           props = props.split(",");
        }
    }else{
        throw new TypeError("No properties defined for objectPump.");
    }
    // create function body
    str = "var obj={};";
    props.each( function(p,i) {  
        str += "obj." + p + "=";
        if (typeof defaults[i] === "string") {
            str += p + "===undefined?" + '"' + defaults[i] + '":';
        } else
        if (typeof defaults[i] === "number") {
            str += p + "===undefined?" + defaults[i] + ":";
        }
        str += p + ";";  
    });
    str += "return obj;";
    str = "return new Function('" + props.join("','") + "','" + str + "')";
    // Uses new Function to create the new function
    return  (new Function(str))();  // Is this dangerous???        
}
})();  // wrapped in an anon function

这使我可以创建对象,而不必在默认情况下命名所有属性和代码。

编辑:使用上述功能。

var car = objectPump("colour,year,type", // objects property names
                     "white,2015,All Wheel Drive"); // object defaults
// or as arrays
var car = objectPump(["colour","year","type"], // objects property names
                     ["white",2015,"All Wheel Drive"]); // object defaults
var cars = [
    car("red",2011), // missing property defaults to All Wheel Drive
    car("blue",2015,"bike"),
];
var aCar =   car("blue",2015,"bike");
// same as
var aCar = {
    colour:"blue",
    year:2015,
    type:"bike"
};  // but saves me having to type out the property names for each new object

对我来说,它看起来非常类似于使用eval,第三方攻击者可能会在其中获取一些恶意代码。到目前为止,它非常方便,我很想将new Function用于其他任务。

我应该使用new Function()来生成代码,还是认为它对公共代码来说是坏的和/或危险的。

var car = objectPump("colour,script", // objects property names
        "white,'" + alert('"test'") + '""); // object defaults
console.log(new car('blue, but the nice one')); // throws alert 

你是说这样危险吗?

老实说,我真的不喜欢objectPump函数。你还有其他可行的选择:

  • 对函数使用TypeScript及其默认值(http://www.typescriptlang.org/Handbook#functions-可选和默认参数)
  • 使用typeof来定义默认值,即使它更像键入:

    function foo(a, b)
    {
        a = typeof a !== 'undefined' ? a : 42;
        b = typeof b !== 'undefined' ? b : 'default_b';
        ... 
    }
    

    (https://stackoverflow.com/a/894877/99256)

编辑:函数objectPump不会给攻击者带来任何优势。1) 如果攻击者可以修改您的JS文件,那么她将立即使用eval,并且不需要任何objectPump。2) 如果你清除了用户的所有输入,这里就没有问题了。

我最担心的是,你最终会朝自己的脚开枪,而不是攻击者。