Issue
I'm experimenting with PropertyChangeSupport
which has the useful firePropertyChange
method. If security is a concern, is it actually safe to use reflection to trigger methods as in the line below or would it be preferable to simply hardcode calls to method names? If reflection is a potential issue, how would one prevent it?
method.invoke(instance, newValue);
Solution
If security is a concern, is it actually safe to use reflection to trigger methods [...] or would it be preferable to simply hardcode calls to method names?
In general, it is preferable to NOT use reflection. Your application will be faster, simpler (e.g. fewer lines of code) and less fragile (e.g. less likely to throw unchecked exceptions) if you use ordinary (non-reflective) calls. It is best to only use reflection when simpler approaches won't work.
[UPDATE - the following discussion only applies to older versions of Java. Java security managers and security sandboxes have been deprecated, and the functionality is being removed starting from Java 17. Java no longer supports running untrusted code.]
Security of reflection is also a potential concern.
If your JVM is running untrusted or unknown code that might try to do bad things, then the reflection APIs in general offer lots of opportunities to do bad things. For example, it allows the bad code to call methods and access fields that the Java compiler would prevent. (It even allows the code to do evil things like changing the value of
final
attributes and other things that are normally assumed to be immutable.)Even if your JVM is running entirely trusted code, it is still possible that a design flaw or system-level security problem may allow the injection of class or method names by a hacker. The reflection APIs would then dutifully attempt to invoke unexpected methods.
If reflection is a potential issue, how would one prevent it?
That is easy. An application requires various permissions to successfully call the relevant security sensitive methods in the reflection APIs. These permissions are granted by default to trusted applications and not to sandboxed applications. You are free to adjust them.
The simple solution: if you are running trusted code, or if you are worried about the possibility of design flaws comprising security, run all relevant code in a security sandbox that prevents use of the reflection APIs. (The downside is that some 3rd-party libraries are designed under the assumption that they can use reflection ... and will break in a sandbox.)
(Apparently, there is no permission check for an actual Method.invoke(...)
call. The check happens earlier when the application code obtains the Method
object from the Class
.)
Answered By - Stephen C
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.