views:

304

answers:

3

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();
 ...
A: 

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.

DigitalRoss
+1  A: 

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

KitsuneYMG
As far as I could tell, the ProcessBuilder takes one string as a command. Therefore I need to spawn the process as root to run the command as root but at the moment don't know how to do this.
cheesysam
Assuming that your jvm is running as root "bash -c sudo xxx" ought to be executed by root. The bash -c is needed because runtime.exec doesn't use a shell
KitsuneYMG
A: 

I've recently come back to this problem and I'm no closer to solving it than when I left. Can anyone shed some more light on it?

cheesysam