|
Rule 2: Make Inner Classes Private
Ensure your inner classes are private if using them is necessary
by Adam Kolawa, Ph.D., Gina Assaf, and Roberto Scaramuzzi, Ph.D.
Posted March 17, 2004
Editor's Note: Java Pro Online presents a weekly rule for ensuring the security of Java systems. This discussion provides the second rule you can follow to begin your strategy for ensuring your Java applications are secure. See the entire index of Java code security rules here.
This rule requires that inner classes be private. As explained in "Rule 1: Avoid Using Inner Classes" (Java Pro Online, March 10, 2004), using inner classes can jeopardize security. However, if you really need to use inner classes, you should at least ensure that they are private.
Java allows classes to contain other classes; however, Java bytecode does not implement this concept, so the compiler translates inner classes into package-private classes. As a result of this translation, any private method or field in the container class that the inner class accesses can be seen by other classes in the same package. Other classes in the package can write to a private field of the container class as long as the inner class also writes to that field. Here is sample code that violates this rule:
package examples.rules.security;
public class INNER {
class INNER_Class {
// VIOLATION
void setValue(int i) {
_value = i; // now the
// "package" can write to
// this "private" field.
}
}
private int _value;
}
To correct this code, make INNER_Class private:
package examples.rules.security;
public class INNER {
private class INNER_Class {
// FIXED
void setValue(int i) {
_value = i;
}
}
private int _value;
}
Rule sources: " IEEE Software: "Statically Scanning Java Code: Finding Security Vulnerabilities" John Viega, Gary McGraw, Tom Mutdosch, and Edward W. Felten (September/October 2000).
Java in Practice: Design Styles and Idioms for Effective Java Nigel Warren and Philip Bishop (Addison-Wesley, 1999) pp. 10–11
About the Author
Adam Kolawa, Ph.D, is the chairman and CEO of Parasoft. He is a writer and speaker on industry issues and in 2001 was awarded the Los Angeles Ernst & Young Entrepreneur of the Year Award in the software category. Gina Assaf has been developing, designing, testing, and implementing applications in Java for over six years, and has researched and developed coding standards for Parasoft, many of which provide security for Java applications. Roberto Scaramuzzi, Ph.D., is a Java and Perl Developer for Parasoft in San Diego, California. Born in Italy, he later moved to the United States to obtain his doctorate in Mathematics from Yale University. Contact the authors at .
Back to top
|