| Author |
Disallowing private method invocation by Reflection
|
Chinmay Bajikar
Ranch Hand
Joined: Dec 08, 2001
Posts: 159
|
|
Hi, We know that using a block of code given below, we can access a private method out of a class. Class myClass = Class.forName(className); Object classInstance = myClass.newInstance(); Method method = myClass.getDeclaredMethod(methodName,classArgs); method.setAccessible(true); method.invoke(classInstance, privateMethodArgs); My question is how can we change the security manager to not allow this. Also is it possible to do this out of java code, in a policy file. Preferably the existing policy file that comes with the JRE. Thanks in advance, -Chinmay
|
The strength of the Wolf is the pack & the strength of the pack is the wolf....Rudyard Kipling
|
 |
Timothy Frey
Ranch Hand
Joined: Jul 22, 2006
Posts: 56
|
|
I don't know if it's possible or not (I'd say it probably isn't), but why would you want to do that anyway? Access modifiers are there to help developers; they're not a security mechanism. You label methods and fields as private to keep other developers (and yourself!) from directly using them. See the "information hiding" principle of OO design. If another developer wants to go crazy with reflection in order to defeat your API, that's their problem, not yours. Chances are their code will break when you start refactoring the internals anyway.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
I wouldn't bother if even Sun haven't secured the core Java API: Output:
abcd, bcd abcf, bcf abcf, abc
As you can see this breaks all assumptions any Java developer has ever made about Strings - that they are immutable. Even worse, because Strings can share the internal char arrays, changing one can many others as well. So yeah, if Sun couldn't secure something as important as this, then I don't think you can secure your methods.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
To block such reflective access, you need a SecurutyManager. By default, Java applications have no SecurityManager. This means if you start java from the command line, you own that process, and you have ultimate authority to do whatever you want in that process. It's your own fault if you misuse reflection. However, if you plan to run code from untrusted third parties, then you can install a SecurityManager: This new SecurityManager will get its permissions from the system and user policy files (if present). See here for more info. By default, the standard system policy file on your system does not allow reflective access to private members, so you should be covered. You may then want to further edit the policy file if it ends up prohibiting some thigns you want to do - that's your call.
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: Disallowing private method invocation by Reflection
|
|
|