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);
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 – some of 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 code in a security sandbox, then allowing that code to use the reflection APIs offers it lots of opportunities to do bad things. For example, the code can 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
finalattributes and other things that are normally assumed to be immutable.)Even if your JVM is running entirely trusted code, it is still possible for a design flaw or system-level security problem to allow the injection of class or method names by a hacker. The reflection APIs would then dutifully attempt to invoke unexpected methods.
Prior to Java 17, an application required various permissions to call security sensitive methods in the reflection APIs. These permissions were granted by default to trusted applications and not to sandboxed applications.
So, if you are worried about the possibility of design flaws in your trusted code comprising security by using reflection incorrectly, run all relevant code in a security sandbox. (The downside is that some 3rd-party libraries are designed under the assumption that they can use reflection. They may break if run in a sandbox.)
(Apparently, there is no permission check for an actual
Method.invoke(...)call. The check happens earlier when the application code obtains theMethodobject from theClass.)The other solution (if sandboxes are unavailable) is to audit your codebase and dependencies. Find and review all code that uses reflection APIs to check for possible security issues. That’s a lot of work if you do it by hand, so maybe you should invest in some tools to do the bulk of the work for you. (I have no recommendations!)
Note: I’m not necessarily recommending that you do this work. You would need to do a risk assessment for your application to determine if the effort is warranted.