ViewStateUserKey, ValidateAntiForgeryToken, and the Security Development Lifecycle

Last week Microsoft published the 5th revision to the SDL.  You can get it here: http://www.microsoft.com/security/sdl/default.aspx.

Of note, there are additions for .NET -- specifically ASP.NET and the MVC Framework.  Two key things I noticed initially were the addition of System.Web.UI.Page.ViewStateUserKey, and ValidateAntiForgeryToken Attribute in MVC.

Both have existed for a while, but they are now added to requirements for final testing.

ViewStateUserKey is page-specific identifier for a user.  Sort of a viewstate session.  It’s used to prevent forging of Form data from other pages, or in fancy terms it prevents Cross-site Request Forgery attacks.

Imagine a web form that has a couple fields on it – sensitive fields, say money transfer fields: account to, amount, transaction date, etc.  You need to log in, fill in the details, and click submit.  That submit POST’s the data back to the server, and the server processes it.  The only validation that goes on is whether the viewstate hasn’t been tampered with.

Okay, so now consider that you are still logged in to that site, and someone sends you a link to a funny picture of a cat.  Yay, kittehs!  Anyway, on that page is a simple set of hidden form tags with malicious data in it.  Something like their account number, and an obscene number for cash transfer.  On page load, javascript POST’s that form data to the transfer page, and since you are already logged in, the server accepts it.  Sneaky.

The reason this worked is because the viewstate was never modified.  It could be the same viewstate across multiple sessions.  Therefore, the way you fix this to add a session identifier to the viewstate through the ViewStateUserKey.  Be forewarned, you need to do this in Page_Init, otherwise it’ll throw an exception.  The easiest way to accomplish this is:

void Page_Init (object sender, EventArgs e) 
{ 
	ViewStateUserKey = Session.SessionID; 
}

Oddly simple.  I wonder why this isn’t default in the newer versions of ASP.NET?

Next up is the ValidateAntiForgeryToken attribute.

In MVC, you add this attribute to all POST action methods.  This attribute requires all POST’ed forms have a token associated with each request.  Each token is session specific, so if it’s an old or other-session token, the POST will fail.  So given that, you need to add the token to the page.  To do that you use the Html.AntiForgeryToken() helper to add the token to the form.

It prevents the same type of attack as the ViewStateUserKey, albeit in a much simpler fashion.

Visual Studio Output Window Auto-Scrolling

Just a quick one here.

Have you ever been using the output window in Visual Studio, scrolled up, and then lost the auto-scroll functionality?  It’s really annoying when you have a thousand things coming out through the likes of Debug.Write, or even if it’s just a massive build.

To re-enable autoscrolling, while in the output window just hit CTRL+END.

Kinda wished I knew that a year ago…

How UAC Actually Works

This post has had a few false starts.  It’s a tough topic to cover, as it’s a very controversial subject for most people still.  Hopefully we can enlighten some people along the way.

From a high level perspective, the UAC was developed to protect the user without necessarily removing administrative privileges.  Any change to the system required a second validation.  On older versions of Windows, an application running with administrative credentials could change any setting on the box.  Viruses and malware became rampant because of this openness, given that the average user had administrative credentials.  Most average users balked at the idea of having a limited user account, so Microsoft came up with an alternative for the new OS, Vista – a second form of validation.  You told the computer you wanted to make a change, it asked “are you sure?” 

Logically it makes sense.  Consider an instance where a devious application wanted to change some setting, and because Windows wanted to verify it’s ok to make this change it asked “are you sure?”  If you responded no, the change didn’t happen.  Simple enough.  However, here we start running into issues.  There are three perspectives to look at. 

First, the end user.  Simple changes to basic settings required validation.  This annoyed most of them, if not all of them.  They didn’t care why it was asking, they just wanted to delete shortcuts from their start menu.  Their reaction: turn off UAC.  Bad idea, but security loses when it comes to usability in the case of the end user.

Second, the irate IT Pro/Developer.  Most people working in IT make changes to system settings constantly.  Given that, the UAC would be seen many times in a day and it would, for lack of a better word, piss that person off.  They didn’t care what security it provided, it was a “stupid-useless-design” that shouldn’t have been created.  Their reaction: turn off UAC.  Once again security loses when it comes to usability.

Third, the knowledgeable IT Pro/Developer.  Not a lot of people fell into this category.  However, these tended to be the same type of people who fit into the Lazy Admin category as well.  When managed properly UAC wasn’t all that annoying because it wasn’t seen all that often.  Set-it-and-forget-it and you don’t ever see the prompt.  If you created the system image properly, you don’t have to constantly keep changing settings.  It’s a simple enough idea.

But…

Application compatibility is a pain.  Most applications didn’t understand the UAC, so they weren’t running with a validation and generally broke when they tried to do things they really shouldn’t be doing in the first place.  These are things like manipulating registry keys that don’t belong to them, writing to system folders, reading data from low-level system API’s etc.  This was reason #1 for disabling UAC.

And now…

With the general availability of Windows 7 in about 2.5 hours from now, it seems like a good time to discuss certain changes to UAC in the latest version of Windows.  The biggest of course being when Windows decides to check for validation.

Windows 7 introduces two new levels of the UAC.  In Vista there was Validate Everything or Off.  Windows 7 added “Do Not Notify Me When I Make Changes to Windows Settings”.  This comes into effect when the user makes a change to a Windows setting like display resolution.  Windows is smart enough to realize it’s the user making the change, and allows it.  It’s second additional level is the same as the first, except it doesn’t hide the desktop.

Now we get into some fun questions. 

  • How does Window’s know to not show the prompt?  It’s fairly straightforward.  All Window’s executables that were released as part of the OS are signed with a certificate.  All executables signed with this certificate are allowed to run if user started.  This is only true for Window’s settings though.  You cannot implement this with 3rd party applications.  There is no auto-allow list.
  • How does Window’s know it’s a user starting the application?  Lots of applications can mimic mouse movements or keyboard commands, but they occur at a higher application level than an actual mouse move.  Input devices like mice and keyboards have an extremely low level driver, and only commands coming from these drivers are interpreted as user input.  You cannot spoof these commands.
  • Can you spoof mouse/keyboard input to accept the UAC request?  No.  The UAC prompt is created in a separate Windows desktop.  Other well known desktops include the Locked screen, login screen, and the Cardspace admin application.  No application can cross these desktops, so an application running in your personal desktop cannot push commands into the UAC desktop.

Mark Russinovich has an excellent article in TechNet Magazine that goes into more detail about changes to the UAC.  Hopefully this post at least covered all sides of the UAC debate.

October 15th Evening SQL Server DBA Event: Disaster Recovery – Edwin Sarmiento, MVP for SQL Server

OttawaSQL.net

October 15th Evening SQL Server DBA Event: Disaster Recovery – Edwin Sarmiento, MVP for SQL Server

Speaker: Edwin M. Sarmiento, MVP for SQL Server

Date: Thursday, October 15th, 2009

Time: 6:00 PM to 8:30 PM

Venue: Microsoft Ottawa Office

RSVP: http://www.clicktoattend.com/?id=142063

Session 1 (6:00 PM to 7:10 PM):  Understanding and communicating business-orientated disaster recovery  concepts and objectives

So you have a database maintenance plan that does a backup of your databases and you’re pretty sure that it works fine. But is that really enough? Are you sure that you will be able to meet your service level agreements if and when disaster strikes? This session will explain the need for understanding and communicating business-orientated disaster recovery concepts and objectives to the business stakeholders. This will include defining your RPO and RTO and how it affects your disaster recovery plan.

Session 2 (7:20 to 8:30 PM):  Disaster Recovery for the Paranoid DBA

In the first session, much have been said about disaster recovery in general. In this session, we will look at bringing the concepts down to SQL Server. This session will focus on dealing with a recovery situation for a SQL Server 2005/2008 database, an instance or an entire server. Topics covered will be backup schemes, partial backups and piecemeal restores, page-level recovery and a thorough understanding of how to troubleshoot a "Suspect" database.

Edwin M. Sarmiento

Speaker Bio:

Edwin M. Sarmiento (MVP for SQL Server) works as a Senior SQL Server DBA/Systems Engineer for The Pythian Group in Ottawa, Canada. He is very passionate about technology but has interests in music, professional and organizational development, leadership and management matters when not working with databases. He lives up to his primary mission statement – "To help people grow and develop their full potential as God has planned for them.".

Refreshments:

Pizza and pop will be provided.

Note: No one will be admitted by building security after 5:55 PM, and the event will start promptly at 6:00 PM.

OttawaSQL.net is a community group of Ottawa area developers and IT professionals.  We share an interest in Microsoft’s data technologies especially:  SQL Server, SharePoint, PerformancePoint, Workflow Foundations, LINQ, ADO.NET and Entity Framework.

Resources for Students who Hate School

I hated school.  Technically, I’m still enrolled in college.  Bachelors of Business Management.  Blech.  I figured at least with business, I would learn something useful later in life.  I chose against Comp. Sci. for a few reasons.  One being that I know a couple PhD’s that know nothing about building applications in the real world.

In Comp. Sci., you learn how to build data structures, and how to make Mandelbrot Set’s process faster.  In business, you learn why people buy stuff.  Or more appropriately, you learn how to get people to buy your stuff.

Seeing as I learned (taught myself?) about things like linked-lists and pointers while in grade 10-ish, and wrote/re-wrote/re-re-wrote Mandelbrot Set builders as a final project in grade 11, I think I can safely say I would be bored as all hell in University.  Not to mention all the theory.  Comp. Sci. is all about theory.  Maybe 10% is actually coding.  F-that.

Business is inherently hands-on.

I like hands-on.  It’s tangible.

The only problem I had was finding resources.  My programming teachers were pretty cool, and were always willing to help me on algorithms that confused me, as well as extra-curricular programs when something just wasn’t jiving.  But I had cool teachers.  Not everyone is as lucky as I was.  And with the teachers, they weren’t thinking in C# or ASP.NET everyday like I tended to do.  Trying to ask them why something trivial like

<asp:TextBox ID="txtUsername">

didn’t compile was kinda painful.  I usually got a response along the lines of “what’s the colon for?”.  I always felt funny trying to explain the quasi-xml structure of ASP.NET to teachers.  This left me in a lame position of needing to find help.  Forums are great, but separating the wheat from the chaff is a waste of time.  Enter stackoverflow.com (4 years late, mind you) and you get answers quickly.  I like it.  I use it all the time.  I’d like to think that those who are willing to look for resources will find the site fairly easily.  However, there is another site out there that not too many people know about.  It’s the Microsoft Student Experience site.  Yeah yeah, brain wash them early.  I drank the kool-aid early.

Part of the website is dedicated to the DreamSpark program.  Free, fully-licensed Microsoft products.  Nuff said.

image

The other half of the site is dedicated to students.  Good thing, given the name.  Not just students studying software development either.  All students.  It provides tangible resources for students.  Stories, tutorials, and templates look to be the main content.  It’s all surprisingly good stuff too.  It ranges from school studies to general life, to post-school life.

image 

These resources may help those students who are struggling with school – at any level.  There are students out there with lots of potential.  Let’s not see it go to waste.

Windows LiveID Almost OpenID

liveopenidThe Windows Live team announced a few months ago that their Live ID service will be a new provider for the OpenID system.  The Live team was quoted:

Beginning today, Windows Live™ ID is publicly committing to support the OpenID digital identity framework with the announcement of the public availability of a Community Technology Preview (CTP) of the Windows Live ID OpenID Provider.

You will soon be able to use your Windows Live ID account to sign in to any OpenID Web site.

I saw the potential in OpenID a while ago, long before I heard about Microsoft’s intentions.  The only problem was that I didn’t really find a good way to implement such a system on my website.  Not only that, I didn’t really have a purpose for doing such a thing.  The only reason anyone would need to log into the site would be to administer it.  And seeing as I’m the only person who could log in, there was never a need.

Then a brilliant idea hit me.  Let users create accounts to make comment posting easier.  Originally, a user would leave a comment, and I would log in to verify comments, at which point the comment would actually show up.  Sometimes I wouldn’t log in for a couple days, which meant no comments.  So now, if a user wants to post a comment, all they have to do is log in with their openID, and the comment will appear.

Implementing OpenID

I used the ExtremeSwank OpenID Consumer for ASP.NET 2.0.  The beauty of this framework is that all I have to do is drop a control on a webform and OpenID functionality is there.  The control handles all the communications, and when the authenticating site returns it’s data, you access the data through the control’s properties.  To handle the authentication on my end, I tied the values returned from the control into my already in place Forms Authentication mechanism:

if (!(OpenIDControl1.UserObject
== null)) { if (Membership.GetUser(OpenIDControl1.UserObject.Identity)
== null) { string email = OpenIDControl1.UserObject
.GetValue(SimpleRegistrationFields.Email); string username = ""; if (HttpContext.Current.User.Identity != null) { username = HttpContext.Current.User.Identity.Name; } else { username = OpenIDControl1.UserObject.Identity; } MembershipCreateStatus membershipStatus; MembershipUser user = Membership.CreateUser( username, RandomString(12, false), email, "This is an OpenID Account. You should log in with your OpenID", RandomString(12, false), true, out membershipStatus ); if (membershipStatus != MembershipCreateStatus.Success) { lblError.Text
= "Cannot create account for OpenID Account: "
+ membershipStatus.ToString(); } } }
That’s all there is to it.

What Makes us Want to Program? Part 3

In my second post I discussed my run in with ASP, and how PHP was far better.  I ended the post talking about an invitation to a Microsoft event.  This was an interesting event.  Greg and I were the only people under 30 there.  When that’s a 15 year difference, things get interesting.  Especially when you need your mother to drive you there…  The talk was a comparison between Microsoft based technologies and Linux based technologies.  The presenter was a 10 year veteran of IBM, working on their Linux platform, who then moved to Microsoft.  For the life of me I can’t remember his name.

His goal was simple.  Disprove myths around Linux costs versus Windows costs.  It was a very compelling argument.  The event was based around the Windows Compare campaign.  It was around this time that Longhorn (Longhorn that turned into Vista, not Server 2008) was in pre-beta soon to go beta, and after discussing it with Greg, we decided to probe the presenter for information about Longhorn.  In a situation like that, the presenter either gets mad, or becomes really enthusiastic about the question.  He certainly didn’t get mad.

Throughout the rest of the talk, the presenter made some jokes at mine and Greg’s expense, which was all in good fun.  Based on that, we decided to go one step further to ask how we can get the latest Longhorn build, at one of the breaks.  the conversation went something like this:

Me: So how do people get copies of the latest build for Longhorn?
Presenter: Currently those enrolled in the MSDN Licensing program can get the builds.
Me: Ok, how does one join such a licensing program?
Presenter: Generally you buy them.
Me: How much?
Presenter: A couple thousand…
Me: Ok let me rephrase the question.  How does a student, such as myself and my friend Greg here, get a the latest build of Longhorn when we don’t have an MSDN subscription, nor the money to buy said subscription?
Presenter: *Laughs* Oh.  Go talk to Alec over there and tell him I said to give you a student subscription.
Me:  Really?  Cool!

Six months later Greg and I some how got MSDN Premium Subscriptions.  We had legal copies of almost every single piece of Microsoft software ever commercially produced.  Visual Studio 2005 was still in beta, so I decided to try it out.  I was less than impressed with Visual Studio 2003, but really liked ASP.NET, so I wanted to see what 2005 had in store.  At the time PHP was still my main language, but after the beta of 2005, I immediately switched to C#.  I had known about C# for a while, and understood the language fairly well.  It was .NET 1.1 that never took for me.  That, and I didn’t have a legal copy of Visual Studio 2003 at the time.

Running a Longhorn beta build, with Visual Studio 2005 beta installed, I started playing with ASP.NET 2.0, and built some pretty interesting sites.  The first was a Wiki type site, designed for medical knowledge (hey, it takes a lot to kill a passion of mine).  It never saw the light of day on the interweb, but it certainly was a cool site.  Following that were a bunch of test sites that I used to experiment with the data controls.

It wasn’t until the release of SQL Server 2005 that I started getting interested in data.  Which I will discuss in the my next post.

ADO.NET Entity Framework and SQL Server 2008

Do you remember the SubSonic project? The Entity Framework is kind of like that. You can create an extensible and customizable data model from any type of source. It takes the boiler plate coding away from developing Data Access Layers.

Entity is designed to seperate how data is stored and how data is used. It's called an Object-Relational Mapping framework. You point the framework at the source, tell it what kind of business objects you want, and poof: you have an object model. Entity is also designed to play nicely with LINQ. You can use it as a data source when querying with LINQ. In my previous post, the query used NorthwindModEntities as a data source. It is an Entity object.

Entity Framework
Courtesy of Wikipedia

The Architecture, as defined in the picture:

  • Data source specific providers, which abstracts the ADO.NET interfaces to connect to the database when programming against the conceptual schema.
  • Map provider, a database-specific provider that translates the Entity SQL command tree into a query in the native SQL flavor of the database. It includes the Store specific bridge, which is the component that is responsible for translating the generic command tree into a store-specific command tree.
  • EDM parser and view mapping, which takes the SDL specification of the data model and how it maps onto the underlying relational model and enables programming against the conceptual model. From the relational schema, it creates views of the data corresponding to the conceptual model. It aggregates information from multiple tables in order to aggregate them into an entity, and splits an update to an entity into multiple updates to whichever table contributed to that entity.
  • Query and update pipeline, processes queries, filters and update-requests to convert them into canonical command trees which are then converted into store-specific queries by the map provider.
  • Metadata services, which handle all metadata related to entities, relationships and mappings.
  • Transactions, to integrate with transactional capabilities of the underlying store. If the underlying store does not support transactions, support for it needs to be implemented at this layer.
  • Conceptual layer API, the runtime that exposes the programming model for coding against the conceptual schema. It follows the ADO.NET pattern of using Connection objects to refer to the map provider, using Command objects to send the query, and returning EntityResultSets or EntitySets containing the result.
  • Disconnected components, which locally caches datasets and entity sets for using the ADO.NET Entity Framework in an occasionally connected environment.
    • Embedded database: ADO.NET Entity Framework includes a lightweight embedded database for client-side caching and querying of relational data.
  • Design tools, such as Mapping Designer are also included with ADO.NET Entity Framework which simplifies the job on mapping a conceptual schema to the relational schema and specifying which properties of an entity type correspond to which table in the database.
  • Programming layers, which exposes the EDM as programming constructs which can be consumed by programming languages.
  • Object services, automatically generate code for CLR classes that expose the same properties as an entity, thus enabling instantiation of entities as .NET objects.
  • Web services, which expose entities as web services.
  • High level services, such as reporting services which work on entities rather than relational data.

Protecting Data in Transit between applications and SQL Server

Alright, so you've just implemented Transparent Data Encryption on your database.  Your database is extremely secure.  The data, not so much.  You see, the problem is this: the data travels unencrypted between SQL Server and your application.  Whoops.
 
To enable SSL Encryption on the server side, there are a couple of fairly simple steps involved:
  1. In SQL Server Configuration Manager, expand SQL Server Network Configuration, right-click Protocols for <server instance>, and then select Properties.

  2. In the Protocols for <instance name> Properties dialog box, on the Certificate tab, select the desired certificate from the drop down for the Certificate box, and then click OK.

  3. On the Flags tab, in the ForceEncryption box, select Yes, and then click OK to close the dialog box.

  4. Restart the SQL Server service.

To enable SSL Encryption on the client side:

  1. Copy either the original certificate or the exported certificate file to the client computer.

  2. On the client computer, use the Certificates snap-in to install either the root certificate or the exported certificate file.

  3. In the console pane, right-click SQL Server Native Client Configuration, and then click Properties.

  4. On the Flags page, in the Force protocol encryption box, click Yes.

finally, set your connection string within the application to 'Use Encryption for Data=True'. 

Driver={SQL Native Client};
Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;Encrypt=yes;
That's really not all that difficult. One more reason to have a more secure infrastructure!>

TorontoSql.com, TorontoSql.net, TorontoSql.org just registered

Boredom is a bad thing!  Especially when you are putting off work.  So what do I do to waste my time?  Check out local user groups.  The websites at least.  A few days ago I posted a few links to some promising groups.  To my disappointment there really aren't that many Microsoft oriented user groups in Toronto.  I wouldn't call it a bad thing.  More of an opportunity.
 
I have determined that TorontoSql.com, TorontoSql.net, and TorontoSql.org were not registered.  So for $30 I registered all three of them.  Now I have to put them to good use.  Currently they are pointed to www.syfuhs.net, until I find a proper home.
 
More to come on that front!