Eval injection

Eval injection

Description

Eval injection occurs when user input is treated as code by JavaScript's eval(), new Function(), or browser timers such as setTimeout() and setInterval() with string arguments. An attacker can supply JavaScript that leads to cross-site scripting (XSS) or similar harm.

Potential impact

  • Malicious JavaScript running with the page's permissions, stealing user information or acting on the user's behalf
  • Sensitive user data sent to an attacker

Remediation

  • Avoid eval, new Function, and browser setTimeout/setInterval calls that execute strings. Call functions or predefined operations instead.
  • Where input is needed, validate it and accept only permitted values.
  • Keep user input separate from executable code and implement the required business operations directly.

Examples

Before

javascript
// Fixed code without external input
eval('alert("hi")'); // Fixed code, no external input
// Untrusted input
const param = new URLSearchParams(window.location.search).get('cmd');
eval(param); // A user can supply malicious code in cmd

After

javascript
const allowed = ['showMessage', 'log']
const param = new URLSearchParams(window.location.search).get('cmd')
if (allowed.includes(param)) {
    if(param === 'showMessage') alert('안녕하세요!')
    if(param === 'log') console.log('로그 처리')
} else {
    // Reject commands outside the allow-list
    console.warn('잘못된 명령입니다.')
}

Explanation:

  • Before: Passing unvalidated input to eval lets the caller insert and execute code.
  • After: The input selects only predefined operations. No dynamic execution function such as eval is used.

References