My app need to run as none-root user but need to switch to other user to execute some commands.
I tried to:
write a JNI,
JNIEXPORT void JNICALL Java_SetUIDJNI_setuid(JNIEnv *env, jobject thisObj,jstring uname) { const char *name = jstringTostring(env,uname); int pid; struct passwd *p; show_ids(); if ((p = getpwnam(name)) == NULL) { perror(name); exit(EXIT_FAILURE); } pid = (int) p->pw_uid; printf("pid=%d\n",pid); if (seteuid (pid) < 0) { perror ("setuid"); exit (EXIT_FAILURE); } show_ids(); }
build it as root and chmod u+s
-rwsr-xr-x 1 root root 76155 Aug 7 16:56 libsetuid.so*
call it in java
api = new SetUIDJNI(); // invoke the native method api.setuid("slurm");
But if run it as none-root, it does not work
/opt/jdk1.8/jre/bin/java -Djava.library.path=../jni HelloJNI
The real user ID is: 1000
The effective user ID is :1000 <= which expected is 0
setuid: Operation not permitted
But it works if runner is root
The real user ID is: 0
The effective user ID is :0
pid=1002The real user ID is: 0
The effective user ID is :1002
Anything wrong here?
UPDATE
Modify the JNI part to executable c
void show_ids (void)
{
printf ("The real user ID is: %d\n", getuid());
printf ("The effective user ID is :%d\n", geteuid());
}
int main(void)
{
show_ids();
if (seteuid (1002) < 0) {
perror ("setuid");
exit (EXIT_FAILURE);
}
show_ids();
return (0);
}
Build it as root and run chmod u+s
-rwsr-xr-x 1 root root 8814 Aug 9 11:44 a.out*
Run it as normal user and works
./a.out
The real user ID is: 1000
The effective user ID is :0
The real user ID is: 1000
The effective user ID is :1002