3

I am writing a Java program which will be running on Linux servers. The program needs to start as "root", do a certain operation (reading a file), and then downgrade itself to a non-root user, after the file has been read and closed.

I read through the following questions, but I haven't found a viable solution - especially since I am not dealing with http ports.

https://askubuntu.com/questions/62713/how-to-downgrade-user-permissions-on-a-java-app-after-opening-port-80-443

https://serverfault.com/questions/112795/how-can-i-run-a-server-on-linux-on-port-80-as-a-normal-user

Running a part of a Java Program as Root

Any ideas on how to implement what I am trying to do?

SOLVED: As suggested in the answer, JNA did the trick for me.

Community
  • 1
  • 1
BlueChips23
  • 1,861
  • 5
  • 34
  • 53
  • 1
    I'm not sure how to do it in Java, but in Unix it's called Bernstein Chaining or https://en.wikipedia.org/wiki/Chain_loading – Neil McGuigan Jul 07 '15 at 21:40

1 Answers1

1

Unfortunately there is no way to do this in pure Java.
But you can use JNI or JNA to call setuid system function.
For instance, you may reuse jetty-setuid package for doing so: JAR + Native library.

apangin
  • 92,924
  • 10
  • 193
  • 247
  • I agree that the only viable way to handle this is by calling setuid system function. Isn't this a somewhat common problem? Typically applications that need to do some specific "root" related tasks should launch as root but for security reasons they should downgrade as soon as possible to a non-root user. – BlueChips23 Jul 08 '15 at 14:02
  • I didn't know earlier about JNA. I did some testing and JNA works perfectly - just what I needed. – BlueChips23 Jul 15 '15 at 15:11