OOP and Security

A new article has been posted at http://www.codemilitia.com/blogs/tobin.titus/articles/10.aspx

(begin excerpt)

A brief discussion broke out at work today surrounding collections and how they should be exposed in a client class. The proper OO way to expose a collection as a property is to provide a get accessor only. The get accessor should most likely always return an instance. Here is an example:

public class GoodClient {
   private TrustedCollection _data = null;
   public GoodClient() {}
   public TrustedCollection Data {
      get {
         if( _data == null ) {
            _data = new TrustedCollection();
         }
         return _data;
      }
   }
}

The get accessor checks for a null private member and creates a new instance if needed. This follows good encapsulation design.

So what does this have to do with security?

Lets consider that your collection’s “Add” and “Insert” methods might do some data validation on the parameters passed to the method before adding an item to the collection. Let’s look at an example of a class that does some validation:

public class TrustedCollection : CollectionBase {
   public TrustedCollection() { }
   public virtual void Add( DateTime date ) {
      DateTime now = DateTime.Now;
      DateTime is21 = new DateTime( now.Year - 21, now.Month, now.Day );
      if( date > is21 ) {
         throw new ArgumentException(
            "The person must be 21 years old.", "date" );
      }
      List.Add( date );
   }
}

Remember, the first rule of application security is that all input is evil. If your client depends on this validation to occur, it had better not provide a set accessor. Let’s look at how we can defeat this by using an inherited class and a set accessor.

(end of excerpt)

Continue

Be Sociable, Share!

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Post Navigation