Fork and drop privileges with Java

女生的网名这么多〃 提交于 2019-12-05 02:24:00

问题


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?


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5140131/fork-and-drop-privileges-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!