Sujal Mandal Sujal Mandal - 3 months ago 14
Java Question

Why can i increase the visibility of a overridden method in a subclass, is it not a security risk?

If we consider this piece of code, is it not a security risk, if yes then why does java allow it?

class SomeApi
{
void someImportantInnerApiMethod()
{
//some operation
}
}

class MaliciousUserClass extends SomeApi
{
@Override
public void someImportantInnerApiMethod()
{
super.someImportantInnerApiMethod();
//inner api method now exposed
}
}

Answer

Access modifiers are not meant for security. You can call even a private method through reflection anyway. They are meant for encapsulation which shields from programming errors and enforces good programming style to a certain degree.

Even if you couldn't make overridden methods public, you could still do this:

class SomeApi
{
    void someImportantInnerApiMethod()
    {
    //some operation
    } 
}

class MaliciousUserClass extends SomeApi
{
    public void aMethodWithATotallyDifferentName()
    {
        // ... that still exposes that important inner API method!
        super.someImportantInnerApiMethod();
    } 
}

Since you can make it “accessible” in this way, the only thing that Java does is allow you to do exactly the same thing while keeping the method name, if you really want to do this. No harm done because you usually don't do this kind of thing accidentally.

It is also probably worth mentioning that package-private access is ridiculously easy to circumvent: unlike .Net's internal, you can really put your classes in the same package as another library you're using, and you're free to call package-private methods! Say, you declare your class to be a part of javax.swing package, now it can call Swing's package-private methods. So much for security. You don't even need inheritance and/or reflection.

Comments