Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Developers often separate program logic across multiple classes or files to modularize code and to increase re-usabilityreusability. When developers modify a superclass (during maintenance, for example), the developer must ensure that changes in superclasses preserve all the program invariants on which the subclasses depend. Failure to maintain all relevant invariants can cause security vulnerabilities.

...

This noncompliant code example relies on a class Account that stores banking-related information with no 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
bgColor#ccccff
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);   // Enforce security manager check
    System.out.println("Withdrawal successful? " + result);
  }
}

At a later date, the maintainer of the class Account added a new method called overdraft(). However, the BankAccount class maintainer is was unaware of the change. The Consequently, the client application subsequently 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
bgColor#FFCCCC
private class Account { 
  // Maintains all banking related data such as account balance
  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);   // Enforce security manager check
    if (!result) {
      result = account.overdraft();
    }
    System.out.println("Withdrawal successful? " + result);
  }
}

While this code works as expected, it adds a dangerous attack vector of attack. 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(200.0);   // No security check performed
    System.out.println("Withdrawal successful? " + result);
  }
}

...

In this compliant solution, the BankAccount class provides an overriding version of the overdraft() method that immediately fails, thereby preventing misuse of the overdraft feature. All other aspects of the compliant solution remain unchanged.

Code Block
bgColor#ccccff
class BankAccount extends Account {
  // ...
  @Override void overdraft() { // override
      throw new IllegalAccessException();
  }
}

AlternatelyAlternatively, when the intended design permits the new method in the parent class to be invoked directly from a subclass without overriding, install a security manager check directly in the new method.

Related Vulnerability: JDK 1.2 java.util.Hashtable.entrySet()

The introduction of the entrySet() method in the java.util.Hashtable superclass in JDK 1.2 left the java.security.Provider subclass class vulnerable to a security attack. The Provider class extends java.util.Properties, which, in turn, extends Hashtable. The Provider class maps a cryptographic algorithm name (for example, "RSA") to a class that provides its implementation.

Wiki Markup
The {{Provider}} class inherits the {{put()}} and {{remove()}} methods from {{Hashtable}} and adds security manager checks to each. These checks ensure that malicious code cannot add or remove the mappings. When {{entrySet()}} was introduced, it became possible for untrusted code to remove the mappings from the {{Hashtable}} because {{Provider}} did not override this method to provide the necessary security manager check \[[SCG 2009|AA. Bibliography#SCG 09]\]. This problem is commonly known as a "fragile class hierarchy" in other object-oriented languages, such as C++.

Noncompliant Code Example (Calendar)

Noncompliant Code Example (Calendar)

This noncompliant code example overrides the methods after() and 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
bgColor#FFCCCC
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(),
                     return compareDays(this.getFirstDayOfWeek(), anotherCalendar.getFirstDayOfWeek());
  }

  private int compareDays(int currentFirstDayOfWeek,
                          int anotherFirstDayOfWeek) {
    return (currentFirstDayOfWeek > anotherFirstDayOfWeek) ? 1
           1 : (currentFirstDayOfWeek == anotherFirstDayOfWeek) ? 0 : -1;
  }

  public static void main(String[] args) {
    CalendarSubclass cs1 = new CalendarSubclass();
    cs1.setTime(new Date());
    cs1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    // Date of last Sunday (before now)
    CalendarSubclass cs2 = new CalendarSubclass();cs1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    // Wed Dec 31 19:00:00 EST 1969
     System.out.println(cs1.after(cs2));   CalendarSubclass cs2 = new CalendarSubclass();
    // expected to     // expected to print trueprint true
    System.out.println(cs1.after(cs2));
  }

  // Implementation of other Calendar abstract methods
}

Such errors generally occur because the developer has depended on made assumptions about the implementation-specific details of the superclass. Even when these assumptions are initially correct, implementation details of the superclass may change without warning.

Wiki Markup
The {{java.util.Calendar}} class provides a {{compareTo()}} method and an {{after()}} method. The {{after()}} method is documented in (\[[API 2006|AA. Bibliography#API 06]\]) as follows:

The after() method returns whether this Calendar represents a time after the time represented by the specified Object. This method is equivalent to
compareTo(when) > 0
if and only if when is a Calendar instance. Otherwise, the method returns false.

...

In this case, the two objects are initially compared using the overriding CalendarSubclass.after() method. This invokes the superclass's Calendar.after() method to perform the remainder of the comparison. But the Calendar.after() method internally calls the compareTo() method, which is delegated delegates to CalendarSubclass.compareTo(). Consequently, CalendarSubclass.after() actually calls CalendarSubclass.compareTo() and returns false.

The developer of the subclass was unaware of the implementation details of Calendar.after() and incorrectly assumed that the superclass's after() method would invoke only its own methods without invoking overriding methods from the subclass. Rule "MET05-J. Ensure that constructors do not call overridable methods" describes similar programming errors.

...

Wiki Markup
This compliant solution uses a design pattern called composition and forwarding (sometimes also referred tocalled as delegation) \[[Lieberman 1986|AA. Bibliography#Lieberman 86]\], \[[Gamma 1995|AA. Bibliography#Gamma 95], 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
bgColor#ccccff
class// The CalendarImplementation extendsobject Calendaris {
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;
    }
    return super.after(when); // Does not compare with first day of week any longer;
      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
           1 : (currentFirstDayOfWeek == anotherFirstDayOfWeek) ? 0 : -1;
  }

  public static void main(String[] args) {
    CalendarImplementation ci1 = new CalendarImplementation();
    ci1.setTime(new Date());
    // Date of last Sunday ci1.setTime(newbefore Date()now);
    ci1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Date of last Sunday (before now)

    CalendarImplementation ci2 = new CalendarImplementation();
    CompositeCalendar c = new CompositeCalendar(ci1);
    System.out.println(c.after(ci2));             CompositeCalendar(ci1);
    // expected to print true
    System.out.println(c.after(ci2));
  }
}

Note that each method of the class ForwardingCalendar redirects to methods of the contained CalendarImplementation class, from which it receives return values; this is the forwarding mechanism. The ForwardingCalendar class is largely independent of the implementation of the class CalendarImplementation. Consequently, future changes to CalendarImplementation are unlikely to break ForwardingCalendar and are also unlikely to break CompositeCalendar. Invocations of the overriding after() method of CompositeCalendar perform the necessary comparison by using the CalendarImplementation.compareTo() method as required. Using super.after(when) forwards to ForwardingCalendar, which invokes the CalendarImplementation.after() method as required. As a result, java.util.Calendar.after() invokes the CalendarImplementation.compareTo() method as required, resulting in the program correctly printing true.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ02-J

medium

probable

high

P4

L3

Automated DetectionDetection

Sound automated detection is not currently feasible.

Related Vulnerabilities

The introduction of the entrySet () method in the java.util.Hashtable superclass in JDK 1.2 left the java.security.Provider subclass class vulnerable to a security attackSound automated detection is not currently feasible.

Related Guidelines

Secure Coding Guidelines for the Java Programming Language, Version 3.0

Guideline 1-3. Understand how a superclass can affect subclass behavior

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c9c5ff64e3430883-37f59c32-49f04b3b-b0148296-90ffae7daedc8f8dbdd26fd8"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

[Class Calendar

http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6a53fe0bf6b2f01d-885e1f3a-42a747c9-827b82a0-31b2e3b34b72e38d3640a92b"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. Bibliography#Bloch 08]]

Item 16: ". Favor composition over inheritance "

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="21ad6b3e35c30b99-20b5d2dd-4d664bda-b7ebb699-b0d42a54c577ef009ae6e6a5"><ac:plain-text-body><![CDATA[

[[Gamma 1995

AA. Bibliography#Gamma 95]]

Design Patterns: , Elements of Reusable Object-Oriented Software

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6e93e4d3b3f887e4-85ec6c75-456d43ed-8eabad27-3f5189c6b30cd348ef967262"><ac:plain-text-body><![CDATA[

[[Lieberman 1986

AA. Bibliography#Lieberman 86]]

Using prototypical objects to implement shared behavior in object-oriented systems

]]></ac:plain-text-body></ac:structured-macro>

...