Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2022.2

Code injection can occur when untrusted input is injected into dynamically constructed code. The One obvious source of potential vulnerabilities is the use of JavaScript from Java code. The javax.script package both provides an API consists of interfaces and classes that define Java Scripting Engines scripting engines and also defines a framework for the use of those interfaces and classes in Java code. An obvious example is the use of JavaScript from Java code.   Misuse of the javax.script API permits an attacker to execute arbitrary code on the target system. Such errors are dangerous because violations of secure coding practices in dynamically generated code cannot be detected in advance through static analysis.

This guideline is a specific instance of IDS00-J. Sanitize untrusted data passed across a trust boundaryPrevent SQL injection.

Noncompliant Code Example

This noncompliant code example incorporates untrusted user input in into a JavaScript statement that is responsible for printing the input.:

Code Block
bgColor#FFCCCC
private static void evalScript(String firstName) throws ScriptException {
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("javascript");
  engine.eval("print('"+ firstName + "')");	
}

An attacker can enter a specially crafted argument in an attempt to inject malicious JavaScript. This example shows a malicious string that contains JavaScript code that can create a file or overwrite an existing file on a Windows vulnerable system running the vulnerable Java code.

Code Block
bgColorffffcc
languagejavascript
dummy\');
var bw = new JavaImporter(java.io.BufferedWriter); 
var fw = new JavaImporter(java.io.FileWriter); 
with(fw) with(bw) { 
   bwr = new BufferedWriter(new FileWriter(\"c://somepath//somefile.txtconfig.cfg\"));
   bwr.write(\"some text\"); bwr.close();
}
// ; 

The script prints in this example prints "dummy" and writes then writes "some text to somefile.txt behind the scenes" to a configuration file called config.cfg.  An actual exploit can execute arbitrary code.

Compliant Solution (Whitelisting)

The best defense against code injection vulnerabilities is to avoid including prevent the inclusion of executable user input in code. When User input used in dynamic code requires user input, that input must be sanitized. For , for example, a top-level method could to ensure that the string firstName it contains only valid, whitelisted characters. Sanitization is best performed immediately after the data has been input, using methods from the data abstraction used to store and process the data. Refer to IDS00-J. Sanitize untrusted data passed across a trust boundary for more details. If special characters are allowed must be permitted in the name, they must be escaped and normalized before comparing comparison with their equivalent forms for the purpose of input validation. This compliant solution uses whitelisting to prevent unsanitized input from being interpreted by the scripting engine.

Code Block
bgColor#ccccff
private static void evalScript(String firstName) throws ScriptException {
  // Allow only alphanumeric and underscore chars in firstName
  // (modify if firstName may also include special characters)
  if (!firstName.matches("[\\w]*")) { 
    // String does not match whitelisted characters
    throw new IllegalArgumentException();
  } 

  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("javascript");
  engine.eval("print('"+ firstName + "')");	
}

Compliant Solution (Secure Sandbox)

An alternative approach An alternative policy is to create a secure sandbox using a security manager . (See SEC60see SEC54-JGJ. Create a secure sandbox using a Security Managersecurity manager.)  The application should not allow prevent the script to execute from executing arbitrary commands including, for example, such as querying the local file system. The two-argument form of of doPrivileged() can  can be used to lower privileges when the application must operate with higher privileges, but the scripting engine must not. The The RestrictedAccessControlContext strips  reduces the permissions granted in the default policy file by reducing the permissions granted to those of the newly created protection domain. The effective permissions are the intersection of the permissions of the newly created protection domain and the systemwide security policy. Refer to to SEC50-JGJ. Avoid granting excess privileges for  for more details on the two-argument form of doPrivileged().

This compliant solution illustrates the use of an an AccessControlContext in  in the two-argument form of of doPrivileged().

Code Block
bgColor#ccccff
class ACC {

  private static class RestrictedAccessControlContext {
      private static final AccessControlContext INSTANCE;
  
    static {	
      INSTANCE = new AccessControlContext(
                INSTANCE = new AccessControlContext(new ProtectionDomain[] { 
                     new ProtectionDomain(null, null) // noNo permissions
                   });
    }
  }
  }

  private static // First sanitizevoid evalScript(final String firstName)
 (modify if the name may includethrows specialScriptException characters)
{
  if(!firstName.matches("[\\w]*")) { //ScriptEngineManager Stringmanager does= not match whitelisted characters
    throw new IllegalArgumentException(new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("javascript");
  } 

  // Restrict permission using the two-argument form of doPrivileged()
    try {
      AccessController.doPrivileged(
        new PrivilegedExceptionActionPrivilegedExceptionAction<Object>() {
                        
          public Object run() throws ScriptException {
            engine.eval("print('" + firstName + "')");		
            return null;
          }
    	
    }, 
        // From nested class
        RestrictedAccessControlContext.INSTANCE); // From nested class

                                                                    
    } catch (PrivilegedActionException pae) {
    	
    // Handle error
  }  }
     

...

}
}

This approach can be combined with whitelisting for additional security.

Applicability

Failure to prevent code injection can result in the execution of arbitrary code.

Automated Detection

Tool
Guideline
Version
Severity
Checker

Likelihood

Remediation Cost

Priority

Level

IDS51-JG

high

likely

medium

P18

L1

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

...

Description
The Checker Framework

Include Page
The Checker Framework_V
The Checker Framework_V

Tainting CheckerTrust and security errors (see Chapter 8)
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.IDS52.TDCODEValidate potentially tainted data before it is used in methods that generate code

Bibliography

...

...


...

Image Modified Image Modified Image Modified