2

I'm writing a Java program that calls library code that is not mine; and so I am running the program in a SecurityManager with only the minimum required permissions.

There is one particular permission which I only need in the first couple lines of method main()... and then never again.

Is it possible in Java, to reduce the permissions at a certain point in execution?

My understanding (I hope this is right) is Apache httpd does this, first using its root privileges to bind to port 80/443 etc., and then using system call setuid() (or similar) to assume lesser privileges for the remainder of the program. I would have thought the same would be possible, in principle, in the Java VM.

Douglas Held
  • 1,452
  • 11
  • 25
  • Just install the SecurityManager after the lines of code in question. – user207421 Jul 15 '15 at 23:25
  • Comment to update that I never did find an acceptable way to do this. When configuring the SecurityManager with java.security, the SecurityManager automatically allows all sorts of obvious things like loading all the classes in your class path. But when introducing a custom SecurityManager at runtime, there are no permissions. You need to open the barn door to do anything. The minimum to load and initialize the classes in my case, included allowing Reflection and modifying System Properties. So it wasn't worth the effort. – Douglas Held Aug 06 '15 at 08:03

1 Answers1

0

You can use a custom SecurityManager for your purpose like...

System.setSecurityManager(new SecurityManager() {
        @Override
        public void checkPermission(Permission perm) {
            ...
    });

Now based on the permission you want to check or based on the current thread execution you can validate.

Hope this is clear.

  • Thank you Aninda. Your example does not compile. It is missing one closing `}` – Douglas Held Jul 17 '15 at 13:48
  • I tried this, adding the same logic as the `java.policy` file I previously prepared, and what I see is this technique does not allow my program to load any classes. See http://stackoverflow.com/questions/3817330/noclassdeffounderror-when-creating-objects-under-securitymanager ... so I think something about this solution must surely be "doing it wrong"... – Douglas Held Jul 17 '15 at 20:17