I'm writing a server program in Java that will allow users to submit jobs using DRMAA. Although the main server process runs as root
, all it does is authenticate the user, then start another Java program which runs as that user and actually does the work in order to comply with the principle of minimising privileges. Initially, I was doing this with Runtime.exec()
and sudo
(example below) which works fine until the process is dæmonised, at which point sudo
gets upset because it doesn't have a terminal.
String[] command = {"sudo", "-i", "-u", username, java, theOtherJavaProgram};
Runtime.getRuntime().exec(command, null, getHomeDirectory(username));
What's the best way to do this fork and drop privileges pattern in Java when running as a daemon? Is there a way? Am I going to have to break out the C and learn how to create JVMs with JNI?
It's probably easier to just use JNI to drop privileges.
Here's one I knocked up earlier:
UID.java
unix_uid.c
UID.h
is machine generated fromUID.class
usingjavah
.If you only want to start a non-
root
process asroot
, thensu
will be sufficient. It will not ask for a password when going fromroot
to another user, so it should not need a terminal.You could use
su(1)
instead ofsudo(8)
.su(1)
is much less involved, and probably won't want the terminal itself. (Of course, if your PAM configuration requires terminal input forsu(1)
, then this might not work well either.)