According to Oracle Secure Coding Guideline Guideline 4-1/EXTEND-1 and Guideline 4-5/EXTEND-5 you should limit the accessibility of classes and their members as a security control against malicious override from an attacker.
Design classes and methods for inheritance or declare them final. Left non-final, a class or method can be maliciously overridden by an attacker. A class that does not permit subclassing is easier to implement and verify that it is secure.
How could an attacker actually exploit the below insecure class in real world scenario? Could he/she do it even if the class is already loaded in a running JVM?
public class PasswordVerifier {
private String regex;
public PasswordVerifier(String regex) {
this.regex = regex;
}
public boolean isPasswordValid(String password) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(password);
return matcher.find();
}
public String getRegex() {
return regex;
}
public void setRegex(String regex) {
this.regex = regex;
}
}
If we are talking about a malicious insider who has access to the source code, couldn't he just remove the final modifier(if one was there already) or alter the class itself by any means in the first place?