0

I need to ensure that a method from a class is only executed by selected methods from different packages.

package myApp.security;
public class SecurityStuff{
    public static final SecurityStuff security = new SecurityStuff();
    public KeyStore getKeyStore(){
        //if invoked by MySock.getTLSServerSocket()
        return keyStore;
        //if not, should return null
    }
}

package myApp.socks;
public class MySock{
    public void getTLSServerSocket(){
        KeyStore keyStore = SecurityStuff.security.getKeyStore();
    }
}

With the 2 classes above, how do I ensure that SecurityStuff.getKeyStore() would return the KeyStore iff it is from the classes & methods that I allow?

Please take into account that the jar would be obfuscated later.

theAnonymous
  • 1,701
  • 2
  • 28
  • 62
  • 2
    Sounds like an [XY Problem](http://xyproblem.info/). – shmosel Nov 05 '17 at 08:56
  • GhostCat - Obfuscation will make that solution useless. Read the last paragraph, thanks. – theAnonymous Nov 05 '17 at 09:00
  • And yes, rethink your design. This is a bad idea. Think more about *objects* - you should rather consider who can get to **objects**. If you prevent handing out the object to invalid "holders" - then you implicitly prevent methods from being called! – GhostCat Nov 05 '17 at 09:01
  • Then you please make it more explicit that you already studied other answers! And I still think that the second answer given to that DUP is what you should focus on! – GhostCat Nov 05 '17 at 09:01
  • I guess a `SecurityManager` could come in handy. These [secure coding guidelines for Java SE](http://www.oracle.com/technetwork/java/seccodeguide-139067.html#9) explains how to properly use it. Also refer to [this SO post](https://stackoverflow.com/questions/5486797/how-to-prevent-public-methods-from-being-called-from-specific-classes/5490106#5490106). – Alexandre Dupriez Nov 05 '17 at 11:10

2 Answers2

2

You can request the sender's object:

 public KeyStore getKeyStore(Object obj){
        if (!obj instanceof MyClassThatIsAllowedToCall) return;
        //execute code
 }

And when you call getKeyStore always provide the parameter:

getKeyStore(this);

This seems to be what you want, but it is NOT secure! You could easily fake the sender. So if you are actually handling confidential data, this won't be the way to go.

Basti
  • 517
  • 4
  • 19
2

Take a look at StakTraceElement . You can get stacktrace like :

StackTraceElement[] stack = Thread.currentThread().getStackTrace();

Then you can get the calling method name using getMethodName(). So, probably you can whitelist the methods you want access to and return keystore for them. For all other cases, you can return null. Hope this helps.

Prem
  • 51
  • 4
  • That is what was suggested in the duplicated question I pointed out earlier on. It doesn't work for the OP because the classes will be obfuscated. Method names will thus be different at runtime. – GhostCat Nov 05 '17 at 09:31