简体   繁体   中英

Java - Inner Classes opening a backdoor to Parent Class

I was going through some JVM Bytecode articles when I came across this video which shows how Inner Classes open up a backdoor into the parent scope, which could be exploited? (not sure, maybe it could be?)

Here's my test code.

public class Outer {

    private String name = "You got me!";

    public class Inner {
        public void printName() {
            System.out.println(name);
        }
    }

    public static void main(String[] args) {

        Outer o = new Outer();
        Inner i =  o.new Inner();
        i.printName();
    }
}

Now to see if such a backdoor method was being created I used javap to look into the class files.

Here is the result, see the printName method

用于printName方法的ByteCode

See the line 7: , you will see the invokestatic call to a Outer.access$0 .

Looking into the Outer.class we see the definition of the method.

后门方法定义

Is this a security vulnerability? Can it be exploited? I am just curious to know more on this.

There is no direct support for nested classes at the bytecode level, so each nested class in the Java source has to be compiled to a separate classfile. Effectively, they are completely separate, ordinary classes with some extra metadata for reflection purposes. When you access a member of the parent, the nested class needs to have access to that parent.

Normally, this is not a problem, but private members are only accessible within the class where they are defined, and hence not to the inner class. The compiler solves this by creating a bridge method that effectively changes the access level to package private.

This is a well documented phenomenon. Is it a security vulnerability? Not unless you are doing something very odd. Relying on Java's in-process sandbox is a bad idea if you care about security. But if you're working on a project that does this anyway, then yes, this is one on a long list of gotchas that you have to be aware of while coding the sandbox.

As you can note, synthetic accessor method has package private access. Thus when security manager is active, you cannot access it via reflection. Using MethodHandles.lookup you can access it from the same package only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM