1177
concatenation of one of the private member variables of the class OuterClass, the separator input
parameter of the method and the private member variable of the class InnerClass.
Example Language: Java (Bad)
public class OuterClass {
// private member variables of OuterClass
private String memberOne;
private String memberTwo;
// constructor of OuterClass
public OuterClass(String varOne, String varTwo) {
this.memberOne = varOne;
this.memberTwo = varTwo;
}
// InnerClass is a member inner class of OuterClass
private class InnerClass {
private String innerMemberOne;
public InnerClass(String innerVarOne) {
this.innerMemberOne = innerVarOne;
}
public String concat(String separator) {
// InnerClass has access to private member variables of OuterClass
System.out.println("Value of memberOne is: " + memberOne);
return OuterClass.this.memberTwo + separator + this.innerMemberOne;
}
}
}
Although this is an acceptable use of inner classes it demonstrates one of the weaknesses of
inner classes that inner classes have complete access to all member variables and methods of
the enclosing class even those that are declared private and protected. When inner classes are
compiled and translated into Java bytecode the JVM treats the inner class as a peer class with
package level access to the enclosing class.
To avoid this weakness of inner classes, consider using either static inner classes, local inner
classes, or anonymous inner classes.
The following Java example demonstrates the use of static inner classes using the previous
example. The inner class InnerClass is declared using the static modifier that signifies that
InnerClass is a static member of the enclosing class OuterClass. By declaring an inner class as
a static member of the enclosing class, the inner class can only access other static members and
methods of the enclosing class and prevents the inner class from accessing nonstatic member
variables and methods of the enclosing class. In this case the inner class InnerClass can only
access the static member variable memberTwo of the enclosing class OuterClass but cannot
access the nonstatic member variable memberOne.
Example Language: Java (Good)
public class OuterClass {
// private member variables of OuterClass
private String memberOne;
private static String memberTwo;
// constructor of OuterClass
public OuterClass(String varOne, String varTwo) {
this.memberOne = varOne;
this.memberTwo = varTwo;
}
// InnerClass is a static inner class of OuterClass
private static class InnerClass {
private String innerMemberOne;
public InnerClass(String innerVarOne) {
this.innerMemberOne = innerVarOne;
}
public String concat(String separator) {
// InnerClass only has access to static member variables of OuterClass
CWE Version 4.14
CWE-492: Use of Inner Class Containing Sensitive Data
CWE-492: Use of Inner Class Containing Sensitive Data