Question

I'm looking to load and unload a linux kernel module from my Java program.

I initially tried doing it by using ProcessBuilder to run the commands, however it fails because the program doesnt have root access. Running my program as root also yields the same problem as it's a different process which needs the root access.

So how do I acquire root access in my program so it is allowed to run insmod and rmmod. This is what it looks like so far.

String loader (String s, int i) throws BadLoaderIntException{
    if(i == 0){
        s = "insmod " + s;
    }else if(i == 1){
        s = "rmmod " + s;
    }else{
        throw new BadLoaderIntException();
    }

    ProcessBuilder pb = new ProcessBuilder("bash", "-c", s);
    pb.redirectErrorStream(true); //Outputs to stderr in-case of Error
    Process shell = null;
    try {
        shell = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream shellIn = shell.getInputStream();
    ...
Was it helpful?

Solution

Wrap your call to modules in su or sudo and make sure that the java process in running as root

OTHER TIPS

Make a setuid wrapper for modprobe(8) or insmod(8)


Modprobe(8) and insmod(8) are not setuid for obvious reasons, but it should be safe to make a setuid wrapper for them that executes only certain approved loads. Then, run the wrapper from java. Just make sure the approved modules require root credentials to change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top