Wiki Markup |
---|
Native methods are defined in Java and written in traditional languages such as C and C++ \[[JNI 06|AA. Java References#JNI 06]\]). The added extensibility comes at the cost of flexibility and portability as the code no longer conforms to the policies enforced by Java. In the past, native method were used for performing platform specific operations, interfacing with legacy library code and improving program performance \[[Bloch 08|AA. Java References#Bloch 08]\]. Although this is not completely true in present times (duebecause toof poor portability, safety and quite ironically, performance issues), native theycode areis still used to interface with legacy code. |
Defining a wrapper method facilitates installing appropriate security manager checks, performing input validation before passing the arguments to the native code or when obtaining return values, defensively copying mutable inputs and sanitizing user supplied input.
Noncompliant Code Example
Security manager checks are not conducted automatically enforced in case of native method invocations. Additionally, as demonstrated in the this noncompliant code example, it is easy to overlook proper input validation before the call. The doOperation()
method invokes the nativeOperation()
native method but fails to provide adequate input validation. Also, the access specifier of the native method is public
which raises risks associated with allows untrusted callers to invoke the method.
Code Block | ||
---|---|---|
| ||
public final class NativeMethod { // public native method public native void nativeOperation(byte[] data, int offset, int len); // wrapper method that does not perform any security checks or input validation public void doOperation(byte[] data, int offset, int len) { nativeOperation(data, offset, len); } static { // load native library in static initializer of class System.loadLibrary("NativeMethodLib"); } } |
Compliant Solution
This compliant solution makes declares the actual native method private
and defines a public
wrapper that calls the securityManagerCheck()
which in turn method. This method performs routine permission checks checking to determine if the succeeding operations can continue. This is followed by the creation of a copy of the mutable input array, data
and input range checking of the parameters. Finally the nativeOperation()
method is called with sanitized safe inputs. Ensure that the validation checks produce outputs that are coherent with the input requirements of the native implementations/libraries.
...