...
Noncompliant Code Example
This noncompliant In this code example relies on , a class Account
that stores stores banking-related information without any inherent security. Security is delegated to the subclass BankAccount
. The client application is required to use BankAccount
because it contains the security mechanism.
Code Block | ||
---|---|---|
| ||
private class Account {
// Maintains all banking related data such as account balance
private double balance = 100;
boolean withdraw(double amount) {
if ((balance - amount) >= 0) {
balance -= amount;
System.out.println("Withdrawal successful. The balance is : "
+ balance);
return true;
}
return false;
}
}
public class BankAccount extends Account {
// Subclass handles authentication
@Override boolean withdraw(double amount) {
if (!securityCheck()) {
throw new IllegalAccessException();
}
return super.withdraw(amount);
}
private final boolean securityCheck() {
// check that account management may proceed
}
}
public class Client {
public static void main(String[] args) {
Account account = new BankAccount();
// Enforce security manager check
boolean result = account.withdraw(200.0);
System.out.println("Withdrawal successful? " + result);
}
}
|
At a later date, the maintainer of the class the Account
class added a new method called overdraft()
. However, the BankAccount
class maintainer was unaware of the change. Consequently, the client application became vulnerable to malicious invocations. For example, the overdraft()
method could be invoked directly on a BankAccount
object, avoiding the security checks that should have been present. The following noncompliant code example shows this vulnerability.
Code Block | ||
---|---|---|
| ||
private class Account {
// Maintains all banking related data such as account balance
private double balance = 100;
boolean overdraft() {
balance += 300; // Add 300 in case there is an overdraft
System.out.println("Added back-up amount. The balance is :"
+ balance);
return true;
}
// other Account methods
}
public class BankAccount extends Account {
// Subclass handles authentication
// NOTE: unchanged from previous version
// NOTE: lacks override of overdraft method
}
public class Client {
public static void main(String[] args) {
Account account = new BankAccount();
// Enforce security manager check
boolean result = account.withdraw(200.0);
if (!result) {
result = account.overdraft();
}
System.out.println("Withdrawal successful? " + result);
}
}
|
While this code works as expected, it adds a dangerous attack vector. Because there is no security check on the overdraft()
method, a malicious client can invoke it without authentication:
Code Block |
---|
public class MaliciousClient {
public static void main(String[] args) {
Account account = new BankAccount();
// No security check performed
boolean result = account.overdraft();
System.out.println("Withdrawal successful? " + result);
}
}
|
...
In this compliant solution, the BankAccount
class provides an overriding version of the overdraft()
method that immediately fails, preventing misuse of the overdraft feature. All other aspects of the compliant solution remain unchanged.
Code Block | ||
---|---|---|
| ||
class BankAccount extends Account {
// ...
@Override boolean overdraft() { // override
throw new IllegalAccessException();
}
}
|
...
This noncompliant code example overrides the methods after()
and compareTo()
of the class java.util.Calendar
. The Calendar.after()
method returns a boolean
value that indicates whether or not the Calendar
represents a time after that represented by the specified Object
parameter. The programmer wishes to extend this functionality so that the after()
method returns true
even when the two objects represent the same date. The programmer also overrides the method compareTo()
to provide a "comparisons by day" option to clients (for example, comparing today's date with the first day of the week, which differs from country to country, to check whether it is a weekday).
Code Block | ||
---|---|---|
| ||
class CalendarSubclass extends Calendar {
@Override public boolean after(Object when) {
// correctly calls Calendar.compareTo()
if (when instanceof Calendar &&
super.compareTo((Calendar) when) == 0) {
return true;
}
return super.after(when);
}
@Override public int compareTo(Calendar anotherCalendar) {
return compareDays(this.getFirstDayOfWeek(),
anotherCalendar.getFirstDayOfWeek());
}
private int compareDays(int currentFirstDayOfWeek,
int anotherFirstDayOfWeek) {
return (currentFirstDayOfWeek > anotherFirstDayOfWeek) ? 1
: (currentFirstDayOfWeek == anotherFirstDayOfWeek) ? 0 : -1;
}
public static void main(String[] args) {
CalendarSubclass cs1 = new CalendarSubclass();
cs1.setTime(new Date());
// Date of last Sunday (before now)
cs1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
// Wed Dec 31 19:00:00 EST 1969
CalendarSubclass cs2 = new CalendarSubclass();
// expected to print true
System.out.println(cs1.after(cs2));
}
// Implementation of other Calendar abstract methods
}
|
...
The documentation fails to state whether after()
invokes compareTo()
or whether compareTo()
invokes after()
. In the Oracle JDK 1.6 implementation, the source code for after()
is as follows:
Code Block | ||
---|---|---|
| ||
public boolean after(Object when) {
return when instanceof Calendar
&& compareTo((Calendar) when) > 0;
}
|
...
This compliant solution uses a design pattern called composition and forwarding (sometimes also called delegation) [Lieberman 1986], [Gamma 1995, p. 20]. The compliant solution introduces a new forwarder class that contains a private member field of the Calendar
type; this is composition rather than inheritance. In this example, the field refers to CalendarImplementation
, a concrete instantiable implementation of the abstract
Calendar
class. The compliant solution also introduces a wrapper class called CompositeCalendar
that provides the same overridden methods found in the CalendarSubclass
from the preceding noncompliant code example.
Code Block | ||
---|---|---|
| ||
// The CalendarImplementation object is a concrete implementation
// of the abstract Calendar class
// Class ForwardingCalendar
public class ForwardingCalendar {
private final CalendarImplementation c;
public ForwardingCalendar(CalendarImplementation c) {
this.c = c;
}
CalendarImplementation getCalendarImplementation() {
return c;
}
public boolean after(Object when) {
return c.after(when);
}
public int compareTo(Calendar anotherCalendar) {
// CalendarImplementation.compareTo() will be called
return c.compareTo(anotherCalendar);
}
}
class CompositeCalendar extends ForwardingCalendar {
public CompositeCalendar(CalendarImplementation ci) {
super(ci);
}
@Override public boolean after(Object when) {
// This will call the overridden version, i.e.
// CompositeClass.compareTo();
if (when instanceof Calendar &&
super.compareTo((Calendar)when) == 0) {
// Return true if it is the first day of week
return true;
}
// Does not compare with first day of week any longer;
// Uses default comparison with epoch
return super.after(when);
}
@Override public int compareTo(Calendar anotherCalendar) {
return compareDays(
super.getCalendarImplementation().getFirstDayOfWeek(),
anotherCalendar.getFirstDayOfWeek());
}
private int compareDays(int currentFirstDayOfWeek,
int anotherFirstDayOfWeek) {
return (currentFirstDayOfWeek > anotherFirstDayOfWeek) ? 1
: (currentFirstDayOfWeek == anotherFirstDayOfWeek) ? 0 : -1;
}
public static void main(String[] args) {
CalendarImplementation ci1 = new CalendarImplementation();
ci1.setTime(new Date());
// Date of last Sunday (before now)
ci1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
CalendarImplementation ci2 = new CalendarImplementation();
CompositeCalendar c = new CompositeCalendar(ci1);
// expected to print true
System.out.println(c.after(ci2));
}
}
|
...
[API 2006] | |
Item 16. Favor composition over inheritance | |
Design Patterns, Elements of Reusable Object-Oriented Software | |
Using prototypical objects to implement shared behavior in object-oriented systems |
OBJ01-J. Declare data members as private and provide accessible wrapper methods 04. Object Orientation (OBJ)