73 lines
1.9 KiB
Plaintext
Raw Normal View History

include::../description.adoc[]
== Noncompliant Code Example
2021-01-27 13:42:22 +01:00
``++eval++`` and other functions that dynamically execute code should not be used in combination with user-input:
2021-01-08 09:39:48 +01:00
----
let input = req.query.input;
eval(input); // Noncompliant
2021-01-08 16:20:41 +01:00
(Function(input))(); // Noncompliant
2021-01-08 09:39:48 +01:00
(new Function(input))(); // Noncompliant
----
----
const vm = require("vm");
let input = req.query.input;
vm.runInThisContext(input); // Noncompliant
const context = {};
vm.createContext(context);
vm.runInContext(input, context); // Noncompliant
vm.runInNewContext(input, context); // Noncompliant
vm.compileFunction(input)(); // Noncompliant
(new vm.Script(input)).runInThisContext(); // Noncompliant
----
----
var Module = require('module');
let name = req.query.name;
let input = req.query.input;
var mod = new Module(name, module.parent);
mod._compile(input, name); // Noncompliant
----
2021-01-27 13:42:22 +01:00
In a MongoDB context, https://docs.mongodb.com/manual/faq/fundamentals/#how-does-mongodb-address-sql-or-query-injection[arbitrary Javascript code] can be executed with the ``++$where++`` operator for instance:
----
let username = req.query.username;
2021-01-08 16:20:41 +01:00
query = { $where: `this.username == '${username}'` } // Noncompliant
User.find(query, function (err, users) {
if (err) {
// Handle errors
} else {
res.render('userlookup', { title: 'User Lookup', users: users });
}
});
----
2021-01-08 16:20:41 +01:00
== Compliant Solution
2021-01-27 13:42:22 +01:00
If ``++eval++`` is used to parse a JSON string this should be done instead with ``++JSON.parse++``:
2021-01-08 09:39:48 +01:00
----
let obj = JSON.parse(req.query.input); // Compliant
----
2021-01-27 13:42:22 +01:00
In a MongoDB context, don't use ``++$where++`` operator or validate the data:
2021-01-08 16:20:41 +01:00
----
let username = req.query.username;
query = { username: username } // Compliant
User.find(query, function (err, users) {
if (err) {
// Handle errors
} else {
res.render('userlookup', { title: 'User Lookup', users: users });
}
});
----
include::../see.adoc[]