Versions Compared

Key

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

Wiki Markup
Native methods are defined in Java and written in traditional languages such as C/C++ (see \[[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 (due to poor portability, safety and quite ironically, performance issues), they are still used to interface with legacy code.

Defining a wrapper method facilitates carrying out security manager checks, perform input validation before passing the arguments to the native code, defensively copy mutable inputs and sanitize user supplied input.

Noncompliant Code Example

...

Code Block
bgColor#FFcccc
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 {
    	    System.loadLibrary("NativeMethodLib"); //load native library in static initializer of class
  }
}

...

This compliant solution makes the actual native method private and defines a public wrapper that calls securityManagerCheck() which in turn performs routine permission checks to determine if the succeeding operations can continue. This is followed by input range checking and creation of a copy of the mutable input array, data. Finally the nativeOperation method is called with sanitized inputs. Ensure that the validation checks produce outputs that are coherent with the input requirements of the native implementations/libraries.

Code Block
bgColor#ccccff
public final class NativeMethodWrapper {

    // private native method
    private native void nativeOperation(byte[] data, int offset, int len);

    // wrapper method performs SecurityManager and input validation checks
    public void doOperation(byte[] data, int offset, int len) {
        // permission needed to invoke native method
        securityManagerCheck();

        if (data == null) {
            throw new NullPointerException();
        }

        // copy mutable input
        data = data.clone();

        // validate input
        if ((offset < 0) || (len < 0) || (offset > (data.length - len))) {
            throw new IllegalArgumentException();
        }

        nativeOperation(data, offset, len);
    }

  static {
    	    System.loadLibrary("NativeMethodLib"); //load native library in static initializer of class
  }
}

...