OdeToCode IC Logo

Words To Live By - From Google Code Search

Friday, December 8, 2006 by scott

I want to take some of the prose I find on Google's Code Search and print it onto T-shirts and coffee mugs. These would make great gifts during the holiday season.

Locks are analogous to green traffic lights: If you have a green light, that does not prevent the idiot coming the other way from plowing into you sideways; it merely guarantees to you that the idiot does not also have a green light at the same time. (from File.pm).

Most people smell bad. But that's no excuse to not let them change their default remote command. (from remote.c).

The last match is not always the one that is chosen. (from data.c).

The last phrase sounds like Socrates. Except, I guess, Socrates never had the pleasure of working with regular expressions.

 

So, What Was Wrong with That Code Anyway?

Thursday, December 7, 2006 by scott

WWWTC #9 ranks 10 out of 10 on the "difficult and subtle" scale. Let's say we write the following code to call the method Jill wrote:

Sub ExploitIt(ByVal path As String, ByVal data As Byte())

    
Dim j As New JillsObject
    
Try
        ' setup an environment that will force
        ' an exception after impersonation starts,
        ' than call into the method

        j.WriteToSensitiveFile(path, data)

    
Catch When RunMaliciousCode() = True
        ' ...
    End Try

End
Sub

Function
RunMaliciousCode() As Boolean

    ' here is your chance to execute code as an admin...

End Function

The problem is that the exception filter (RunMaliciousCode) has a chance to execute before Jill's method turns off impersonation in the finally clause.

I planned on going into more detail, but Jonas provided two links in the comments that point to a pair of excellent posts by Shawn Farkas. See:

Safely Impersonating Another User
Impersonation and Exception Filters in v2.0

What's Wrong With This Code? (#9)

Tuesday, December 5, 2006 by scott

Jill Developer has a new assignment. She needs code that will overwrite data in a sensitive file. Only the local machine administrator has access to the file, but Jill plans to impersonate the admin account to gain access to the file.

Jill first builds a static class to PInvoke LogonUser and start the impersonation. This class (Utility), and it's method (ImpersonateAdministrator) work well. Jill's next step is to write the following code:

public void WriteToSensitiveFile(string path, byte[] data)
{
    
WindowsImpersonationContext impersonationContext = null;
    impersonationContext =
Utility.ImpersonateAdministrator();

    
try
    {
        
using (FileStream fs = File.OpenWrite(path))
        {
            fs.Write(data, 0, data.Length);
        }

    }
    
finally
    {
        
if (impersonationContext != null)
        {
            impersonationContext.Undo();
        }
    }

}

Of course, Jill still has some work ahead to verify the path, the data, and the user who is calling this method. At this early point, however, Jill has one worry she wants to put to rest before moving on - is it possible for a malicious caller to take advantage of the impersonation context and do something other than write to a file?

Win a Visual Studio 2005 Team Suite with MSDN Premium Subscription

Friday, December 1, 2006 by scott

In celebration of my solitary post this month, I'm giving away two Visual Studio 2005 Team Suite with MSDN Premium subscriptions. Microsoft gave me these subscriptions to give to the community, and I'd like to find some deserving candidates.

To win a subscription, send me an interesting application or some cool code you've written that uses a .NET 3.0 technology (WF, WPF, or WCF), or uses ASP.NET AJAX 1.0 Beta 2. I'll pick one winner from the .NET 3.0 category and one winner from the AJAX category. I'll be posting the code from 6 or more of the entries here on the site. You have to own the code and be willing to have it featured here in a post. We can all learn something from the contest.

Send submissions to contest @ odetocode.com before midnight on December 15th (GMT -5). I'll announce the winners on December 20th. Winners must activate their subscriptions before December 29.

Working MasterPage Samples

Monday, October 30, 2006 by scott

A few people have asked me for a working web site with some of the code from my MasterPage: Tips, Tricks, and Traps article. This download is a web site based on the ASP.NET Personal Web Site Starter Kit and provides a number of the samples from the article.

Samples include a master page base class, and an HttpModule to assign the MasterPageFile property for .aspx web forms at runtime. There is an example of content page to master page interaction through a strongly typed Master property, and an example of master page to content page interaction via an event.

What's Wrong With This Code? (#8)

Tuesday, October 24, 2006 by scott

Joe Developer is working with a simple struct:

struct Point
{
    
public int x;
    
public int y;
}

Joe's tech lead asked him to write a method that will return an array of 10,000 initialized points. Joe wrote following code.

Point[] CreatePoints()
{
    
Point[] points = new Point[10000];

    
for (int i = 0; i < points.Length; i++)
    {
        points[i] =
new Point();
    }

    
return points;
}

The code doesn't create any runtime errors, but Joe is worried because his tech lead looked at the code and frowned. What could provoke such a reaction?

Hint: Joe's lead is a performance nut.

What's In a Workflow Queue Name?

Monday, October 23, 2006 by scott

There is a queuing infrastructure in Windows Workflow that facilitates communications between workflows and the outside world. Event related activities, like the HandleExternalEvent and Delay activities, provide a formalized layer of abstraction over this queuing infrastructure. You might never need to know that a queuing service exists if you can get 100% of the job done with components from the base activity library.

If you need more flexible messaging, or like Harry, want to work with a low level API, you can use the queuing service to create queues and en-queue messages for your own purposes. Before jumping in, it's worthwhile to study how the built-in activities make use of workflow queues, particularly workflow queue names.

If we look at the correlated local service example in the Windows SDK, we'll find a Parallel activity with two sequences inside. Both sequences call a CreateTask method and expect a TaskCompleted event to arrive. A local service we've implemented has to raise this TaskCompleted event, but the event isn't delivered directly to the running workflow. Instead, the workflow runtime catches the event. The workflow instance might be unloaded from memory and living as a serialized blob in a database table. The runtime will reload the proper workflow and deliver the event.

If there are multiple workflow instances active, it's easy for the runtime to find the right instance because of the InstanceId property on all incoming event arguments (local service communications might define event arguments that derive from the ExternalDataEventArgs class).

But how does the workflow know what activity is waiting for the event? This isn't hard if there is only one activity waiting for an event, but in this sample we have two activities both waiting for the same event from the same service.The secret is in the workflow queue names the individual activities create to wait for the events. If we use GetWorkflowQueueData on the workflow instance, we can inspect the queue names. A queue name in the this SDK sample will look like the following:

Message Properties
Interface Type:ITaskService
Method Name:TaskCompleted
CorrelationValues:
001

What we see is that the workflow queue "name" actually contains all of the information the runtime needs to deliver events to their proper destination. The name includes the interface and event name, as well as correlation values when the associated activities have correlation tokens.

Queue names in windows Workflow are more than just friendly identifiers. As Harry pointed out, they implement IComparable and are actually a key piece to how Windows Workflow works with data exchange services.