Search code examples
javaclassloader

Load library from MemoryClassLoader?


I've been working on a sort of bootstrapper for an application I am writing. It buffers an application from a website and runs it. It works very well up to the point that I call the main method of the main class of the application, which requires libraries, which are also streamed. The LIBs and the Application are in the same classloader, but it says it was unable to locate the library due to an unsatisfied link. I searched for help, but could not find any.


Solution

  • I assume you're getting an UnsatisfiedLinkError because you haven't done a Runtime.loadLibrary to bring in native code to support native methods. Such libraries need to be on the local file-system and are independent of any class loader. Javadoc:

    public void loadLibrary(String libname)
    

    Loads the dynamic library with the specified library name. A file containing native code is loaded from the local file system from a place where library files are conventionally obtained. The details of this process are implementation-dependent. The mapping from a library name to a specific filename is done in a system-specific manner.

    and obviously, Runtime.getRuntime() is independent of any particular class loader.

    If a network class load could cause a network load of native code, that would be a huge remote code execution vulnerability because native code cannot be constrained by a SecurityManager the way java bytecode can be.

    If you trust the website that produces the application, and are fetching it over a secure channel (encrypted to prevent MITM and tampering), then you can fetch the libraries, dump them to the local file system, verify any signatures or checksums, then call Runtime.loadLibrary or System.loadLibrary to load the native libraries before causing the class to initialize.

    If you don't trust the authors of the website that produces the application, or that website hosts third-party content, then don't load JARs much less system libraries from it.

    Even if the website authors are trustworthy, loading system libraries or other native code that you haven't vetted and tested can be dangerous. Process sandboxing via chroot and system call interception can help mitigate this risk somewhat but be careful.