开发者

Fork and drop privileges with Java

开发者 https://www.devze.com 2023-02-13 16:35 出处:网络
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 pro

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开发者_JS百科 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

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.


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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号