Assertion
Sun’s Java Virtual Machine ignores inner class access modifiers. All Sun’s virtual machine versions are affected.
Proof
Create the following files.
File public/A.java
public class A {
public static class B {
public static String name() { return "Public inner class"; }
}
}
File private/A.java
public class A {
private static class B {
public static String name() { return "Private inner class"; }
}
}
File C.java
public class C {
public static void main(String[] args) {
System.out.println(A.B.name());
}
}
Compile the “public” version of class A and package it in a JAR.
cd public
javac A.java
jar cvf ../public-inner-class.jar *.class
cd ..
Compile the “private” version of class A and package it in a JAR.
cd private
javac A.java
jar cvf ../private-inner-class.jar *.class
cd ..
Compile the client class, using the public version of the JAR.
javac -classpath public-inner-class.jar C.java
Run the client class, using the private version of the JAR. (If you’re on a Windows-based computer, replace the colon with a semicolon.)
java -classpath .:private-inner-class.jar C
The code should fail to run, because class A.B is private and cannot be accessed from class C. Instead, the code runs successfully, printing out Private inner class. Quod erat demonstrandum.
Conclusion
Although Sun’s compiler enforces the rules of access to an inner class based on the access flags of the class, the Virtual Machine fails to enforce the same access rules, creating potential security breaches.
Post a Comment