Java Reference
In-Depth Information
Compliant Solution (Whitelisting)
The best defense against code injection vulnerabilities is to prevent the inclusion of ex-
ecutable user input in code. User input used in dynamic code must be sanitized, for ex-
ample, to ensure that it contains only valid, whitelisted characters. Santization is best per-
formed immediately after the data has been input, using methods from the data abstrac-
tion used to store and process the data. Refer to “IDS00-J. Sanitize untrusted data passed
across a trust boundary” [Long 2012] for more details. If special characters must be per-
mitted in the name, they must be normalized before comparison with their equivalent
formsforthepurposeofinputvalidation.Thiscompliantsolutionuseswhitelistingtopre-
vent unsanitized input from being interpreted by the scripting engine.
Click here to view code image
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 is to create a secure sandbox using a security manager (see
Guideline 20 , Create a secure sandbox using a security manager ”). The application
should prevent the script from executing arbitrary commands, such as 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 reduces the permissions granted in the de-
faultpolicyfiletothoseofthenewlycreatedprotectiondomain.Theeffectivepermissions
aretheintersectionofthepermissionsofthenewlycreatedprotectiondomainandthesys-
temwide security policy. Refer to Guideline 16 , Avoid granting excess privileges ,” for
more details on the two-argument form of doPrivileged() .
Search WWH ::




Custom Search