Resolving Fortify Dynamic Code Evaluation Warnings with JavaScript

During static code analysis with Fortify, usage of JavaScript's eval() function triggers warnings labeled as "Dynamic Code Evaluation: Code Injection." This security concern arises because dynamically executed code can introduce vulnerabilities that may compromise application integrity.

The primary risks associated with dynamic code evaluation include:

  • Execution of malicious code embedded within dynamic strings
  • Unauthorized code injection leading to data theft or logic manipulation
  • Increased difficulty in debugging and maintaining runtime-generated code
  • Potential for remote script execution attacks

While eval() provides powerful capabilities such as executing arbitrary JavaScript expressions, statements, and even function definitions, these features make it inherently unsafe. Common use cases include dynamic JSON parsing and runtime code generation, but safer alternatives exist for most scenarios.

Replacing Dynamic JSON Processing

When dealing with non-standard JSON responses from backend services, direct parsing with JSON.parse() often fails. For example, consider this response format:

var response = "{count:5,items:[{\"id\":1,\"value\":true}]}";

Historically, developers used eval("("+response+")") to convert such strings into objects. However, this approach introduces security vulnerabilities. A safer alternative involves preprocessing the string to conform to standard JSON syntax:

function parseNonStandardJSON(str) {
    // Convert unquoted keys to quoted keys
    const normalized = str.replace(/([{,])\s*([a-zA-Z0-9_]+)\s*:/g, '$1"$2":');
    return JSON.parse(normalized);
}

// Usage
const dataString = "{count:5,items:[{\"id\":1,\"value\":true}]}";
const result = parseNonStandardJSON(dataString);
console.log(result.count); // Outputs: 5

Evaluating Mathematical Expressions

Another common pattern involves using eval() for mathematical computations:

// Unsafe approach
const calculation = "3 * (4 + 2)";
const output = eval(calculation);

This can be replaced with JSON.parse() when dealing with numeric operations that produce valid JSON values:

// Safer replacement
const expression = "3 * (4 + 2)";
const computed = JSON.parse(expression);

For more complex mathematical expressions, consider implementing a dedicated expression parser or utilizing specialized libraries designed for safe mathematical computation.

These approaches eliminate Fortify warnings while maintaining functionality through secure coding practices.

Tags: javascript fortify Security JSON code-analysis

Posted on Mon, 27 Jul 2026 16:38:02 +0000 by houssam_ballout