The Synthetic Outer Class Method

Assertion

When the inner class accesses private members of the outer class, the compiler generates synthetic methods that are package private. The assertion is that these synthetic methods are available to any class from the same package, not just the inner classes of the class.

Proof

Create the following files.

File synthetic/A.java

public class A {
  private static String name() { return "Synthetic method"; }
  public static class B {
    public static String name() { return A.name(); }
  }
}

File non-synthetic/A.java

public class A {
  private static String name() { return "Non-synthetic method"; }
  static String access$000() { return name(); }
  public static class B {
    public static String name() { return A.access$000(); }
  }
}

File C.java

public class C {
  public static void main(String[] args) {
    System.out.println(A.access$000());
  }
}

Compile the “synthetic” version of class A, and package it in a JAR.

cd synthetic
javac A.java
jar cvf ../synthetic-method.jar *.class
cd ..

Compile the “non-synthetic” version of class A, and package it in a JAR.

cd non-synthetic
javac A.java
jar cvf ../non-synthetic-method.jar *.class
cd ..

Compile the client class, using the “non-synthetic” version of the JAR.

javac -classpath non-synthetic-method.jar C.java

Run the client class, using the “synthetic” version of the JAR. (If you’re on a Windows-based computer, replace the colon with a semicolon.)

java -classpath .:synthetic-method.jar C

The client should fail to produce a result, because there is no method called access$000 defined by A. The synthetic method access$000 is generated by the compiler to enable inner class B to access the private method name. Instead, the program prints Synthetic method. Quod erat demonstrandum.

Conclusion

The additional synthetic methods generated by the compiler to support inner class semantics provide access to private class fields/methods, bypassing normal security mechanisms. This provides potential attack avenues to attackers.

Post a Comment

Your email is never published nor shared. Required fields are marked *