New function detected Medium

Use of new Function() can be dangerous if used to evaluate dynamic content. Input from outside of program might cause code injection vulnerability.

Detector ID
javascript/new-function-detected@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1var express = require('express')
2var app = express()
3function newFunctionDetectedNoncompliant() {
4    app.post('www.example.com',  (req, res) => {
5        // Noncompliant: passing arbitrary user-input to new 'Function()'.
6        var newFunc = new Function(req.body)
7        newFunc()
8    })
9}

Compliant example

1var express = require('express')
2var app = express()
3function newFunctionDetectedCompliant() {
4    app.post('www.example.com',  (req, res) => {
5        var value = "test"
6        // Compliant: passing hardcoded value to new 'Function()'.
7        var newFunc = new Function('alert(value)')
8        newFunc()
9    })
10}