Posts in category .net - page 15

Security vulnerabilities are not acceptable in sample code

Earlier this week the ASP.NET article of the day linked to 4-Tier Architecture in ASP.NET with C# which I noticed suffered from both HTML and SQL injection. I promptly informed the author and the ASP.NET site (who pulled the link) but the author was rather unconcerned and wrote (after editing my comment):

Thanks for your feedback Damieng. Sql statement has been used here to make the tutorial simple, it is informed in the DAL description.

The problem is people borrowing this code may not notice the vulnerability or understand how to fix it. This isn’t the first time I’ve seen easily exploited sample code, responded and been buffed off with the it’s just sample code excuse.

Writing secure code isn’t difficult, time consuming or confusing to read.

Microsoft’s forthcoming LINQ toS QL and Entity Framework provide object-relational mapping that takes care of the SQL, as do other well-known ORM tools such as SubSonic and NHibernate.

If you must write your own data-access-layer (DAL) code use parameterized queries and not string concatenation.

When outputting values be 100% sure whether your technique will encode the values for you or not and be aware of what encoding tools are available to you.

ASP & ASP.NET’s Response.Write and <%= %> methods do NOT encode for you and you should be using HttpUtility.HtmlEncode to output data to a HTML stream.

Samples of vulnerable and secure code are in my presentation on Web Security I gave at the Guernsey Software Developer Forum a few months ago.

[)amien

Extension methods illustrated

Extension methods are a great new feature in the .NET Framework 3.5 that let you write new methods that appear to be part of existing classes without the need to subclass or modify them.

We can explain this in simple terms with an example. Here is a useful routine that takes a string and returns what it finds between two other strings that works just fine with .NET 2.0 and .NET 1.1.

public static string Between(string value, string start, string end) {
  int startIndex = value.IndexOf(start, StringComparison.CurrentCultureIgnoreCase);
  if (startIndex == -1)
    return "";
  startIndex += start.Length;

  int endIndex = value.IndexOf(end, startIndex, StringComparison.CurrentCultureIgnoreCase);
  if (endIndex == -1)
    return "";

  return value.Substring(startIndex, endIndex-startIndex);
}

If this method belonged to a static StringUtilities class then you could use it like this:

string newString = StringUtilities.Between(inputString, startingString, endingString);

The problem is knowing that the StringUtilities class within the project you are working on and until you know that IntelliSense can’t even kick in. What would be nice is to add this to the String class but of course we can’t because String is sealed and besides methods everywhere create String classes and not instances of your subclass.

What would be really cool is if Visual Studio and .NET could just realize that this method is static and takes a string parameter as it’s first parameter and let it just appear as another method on the String class and just call StringUtilities behind the scenes.

That is exactly what the extension methods in .NET 3.5 achieve.

All we need to do is put this in front of the first parameter which will let VS and the compiler know that this method should appear as if it is a method against the type of that first parameter. The method must be static and visible to the code and curiously the class itself must also be static. Our signature now appears as:

public static string Between(string <em>this</em> value, string start, string end)

To call the method we simply press . after our string and IntelliSense displays all the usual methods and properties of the String class and any extension methods it can find in your project too which now includes our Between method giving us:

string newString = inputString.Between(startingString, endingString);

Nice but bear in mind the extension method can only access the public parts of the class it will appear with – there is no privileged access to protected properties or methods that would be available with sub-classing!

[)amien

Color schemes for Visual Studio

The default syntax color scheme in Visual Studio seems to be stuck in the 16-color era so once you’ve found your perfect font you are going to need a great theme to go with it.

Here is the theme I’m currently using at home (currently on a 42″ 1900×1200 LCD TV until I can find space for my monitor) that a couple of people have asked for.

To to take full advantage of this theme you will need to download:

  • Envy Code R for the syntax font with the italics hack
  • PalmOS for the output window’s tiny text

Alternatively you could remap it to your coding font of choice (but you won’t get italics because of limitations within the Visual Studio IDE).

Screen shot of Envy Code R PR7 with HumaneStudio theme.

Observations on Microsoft MVC for ASP.NET

Anyone who’s tried to develop large complex web sites with ASP.NET has likely run into many problems covering the page and control life cycle, view state and post backs and subsequent maintainability including the difficulty in creating automated unit tests.

Microsoft, taking a cue from the popularity of Ruby on Rails and subsequent .NET related efforts such as MonoRail, are embracing the model-view-controller (MVC) pattern and developing something more suited to web development than WebForms which aimed to make web development as similar to Windows development as possible (despite the major underlying differences in architecture).

The prototype, currently named System.Web.Mvc or Microsoft.Web.Scalene depending on where you look, is headed by Scott Guthrie with both Phil Haack and Scott Hanselman involved (sounds like a dream project and team to be involved with) and a preview release (“drop”) is due within the coming weeks.

Guthrie and Hanselman presented Microsoft MVC at the ALT.NET conference which revealed some interesting details buried in the video, my rough observations and notes based on the prototype they showed follows:

Philosophy

  • Don’t repeat yourself
  • Highly extensible & pluggable
  • Use generics to achieve strong-typing without code generation
  • Good performance, fast enough for large-scale sites
  • Separation of concern for maintainability
  • Clean URLs in and out
  • Clean HTML

Extensible

  • Interfaces used extensively
  • No sealed classes
  • Plug-in points for view engines (e.g. MonoRail’s NVelocity, Brail)
  • Support for Inversion of Control (IoC) engines (e.g. Windsor, StructureMap, Spring.NET)

Compatibility

  • Runs on the .NET 2.0 CLR
  • Some helper classes require .NET 3.5 (extension methods)
  • Normal Request, Response objects (via interfaces for mocking)
  • Does not support postback form runat="server"
  • Supports MasterPages, DataBinding, CodeBehind
  • Existing .aspx’s are blocked using web.config

Visual Studio

  • Solution templates for web project and unit testing
  • Full designer & IntelliSense integration

Flow

  • Route -> ControllerFactory -> Controller -> Action -> ViewEngine -> View

Routing

  • Routes can be defined dynamically and support RegEx URL matching
  • IControllerFactory pops out the required IController
  • Routing is case insensitive by default
  • Support REST, blog engine, Jango style mappings etc. default is /controller/action/parameters

Controllers

  • FrontController style
  • IController exposes:
    • Execute(IHttpContext context, RouteData routeData)
    • IViewEngine ViewEngine property
  • Some implementations available, all with virtual methods:
    • ControllerBase (adds dispatching)
    • Controller (Populate parameters into ViewData["key"])
    • Controller (Populates parameters by making ViewData type T)
  • Attributes
    • [ControllerAction] attribute to expose methods as actions (secure default behavior by not exposing helper methods)
    • Attribute for output caching
    • [ControllerAction(DefaultAction=true)] to override default method of Index

Parameters (to the controller)

  • Automatically parsed where a TypeConverter exists
  • Future versions will support more complex serialization of types
  • Can be nullable – use null coalesce operator for defaults

View Engine

  • IViewEngine
    • IView LoadView(string viewName)
  • Implementations include:
    • WebFormViewEngine

Views

  • IView
    • virtual void RenderView(object data)
  • Implementations include:
    • ViewPage – pick up parameters from ViewData[""] in conjunction with Controller
    • ViewPage pick up parameters from ViewData as type T in conjunction with Controller

HTML

  • Clean HTML generation (have they sorted out the id mangling by MasterPages/INamingContainer?)
  • Static HTML class supports Link, PagingLinks and Url methods
  • Map to action names using Lambda expressions to ensure follows refactoring, e.g. string url – Html.Link<ProductController>(controller =>controller.Edit(4);
  • Is there a way to follow the default action?

Model/data

  • Pagination extension methods extend IQueryable for getting pages of data (skip, limit)
  • Pattern for view-update-view cycle
  • Object property to form field id mapping available and pluggable, allows
    • product.UpdateFrom(Request.Form)

Testing

  • Easy to write tests by using mock objects (request, response)
  • Unit testing framework project (NUnit, MBUnit, xUnit.NET)

Finally

  • What’s with ScottGu’s nametag, can the show’s organizers not afford anything more than a Post It note?
  • What cool software is Scott Hanselman using to do the screen-cast video/zoom/overlay/highlighting?

[)amien