Running scripts generated from unsanitized inputs (for example, evaluating expressions that include user-provided strings) can lead to malicious behavior and inadvertently running code remotely.
1var express = require('express')
2var app = express()
3var vm = require('vm')
4function codeInjectionNoncompliant() {
5 app.get('/perform/:action', (req, res) => {
6 const sandbox = {
7 actionToPerform: req.params.action
8 }
9 const code = 'performAction(sandbox.actionToPerform)'
10 vm.createContext(sandbox)
11 // Noncompliant: user-supplied input evaluated as a script.
12 vm.runInContext(code, sandbox)
13 res.send('Action performed successfully!')
14 })
15}
1var express = require('express')
2var app = express()
3var vm = require('vm')
4function codeInjectionCompliant() {
5 app.get('/perform/:action', (req, res) => {
6 const sandbox = {
7 actionToPerform: req.params.action
8 }
9 const code = 'performAction(sandbox.actionToPerform)'
10 vm.createContext(sandbox)
11 // Compliant: user-supplied parameter must be in allow-list to be evaluated.
12 if(sandbox.actionToPerform.match(/^pull|fetch|add|commit$/)) {
13 vm.runInContext(code, sandbox)
14 res.send('Action performed successfully!')
15 }
16 else
17 res.send('Invalid action')
18 })
19}