Fork and drop privileges with Java

2020-06-23 07:47发布

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?

3条回答
虎瘦雄心在
2楼-- · 2020-06-23 08:27

It's probably easier to just use JNI to drop privileges.

Here's one I knocked up earlier:

UID.java

public class UID {

    public static native int setuid(int uid);

    static {
        System.loadLibrary("uid");
    }
}

unix_uid.c

#include <sys/types.h>
#include <unistd.h>
#include <jni.h>
#include "UID.h"

JNIEXPORT jint JNICALL
Java_UID_setuid(JNIEnv * jnienv, jclass j, jint uid)
{
    return((jint)setuid((uid_t)uid));
}

UID.h is machine generated from UID.class using javah.

查看更多
Root(大扎)
3楼-- · 2020-06-23 08:28

If you only want to start a non-root process as root, then su will be sufficient. It will not ask for a password when going from root to another user, so it should not need a terminal.

查看更多
家丑人穷心不美
4楼-- · 2020-06-23 08:46

You could use su(1) instead of sudo(8). su(1) is much less involved, and probably won't want the terminal itself. (Of course, if your PAM configuration requires terminal input for su(1), then this might not work well either.)

查看更多
登录 后发表回答