Dynamic code execution APIs allow code to be provided and executed as strings at runtime.
Some APIs enable the execution of code provided as strings at runtime. These APIs might be useful in specific meta-programming use-cases, but they also increase the risk of code injection. When user-controlled data is included in the code string, an attacker can inject and execute arbitrary instructions within the application.
eval and the Function constructor execute strings as JavaScript code in the current scope. Strings prefixed with
javascript: in URLs are evaluated the same way.
When user-controlled data reaches a dynamic code execution API, an attacker can craft input that alters the intended logic of the program.
An attacker who can influence the code being executed can run arbitrary commands on the host system or within the database, potentially leading to full system compromise, data exfiltration, or privilege escalation.
function run(role) {
eval(`handle_${role}()`); // Noncompliant
}
const HANDLERS = {
user: handleUser,
admin: handleAdmin,
};
function run(role) {
const handler = HANDLERS[role];
if (!handler) {
throw new Error(`Unknown role: ${role}`);
}
handler();
}
This rule does not raise an issue when the argument of eval or Function is a literal string, as there is no opportunity
for injection.