Archive for the ‘Development’ Category

SQL Injection Prevention: ID’s in the Query String

In the past year or so, I’ve helped solve three or four problems with data on a web site site being inserted/changed through SQL injection. Not a fun thing to have happen.

I used to think of SQL injection attacks coming through web forms, where people try to enter things into forms that cause the attacks. This can be a very dangerous type of attack, because in some cases, it will allow the attacker to log in as an administrator of the web app, therefore being able to see/do whatever they want in the application.

However, the attacks I’ve seen have all come through query strings, on pages that have URL’s like webapp.myserver.com/showpage.cfm?ID=8 What they do is simply add a semicolon ( ; ) to the end of the URL, then append SQL commands to it. If the application simply uses the query string variable “ID” to build a SQL command, the application is vulnerable.

The cases I’ve worked on have all been old, legacy code, and have been in two or three different programming languages. Bad code can be written in any language. These applications were written back when we didn’t hear much about SQL injection, therefore application developers didn’t always practice good programming practices. In fact, one of the applications I helped fix recently was originally written by a commercial firm that did some programming for one of our departments.

In each case, the way I fixed the problem was to simply convert the ID to an integer, then used this integer to build the where clause of the SQL command. By doing so, real requests for the web page work just fine, and one of three things happen the bogus hits come in:

  1. The server throws an error because the ID can no longer be converted to an integer.
  2. The conversion returns a default integer (such as zero), in which case you probably don’t have a ID=0 in your database, giving some kind of page not found message.
  3. The first part of the string is converted, up until it finds a character that is not a digit. In the example above, it would return the page where ID=8.

In all these cases, converting the query string variable ID to an integer, prevents the SQL injection attacks from being successful because it doesn’t pass the whole ID string along to the database.

Advertisements

Server Side vs Client Side Comments in ASP.NET

Last week, I was asked to make a change to the name of a channel (folder) in an application using our Content Management Server (CMS). After I did this, I went to their home page and received the dreaded yellow error screen of ASP.net.

After making this change, the application was throwing a null reference exception from a user control that was within comments in the .aspx file. This user control was trying to do something with the old channel name, but was no longer able to find it.

But why was this an issue at all? After all, the code was commented. Yes it was, however it was using client side (HTML) comment “<!– HTML comment –>“, instead of an ASP.NET comment “<%– ASP.NET comment –%>“.

Because “<!– –>” is a client side comment, the browser does not display whatever is in the comment, however the server still handles this code and sends it to the browser. If you have things like server controls, users controls, etc in this type of comment, the server still runs these controls.

As an example, consider this simple aspx file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Test Page</title>
</head>
<body>
  <!-- HTML Comment -->
  <%-- ASP.NET Comment --%>
  <p>Test</p>
</body>
</html>

When you do a view source in your browser on this page, you get:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test Page</title>
</head>
<body>
  <!-- HTML Comment -->
  <p>Test</p>
</body>
</html>

Notice that the HTML comment does get sent to the browser, however the ASP.NET comment does not. The server ignores everything embedded in the the ASP.NET comment.

On the page I was looking at last week, this caused two major problems. First, we were sending code to the client that wasn’t really necessary. What was commented out was HTML code that the browser would not display, therefore it added a little to the download time for the page.

A bigger problem was this section of code had a couple of user controls in it, and these user controls took a few seconds to run each time this home page was hit. Therefore this was a very slow page to load, and the slowness was caused by the server generating an HTML comment which the user never saw. When I changed this, the load time for the page was greatly improved.

The moral of the story is simple. If you are writing a comment that should be seen in the HTML code, then go ahead and use the client side HTML comment code. However, in many cases, you don’t need/want the user to be able to see the comments. For these cases, you should use the ASP.NET comment code “<%– –%>”, which will cause the server to skip this code. In certain cases, this small change can have a dramatic effect on the performance of your web page.

For more information on this, see Scott Guthrie’s post: Tip/Trick: User Server Side Comments with ASP.NET 2.0

CASE Statement in SQL Query

I’ve used SQL to varying degrees for a number of years. However, one of the features I’ve recently learned about is the CASE statement. For some reason, I missed this powerful feature when I studied SQL.

When would you use the CASE statement? I use it when writing stored procedures when I want to have optional input parameters. Consider this simple stored procedure:

ALTER PROCEDURE [dbo].[GetRooms]
(
@roomID int = 0,
@color varchar = ''
@type varchar =''
)
AS
BEGIN
SELECT roomID, roomName, roomColor, roomType, roomWidth, roomLength, roomheight
FROM tblRooms
WHERE
roomID = CASE @roomID WHEN 0 THEN roomID ELSE @roomID END
and roomColor = CASE @color WHEN '' THEN roomColor ELSE @color END
and roomType = CASE @type WHEN '' THEN roomType ELSE @type END
ORDER BY roomName
END

With this one Stored Procedure, we have a lot of options for what is returned, depending on what parameters we include in the call.

EXEC GetRooms – Returns all the rooms in the database.
EXEC GetRooms @roomID=3 – Returns the room with ID of 3
EXEC GetRooms @color=’blue’, @type=’kitchen’ – Returns all the kitchens that are blue

With the optional parameters, this one stored procedure can be used in a number of different scenarios. Using this technique, I once replaced about a dozen stored procedures in a database with just one. How cool is that!

HtmlEncode in ASP.NET

I keep forgetting where to find HtmlEncode when working in .NET. I end up going to Google and doing a couple searches before I find the right namespace to include. Hopefully now I’ll remember to look at my blog rather than Google:-)

HtmlEncode does exactly what it sounds like it should. It takes a string value as a parameter, and returns an escaped string.

using System.Web;

private static string ReturnEncoded()
{
	return (HttpUtility.HtmlEncode("<br />"));
}

This function would return “&lt;br /&gt;”. Not a real useful function, but is shows how to use HtmlEncode.

This same location also has HtmlDecode, UrlEncode, and UrlDecode.

Web Forms Should Inherit a Custom Class

When doing a web application in .NET, I like to create a custom class that inherits from System.Web.UI.Page I usually call this class “MyWebPage”. In some (most) cases, this class doesn’t add any functionality, it’s just a wrapper. However, when you need to do certain things in your web app, this wrapper is invaluable.

When creating web forms, the first thing I do is change the code behind file, so it inherits from “MyWebPage” rather than default System.Web.UI.Page. This gives the new web form whatever functionality is built into “MyWebPage”.

When is this useful? Previously, I talked about dynamic master pages in a CMS application. By overwriting the PreInit method in “MyWebPage” to include the functionality for dynamic web pages, any new template that inherits “MyWebPage” will automatically receive this functionality. The alternative would be to override the PreInit method in every new template.

I first heard about making this page wrapper when Paul Sheriff gave a talk at an Iowa .Net User Group meeting. The example he gave was that you have a large .NET application. On Friday morning, your boss tells you that by Monday, the web application should log every time a page is hit, this log would be something above and beyond what the web server can log. Without the wrapper, you would have to edit every web form in the application, possibly hundreds of files. With the web forms inheriting from your wrapper class, you simply change this one class, and you enjoy the weekend.

Since then, I’ve heard this talked about on .NET Rocks, and also in this blog post by Brian Mishler.

Dynamic Master Pages

An important thing to remember about master pages is that you can have more than one in any given web application. For example, if some pages in your web application will be two columns, and some will be three, you might build two master files. Then, when you create the web forms, you select which master file to use.

A powerful use for multiple master pages in an application is to dynamically assign them when the page loads. Here is an example of code to do dynamic master pages. The example on this page is giving a different master page if the client is using a browser on Windows CE. The thing to remember about dynamically assigning master pages, is that it needs to be done very early in the page life cycle, in the PreInit method.

Imagine a situation where you want to host a web application for many different entities, for example, I recently watched a demonstration of a hosted 4-H enrollment application. Every state wants to have their own look to the application. An easy way to do this is by using dynamic master pages, and assigning them based on the username of the person that is logged in.

A place where we are using dynamic web pages extensively is in our Content Management Server (CMS). We have one set of templates that are used for 18 different sites. Each of these sites have their own branding and navigation, although many of them are similar. When we set up the sites in CMS, we set a custom property that tells it what master file to load. This allow us to provide a huge amount of customization by only modifying the two files that make up the master page. Our Midwest Grape and Wine Industry Institute site, and our Bioeconomy site are using this CMS application, and have quite different looks.

We are currently working on a project for community foundations, that will have a number of sites for individual community foundations. These sites will use the same CMS application as the ISU extension sites referenced above. However, they will have a completely different look and feel. This project was possible because we are dynamically assigning the master pages as the page loads.

wine2.png bioeconomy2.png hardin2.png

Here are thumbnails of the three web sites referenced above that are using this single CMS application. The different looks is a result of the dynamic master pages mentioned above.

Master Pages in .NET 2.0

One of the big improvements with .NET 2.0 is master pages. A master page is a template that you use to build the structure of your web pages. You use it to do things like branding, top navigation, side navigation, footer, etc. Anything that you want repeated on every page can be placed in a master page.

Before .NET 2.0, we would build things in user controls, and add the user controls to our pages. This worked reasonably well, until you wanted to add a new feature, such as a search box to all your pages. If you didn’t have a suitable user control on your pages, you’d create a new user control, then add that to every page in your web application.

With .NET 2.0 or later, you can add the search box to the master page, and every page using that master page will automagically get the search box. This can save a huge amount of time. I learned this a few weeks ago, when I had to modify project that was created in .NET 1.1.

On master pages, in addition to the branding and navigation elements, you provide one or more content ares. These content areas are where the individual pages are responsible for populating the content. However, the content page does not have to populate every content area, you can pick and choose which content areas to use. For example, if your master page has an area for a sidebar, but your page doesn’t have content for the sidebar, you simply leave that area off your content page. It is an error, however, when your pages implement a content area that is not on the master page.

SharePoint makes extensive use of master pages, so this is a concept I will continue working with and expanding my knowledge.

Writing Atom Feeds in .NET Using Argotic

This week, one of my projects entailed generating some Atom feeds from web pages produced in our Content Management System. Because our CMS doesn’t generate feeds automatically, I used a package called Argotic Syndication Framework, by Brian Kuhn, to help build the feeds in a .NET program.

Argotic is a very well designed and implemented framework that reads and writes both Atom and RSS feeds. It also handles popular extensions to feeds, such as the iTunes extensions. Very nice having a single framework that handles both major feed formats!

I discovered a minor problem when I tried to validate the feeds using the Feed Validator. Although I didn’t see anything in the Atom Specifications about it, the validation failed because the <entry> items were not the last thing in the feed. I downloaded the source code for Argotic, to change the output order, which was pretty easy to accomplish.

I also posted a bug report at the Argotic Syndication Framework web site at about 10:30 pm Monday. By 9:00 AM Tuesday, there were 2 responses from Brian, one of which said it was fixed for the next release. Wow, great service Brian! Especially for a product that is freely available.

I definitely recommending using Argotic to work with feeds in .NET.

Web Controls on dnrTV

One of the projects I’ve been thinking about for a long time is a toolbox of controls that we can reuse. I’ve had a hard time trying to explain what that would look like, but I definitely know it’s the direction that we need to go. Not only will it be good for us, but it could provide a mechanism for sharing code with other states.

A couple of weeks, I decided that it would be easier to explain if I had something tangible to show people. As a first step, I fired up episode #1 of dnrTV. In this episode, Miguel Castro builds a “contact us” web control that can be dropped into any ASP.NET web page where you want a contact us form.

As he went though the process, I’d stop the video to duplicate his steps by writing my own web control. Mine was much simpler in function, it provides a search text field and button, that will interact with our Google search appliance. I learned a lot by watching a couple minutes, then doing whatever he was talking about.

There were two more episodes on dnrTV where Miguel talked about web controls, both of which talk mostly about adding design time features to the control, meaning how the control acts in Visual Studio. These episodes are number 2, and number 31.

The best thing about these three episodes is that they help me think about how we can reuse code from one product to another. I now have a “Google Search Appliance” control that I can show. It takes a little more work initially to write the code with enough flexibility and configurations to be useful in multiple projects. However, done correctly, it will save time in the long run.

I really like the dnrTV videos. In fact, as I think about holding regular developer meetings, I’m thinking we might want to use them as the various topics. We’d watch and discuss the episodes that have topics of interest. Is this a good idea?

The people that do dnrTV, started by doing weekly podcasts at DotNetRocks. These are highly recommended for .NET developers as well.

Date Field Validation

In .NET, it is really easy to check whether a user is entering a date into a form field, although it’s not necessarily obvious how to do so. What you need to do is include a CompareValidator in your web form. The code would look like this:

<asp:TextBox ID="txtBirthDate" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
	ErrorMessage="CompareValidator" ControlToValidate="txtBirthDate"
	Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>

The three important properties that you need to set in the CompareValidator are:

  1. ControlToValidate – This is the ID of the Textbox
  2. Operator – Default is “Equal”, need to change to DataTypeCheck
  3. Type – Default is String, set to Date

This will cause the validator to return the error message when an invalid date is entered. It will accept dates such as “4/18/2004”, “9/12/95” and “02/29/2004”, however would cause the error message to be displayed on “14/14/2000”, “02/29/2005”, and “January 1, 2000”. I’d like to see it accept the last one, however, the date should be in the format mm/dd/yyyy, be sure to tell the users to enter this format.

Of course, to be semantically correct, you’d want to give your Textbox a label on the form, and the CompareValidator a more descriptive error message. Also, be sure to enable server side validation, see “Server-Side Validation“.

This tip came from Peter Blum, on dnrTV. Peter has done a ton of work with validation in .NET. His product, Professional Validation and More looks very promising.