Cross Site Scripting (XSS) Attacks, SQL Injection and ASP.NET

“The biggest challenge to developing secure applications is that most programmers don’t know they’re writing insecure applications. Let’s look at a simple example, a forum-type application. However, any application that displays data entered by a user is a potential target.“ –Brad McCabe, XSS Happens


For an introduction to securing ASP.NET sites, check out Dino Esposito’s article “Take Advantage of ASP.NET Built-in Features to Fend Off Web Attacks“.



Dino summarizes the most common types of Web attacks and describes how Web developers can use built-in features of ASP.NET to increase security.


Perhaps one of the most dangerous and overlooked attacks is the SQL Injection attack.  It’s very easy to overlook how an attacker can exploit seemingly harmless SQL code, especially if a developer’s experience and understanding of SQL is less than expert.  There are a number of articles available, including:



Stop SQL Injection Attacks Before They Stop You (MSDN Magazine, Sep 2004)
source: http://msdn.microsoft.com/msdnmag/issues/04/09/SQLInjection/default.aspx
This article discusses:



  • How SQL injection attacks work
  • Testing for vulnerabilities
  • Validating user input
  • Using .NET features to prevent attacks
  • Importance of handling exceptions




Preventing SQL Injection Attacks
source: http://www.wwwcoder.com/main/parentid/258/site/2966/68/default.aspx


Keep your code secure against intruders. In this article we provide examples of SQL injection attacks and how you can write code to prevent them. Stop people from getting information from your database.


Are you still vulnerable to a SQL Injection attack?
source: http://www.spidynamics.com/whitepapers.html


SQL Injection can deliver total control of your server to a hacker giving them the ability to read, write and manipulate all data stored in your backend systems!
Despite being remarkably simple to protect against, there are an astonishing number of production systems connected to the Internet “fixed” the problem by hiding error data from the users but were left vulnerable to this type of attack!


Advanced SQL Injection In SQL Server Applications
source: http://www.nextgenss.com/papers/advanced_sql_injection.pdf


This document discusses in detail the common ‘SQL injection’ technique, as it applies to the popular Microsoft Internet Information Server/Active Server Pages/SQL Server platform. It discusses the various ways in which SQL can be ‘injected’ into the application and addresses some of the data validation and database lockdown issues that are related to this class of attack. The paper is intended to be read by both developers of web applications which communicate with databases and by security professionals whose role includes auditing these web applications.


(more) Advanced SQL Injection
source: http://www.nextgenss.com/papers/more_advanced_sql_injection.pdf


This paper addresses the subject of SQL Injection in a Microsoft SQL Server/IIS/Active Server Pages environment, but most of the techniques discussed have equivalents in other database environments. It should be viewed as a “follow up”, or perhaps an appendix, to the previous paper, “Advanced SQL Injection”.


The paper covers in more detail some of the points described in its predecessor, providing examples to clarify areas where the previous paper was perhaps unclear. An effective method for privilege escalation is described that makes use of the openrowset function to scan a network. A novel method for extracting information in the absence of ‘helpful’ error messages is described; the use of time delays as a transmission channel. Finally, a number of miscellaneous observations and useful hints are provided, collated from responses to the original paper, and various conversations around the subject of SQL injection in a SQL Server environment.  


One method to prevent SQL injection attacks is to use parameterized SQL queries.  This technique can be used for Access as well as SQL Server, and any other DB system that supports parameterized queries.  The example below demonstrates .NET with SQL Server, but the underlying examples should be easily adapatbale to whatever system you’re using.



Using parameterized SQL queries
source: http://www.uberasp.net/getarticle.aspx?id=46


Save yourself from SQL injection attacks and other nasty problems by passing along data in parameters.


The Curse and Blessing of Dynamic SQL
source: http://www.sommarskog.se/dynamic_sql.html


In this article I will discuss the of use dynamic SQL in stored procedures in MS SQL Server, and I will show that this is a powerful feature that you should use with care. I first discuss why we use stored procedures at all, before I explain the feature as such. I then look at the conflicts between the virtues of stored procedures and the effects of dynamic SQL. I also point to the common security issue known as SQL injection. I then move on to suggest some good coding practices. I conclude by reviewing a number of cases where dynamic SQL often is suggested as a solution, both where dynamic SQL is the way to go, and where it is a poor choice. For the latter cases, I suggest alternative strategies.


Dynamic Search Conditions in T-SQL
source: http://www.sommarskog.se/dyn-search.html


This article details the ways to use dynamic SQL in a stored procedure for searching Sql Server databases.  Written by a Microsoft MVP, there are a few topics that will be over the head of beginnning SQL programmers, but this is still an important read.  This is a follow-up to “The Curse and Blessing of Dynamic SQL“.


It is important to have a full understanding of all the risks that your web application faces.  For this, Microsoft has released a guide for developers and administrators.  You can purchase the guide from Amazon by clicking the links below, or click this link to download for free from Microsoft.













cover Improving Web Application Security: Threats And Countermeasures
This guide gives you a solid foundation for designing, building, and configuring secure ASP.NET Web applications. Whether you have existing applications or are building new ones, you can apply the guidance to help you make sure that your Web applications are hack-resilient.
cover Web Applications (Hacking Exposed)
This work covers all major Web applications platforms and focuses on vulnerabilities across different programming languages, including PHP, ASP, Perl, JavaScript and Java. It includes examples of security attacks and countermeasures in Web application software.
cover Hacking Exposed: Network Security Secrets & Solutions, Fourth Edition (Hacking Exposed)
This text unveils the methods hackers use to break into systems, networks, and software, and suggest steps administrators can take to secure their computers at the different layers. The fourth edition covers the latest hacking methods and adds a chapter on 802.11 wireless networks. The DVD-ROM contains a video presentation with PowerPoint slides.

Is Dynamic SQL in Your Stored Procedures Vulnerable to SQL Injection?

We all should be familiar with the fact that concatenating user input directly into SQL statements is an open invitation to an SQL Injection attack.  Code such as
MySql = “Select * from Orders where Customer ID='” & txtCustomerId & “‘”
should be avoided.  If you need some more background information on SQL Injection attacks, I am building a reference at http://www.rjdudley.com/blog/CrossSiteScriptingXSSAttacksSQLInjectionAndASPNET.aspx
.  This reference will be updated as time goes on–there are a few good references now, and I’ll post update notices to the security section of this blog.


The recommended practice for avoiding SQL Injection attacks is to use parameterized queries or stored procedures (sprocs), where user input is passed as parameters.  Since information in parameters is not treated as executable code, any SQL code conatined in the user input is rendered harmless.  Or is it?  This depends on what you do with that input inside of your sproc.


One of the common functions on a web site is querying a data store.  In advanced searches (those with more than a single input), it would be infeasible to create and mainatin an sproc for every combination of search critera.  Instead, one practice is to create an sproc that dynamically creates the SELECT statement based on the parameters passed to it.  Typically, there is an input parameter for each input on the search form, which is rendered optional by adding “=NULL” after the parameter declaration (e.g., @orderId int=NULL).  Then, the sproc uses a series of statements such as


IF @orderId IS NOT NULL
 select @sql = @sql + ‘ AND order_id=’ + @orderId
 
to generate the complete SQL statement.  At the end of the sproc, the EXECUTE statement is used to query the database using the dynamically generated SQL statement.


I remember what a revolutionary concept dynamic SQL in an sproc was for me when I was learning to write SQL.  It opened up a whole new way of writing SQL code and handling advanced searches on my websites.  But did you catch the security problem in the previous SQL statement?  I didn’t at first, and in fact, I’ve been making this same security mistake for some time now.  It wasn’t until I finally listened to Kim Tripp on DotNetRocks that I realized the problem (download the show from http://www.dotnetrocks.com/default.aspx?showID=75), and fortunately I only have a few sprocs to rewrite and fix this problem.


Look carefully at the statement again.  It looks like the parameter is being used in the SQL statement, but in reality, the parameter’s value is being concatenated to the SQL statement.  The technique demonstrated above is no better than the technque we dismissed in the first paragraph.


After listening to Kim’s show, I did some digging around, and found an excellent reference on how to handle dynamic SQL in search queries at http://www.sommarskog.se/dyn-search.html.  In this article, Microsoft Sql Server MVP Erland Sommarskog details ways to use dynamic and static SQL to perform searches that have a number of possible combinations of inputs.


As Erland shows us, the correct way to use dynamic SQL in the situation I presented above is to concatenate another parameter into the SQL statement, as so:


IF @orderId IS NOT NULL
 select @sql = @sql + ‘ AND
order_id=@xorderId’


We then create a parameter list of these second parameters, as so:


SELECT @paramList = ‘@xorderId’


To finally execute the query, we execute a system sproc named sp_executesql.  As Erland states:



sp_executesql is a system procedure with a very special parameter list. The first parameter is a parameterized SQL statement. The second parameter is a parameter-list declaration, very similar to the parameter list to a stored procedure. And the remaining parameters are simply the parameters in that parameter-list parameter.


Our final statement would end up looking like:


EXECUTE sp_executesql @sql, @paramList, @orderId


And with this technique, our query is safe from malicious user input.  This whole process is outlined in detail in Erland’s article.


Since writing sprocs as outlined in Erland’s article can be tedious, I created a CodeSmith template that will do the work for you.  You only need to input the table you wish to query, and CodeSmith will generate a complete sproc for you.  You can then edit the sproc down, since it will include every column in the table.  You can find the template at http://www.ericjsmith.net/codesmith/forum/default.aspx?f=9&m=4346.


<update 2005-07-06: fixed DNR show link>

Pre-configuring Windows 2003 Server for SharePoint Portal Server 2003

After you’ve installed Windows Server 2003, you need to add the role of Application Server to your server.  This will configure IIS, SMTP, etc. and you can optionally choose to configure FrontPage 2002 Server Extensions and the ASP.NET Framework.  At this point, do configure the ASP.NET Framework, but do not configure FPSE 2002, even if you are going to use FrontPage to customize your portal!  You don’t need the FPSEs on Win2K3 to customize SPS 2003.


If you did happen to install the FPSEs at this step, your Default Web Site will be extended with FPSEs, and appear to the SharePoint Central Administration to be a site already in production (which requires a different upgrade path).  You won’t be able to extend the Default Web Site to use SharePoint unless you remove the FPSEs.  You’ll know when you get this error message:



Setup has detected that your default virtual server is running FrontPage 2002 Server Extensions. To continue Setup and upgrade your default virtual server later, click OK. To exit Setup and move data from your default virtual server, click Cancel. For more information about moving data from FrontPage 2002 Server Extensions, see the Administrator’s Guide for Windows SharePoint Services.

Chances are, clicking OK isn’t going to do a darn thing.  There’s a Microsoft KB article that deals with the problem if you’ve already caused it:


“Virtual Server Is Running FrontPage 2002 Server Extensions” Message When You Run Windows SharePoint Services Setup or When You Try to Extend the Virtual Server with Windows SharePoint Services


 

Happy Trails Ken “The Feb”

Ken LeFebvre, our Evangelist/Champion of some flavor, is dust in the wind again.  Today is his final event in Bethlehem, PA.  Ken was the guy who originally sowed the seed of BADNUG, and helped get us pointed in the right directions at the very beginning.  I know we’ll miss you, Ken.  Now that you have some free time, how about presenting at BADNUG?  We are right on the way to Ohio…

iTunes 4.9 With Podcast Support

Sweet!



With iTunes 4.9 you can now browse, find, sample and subscribe to thousands of free podcasts — radio shows delivered over the Internet to your computer — then sync them to your iPod and listen anytime, anywhere.


Now you can easily find and subscribe to free podcasts from one of the largest directories on the web — the iTunes Podcast Directory. Featuring over 3,000 free podcasts from favorites such as ABC News, Adam Curry, ESPN, KCRW and more, the Podcast Directory puts all the best podcasts in one place. Once you subscribe to a podcast, iTunes automatically checks for updates and downloads new episodes to your computer. When you sync your iPod, all your podcasts come along for the ride. You get on-demand radio, delivered automatically. All from the world’s best digital jukebox.


More at http://www.apple.com/itunes/

Jimmy Buffett – Never Play In PNC Park Again

Last night was probably the worst Buffet show I’ve ever seen (this made 7 or 8 for me).  To start with, it took over an hour just to get through the gates at PNC Park (arguably the best stadium for baseball).  A spokeswman was quoted in an article in today’s Post Gazette saying the crowd thronged the entrances just before the show.  I’m not sure where this woman was between 4 and 6, but that crowd was huge long before “just before the show”, and PNC’s pathetic crowd moving ability was partly to blame.  All the tickes were printed saying enter at the home plate entrance, and PNC made absolutely no effort to indicate the left field gates were open.  Next year, go back to Starlake (our outdoor amphitheater, similar to Blossom or Ravinia, although much larger than Ravinia), who can actually move a crowd.  Numerically, the show was a sell-out, but there were a lot of tickets for sale before the show.  Because of the way the stage was placed in the park, none of the far outfield seats were sold.  Even though there were seats on the field, the total crowd in attendance shouldn’t have been siginficanly more than a sell out Pirates game, and PNC should have been able to move the crowd better.


Speaking of stage placement, Jimmy was some 400 feet or so from where we were, and looked like a little green bug.  The video monitors were delayed, so the show looked like a bad Godzilla overdub on those.  $100 tickets were way too overpriced to watch a little green bug, or a big head out of sync with the band.  There’s no lawn mojo in cramped stadium seat rows, so dancing with the wifeys was just about out of the question.


Finally, why does a guy who has over 20 albums need to make half the second set covers of other songs?  We could have done without an OK cover of a lousy James Taylor song that was the inspiriation for your worst book.  Part of the second act was so slow that the best part was watching the River Patrol move all the boats away from the Clemente Bridge so the after-concert fireworks could be launched safely.


Jimmy, go back to Starlake and play your own music.

Building Websites with VB.NET and DotNetNuke 3.0

Daniel Eagan’s (from DotNetDoc) book Building Websites with VB.NET and DotNetNuke 3.0 is now shipping.  The publisher is also offering a free chapter and chapter summaries.



A practical guide to creating and maintaining your own website with DotNetNuke, the free, open source evolution of Microsoft’s IBuySpy Portal Create and manage your own website with DotNetNuke Customize and enhance your site with skins and custom modules Extend your site with forums and the best of third-party add-ons Complete coverage of setup, administration, and development


 


 


 

Free DotNetNuke Chapter From “Building Websites With VB.NET and DotNetNuke 3.0”

Packt Publishing is offering a free chapter on module development from Building Websites With VB.NET and DotNetNuke 3.0, as well as chapter summaries for the rest of the book.  Building custom modules for DNN has a learning curve, so this is a valuable chapter in itself.  Since this is probably the most complicated aspect of working with DNN, the free chapter will give you an idea of how good the rest of the book is.

The Assembly Version ( [ASSEMBLYVERSION] ) does not match the Database Version ( [DATABASEVERSION] )

When upgrading the BADNUG site, I encountered the following error:



DotNetNuke Upgrade Error
The Assembly Version ( [ASSEMBLYVERSION] ) does not match the Database Version ( [DATABASEVERSION] )


ERROR: Could not connect to database.


The stored procedure ‘dbo.GetPortalAliasByPortalID’ doesn’t exist.


I found a solution that works at http://forums.asp.net/958251/ShowPost.aspx.  What worked for me was changing UseDnnConfig to false.  Once I made that change, the upgrade completed normally.

Free Certificates for Encrypting E-mail

Microsoft MVP Susan “The SBS Diva” Bradley gives a short overview about sending encrypted e-mails.  In her post, she says you have to purchase a digital certificate.  From some certificate authorities, you may have to do so, but Thawte offers free certificates for e-mail through their Web of Trust program.  When your certificate is issued, the name on the certificate is “Thawte Freemail Member”.  In order to have your name appear on the certificate, you need to get yourself notarized.  Basically, you meet up with a Thawte notary (I am one), who looks at two forms of identification and assigns you points.  You need 50 points to be notarized (I can assign up to 35, the maximum allowed), and then your certificates will contain your name.  There’s more information at the WOT site at http://www.thawte.com.wot.