Versions Compared

Key

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

It is common for developers to separate the program logic into different classes or files to encourage modularity modularize code and increase re-usability. Unfortunately, this often imposes maintenance hurdles such as ensuring that the superclass does not change and in turn having to ensure that changes in superclasses do not indirectly affect subclass behavior in undesired ways.

Wiki Markup
For instance, the introduction of the {{entrySet()}} method in the superclass {{java.util.Hashtable}} in JDK 1.2, left the {{java.security.Provider}} class vulnerable to malicious deletion of entries due to absence of a security attack. The class {{java.security.Provider}} extends {{java.util.Properties}} which in turn extends {{java.util.Hashtable}}. {{Provider}} inherits the {{put()}} and {{remove()}} methods from {{Hashtable}} and adds security manager checks to each. (See \[[Guideline 1-3 Understand how a superclass can affect subclass behavior|http://java.sun.com/security/seccodeguide.html]\])The {{Provider}} maps a cryptographic algorithm name (for example, RSA) to a class that provides its implementation. The security manager 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 07|AA. Java References#SCG 07]\]

Noncompliant Code Example

This noncompliant example shows a class SuperClass that stores banking related information but delegates the security manager and input validation tasks to the class SubClass. The client application has is required to use SubClass since as it contains various authentication mechanisms as well. A new method called overdraft is added by the maintainer of the class SuperClass and the extending class SubClass is not aware of this change. This exposes the client application to malicious invocations such as ones using . One such example is of the overdraft method being used on the currently in-use object. All security checks are deemed useless in such casesthis case.

Code Block
bgColor#FFCCCC
class SuperClass {  //Main Bank The bank SuperClass class maintains all data  during program execution
  private double balance=0;
 
  protected boolean withdraw(double amount) {
	 balance -= amount;
	 return true;	 
  }
 
  protected void overdraft() {  // this method wasia added at a later date
	balance += 300; // add 300 in case there is an overdraft
	System.out.println("The balance is :" + balance);
  }
}

class SubClass extends SuperClass {	 //all users have to subclass this to proceed
  public boolean withdraw(double amount) {
    // inputValidation();
    // securityManagerCheck();
    // Login by checking credentials using database and then call a method in SuperClass 
    // that updates the balance field to reflect current balance, other details
    return true;
  }			
 
  public void doLogic(SuperClass sc,double amount) {
    sc.withdraw(amount);
  }
}

public class Affect {
  public static void main(String[] args) {
    SuperClass sc = new SubClass();  //override
    SubClass sub = new SubClass();  //need instance of SubClass to call methods

    if(sc.withdraw(200.0)) { // validate and enforce security manager check 
      sc = new SuperClass(); // if allowed perform the withdrawal
      sub.doLogic(sc, 200.0); // pass the instance of SuperClass to use it
    }
    else
      System.out.println("You do not have permission/input validation failed!");	
      sc.overdraft(); // newly added method, has no security manager checks. Beware!
    }
}

...

Typically, errors manifest when assumptions are made about the implementation specific details of the superclass. Here, the two objects are compared for equality in the overriding after() method and subsequently, the superclass's after() method is explicitly called to take over. The issue is that the superclass Calendar's after() method in turn internally uses the class Object's compareTo() method. The Consequently, the superclass's after() method erroneously invokes the subclass's version of compareTo() due to polymorphism. Since the subclass is unaware of the superclass's implementation of after(), it does not expect any of its own overriding methods to get invoked.

...

Note that each method of the class ForwardingCalendar redirects to methods of the contained class instance (CalendarImplementation), and receives back return values. This is the forwarding mechanism. This class is largely independent of the implementation of the class CalendarImplementation. Consequently, any future changes to the latter will not break CompositeCalendar which inherits from ForwardingCalendar. When CompositeCalendar's overriding after() method is invoked, it performs the necessary comparison by using the local version of the compareTo() method as required. Using super.after(when) forwards to the ForwardingCalendar which invokes the CalendarImplementation's after() method. In this case, CalendarImplementation's compareTo() method gets called instead of the overriding version in CompositeClass that was inappropriately called in the noncompliant code example, as a product of polymorphism.

Code Block
bgColor#ccccff
// 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;
  }

  public boolean after(Object when) {
    return c.after(when);
  }

  public int compareTo(Calendar anotherCalendar) {
    // ForwardingCalendar's compareTo() will be called
    return c.compareTo(anotherCalendar);
  }
}

//Class CompositeCalendar
class CompositeCalendar extends ForwardingCalendar {
  public CompositeCalendar(CalendarImplementation ci) {
    super(ci);  
  }
  
  @Override public boolean after(Object when) {
    if(when instanceof Calendar && super.compareTo((Calendar)when) == 0)
          // this will call the overridden version
          // i.e. CompositeClass.compareTo();
          // return true if it is the first day of week
      return true;
    return super.after(when); // does not compare with first day of week anymore;
                              // uses default comparison with epoch
  }
	
  @Override public int compareTo(Calendar anotherCalendar) {
     // CompositeCalendarcompareTo() will not be called now
     return compareTo(anotherCalendar.getFirstDayOfWeek(),anotherCalendar);
  }

  private int compareTo(int firstDayOfWeek, Calendar c) {
    int thisTime = c.get(Calendar.DAY_OF_WEEK);
    return (thisTime > firstDayOfWeek) ? 1 : (thisTime == firstDayOfWeek) ? 0 : -1;
  }

  public static void main(String[] args) {
    CalendarImplementation ci1 = new CalendarImplementation();
    CalendarImplementation ci2 = new CalendarImplementation();
    CompositeCalendar c = new CompositeCalendar(ci1);
    ci1.setTime(new Date());
    System.out.println(c.after(ci2)); // prints true 
  }
}

...