Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Code injection results from untrusted input being injected into dynamically constructed code. The javax.script package provides utilities to use various scripting engines an API of interfaces and classes that define Java Scripting Engines and defines a framework for their use in Java code. An obvious example is the use of JavaScript from Java code.  Misuse of these utilities 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.

Although code injection often involves scripting languages, code injection is possible using many coding languages, including HTML.

Noncompliant Code Example

...

An alternative policy is to create a secure sandbox using a security manager. (See SEC60-JG. Create a secure sandbox using a Security Manager.)  The application should not allow the script to execute arbitrary commands including, for example, querying the local file system. The two-argument form of doPrivileged() can be used to lower privileges when the application must operate with higher privileges but the scripting engine must not. The RestrictedAccessControlContext strips the permissions granted in the default policy file by reducing the permissions granted to 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 SEC50-JG. Avoid granting excess privileges for more details on the two-argument form.

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

Code Block
bgColor#ccccff
class ACC {

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

  // First sanitize firstName (modify if the name may include special characters)

  if(!firstName.matches("[\\w]*")) { // String does not match whitelisted characters
    throw new IllegalArgumentException();
  } 

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

...