Navigation

Search

Categories

On this page

Mocking Request.UserHostAddress in ASP.NET MVC
Shame, I Have None
Securing Form Values in ASP.NET MVC
Syntax Highlighting
Prime Factors Kata in C#
From The Nietzsche Family Circus
An Epic Battle
Waiter Revealed

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 36
This Year: 0
This Month: 0
This Week: 0
Comments: 2

Sign In
Pick a theme:

# Thursday, July 14, 2011
Thursday, July 14, 2011 12:47:20 AM (Eastern Daylight Time, UTC-04:00) ( The Geek )

I spent a lot more time on this tonight than I really should have.

A controller of mine needed to use the value of Request.UserHostAddress and I wanted to mock that value in my unit tests.

I tried, and failed, to get this to work using the MvcContrib.TestHelper assembly. Eventually, I stumbled on a (old) post of Scott Hanselman's with a class called MvcMockHelpers. I'm using the Moq version of that class.

Simply add the following extension method to that class and you're good to go:

public static void SetupUserHostAddress(this HttpRequestBase request, string address)
{
    if (address == null) throw new ArgumentNullException("address");

    var mock = Mock.Get(request);

    mock.Setup(x => x.UserHostAddress).Returns(address);
}

And here's how you use it:

var controller = new ControllerToTest();
controller.SetFakeControllerContext();
controller.Request.SetupUserHostAddress("127.0.0.1");

Voila.

# Tuesday, March 22, 2011
Tuesday, March 22, 2011 9:24:29 AM (Eastern Standard Time, UTC-05:00) ( The Geek )

I am shamelessly neglecting my oft-ignored blog to attempt to win a free trip to VSLive.

Hope to see you there!

# Wednesday, January 20, 2010
Wednesday, January 20, 2010 12:50:08 AM (Eastern Standard Time, UTC-05:00) ( The Geek )

It’s fairly common to use hidden form fields to store a value that gets posted back to your controller for the purposes of establishing context.

For example, on an edit form, you might render a hidden field containing the ID of the entity you’re editing. This is actually preferable to using route values because it’s much easier to tamper with those than it is to tamper with form data.

That said…it’s still pretty darn easy to tamper with form data. If you’re using FireBug, you can view the current page’s DOM and fiddle with any value you please. This can be catastrophically bad if, for example, an attacker views a form to edit an entity they have access to, and then changes the entity ID field to the ID of an entity they don’t have access to. Granted, your validation code should handle that case, but when it comes to attacks, an ounce of prevention is worth a pound of cure.

So, how to prevent an attacker from tampering with our hidden fields?

One solution is to create a secure hash of the field in question and render that to the client as well. Then, on postback, validate that the hash of the incoming value matches the original hash. Here’s an example of the HTML for that:

<input id="productId" name="productId" type="hidden" value="1" />
<input id="productId_sha1" name="productId_sha1" type="hidden" value="vMrgoclb/K+6EQ+6FK9K69V2vkQ=" /><

The second hidden field is the SHA1 hash of the productId value 1, plus a secret value that makes tampering with the hash impossible.

I’ve written an HTML helper that facilitates creating these hash fields. Here’s how it’s used:

<% using(Html.BeginForm()) { %>
    <%=Html.SecuredHiddenField("productId", 1) %>
    <fieldset>  
        <p><label for="Name">Product Name:</label> <%=Html.TextBox("productName") %></p>
        <button name="save" value="with">Save Product</button>
    </fieldset>
<% } %>

And here’s the code for the HTML helper:

public static class SecuredValueHtmlHelper
{
    public static string SecuredHiddenField(this HtmlHelper htmlHelper, string name, object value)
    {
        var html = new StringBuilder();
        html.Append(htmlHelper.Hidden(name, value));
        html.Append(GetHashFieldHtml(htmlHelper, name, GetValueAsString(value)));
        return html.ToString();
    }

    public static string HashField(this HtmlHelper htmlHelper, string name, object value)
    {
        return GetHashFieldHtml(htmlHelper, name, GetValueAsString(value));
    }

    public static string MultipleFieldHashField(this HtmlHelper htmlHelper, string name, IEnumerable values)
    {
        var valueToHash = new StringBuilder();
        foreach (var v in values)
        {
            valueToHash.Append(v);
        }

        return HashField(htmlHelper, name, valueToHash);
    }

    private static string GetValueAsString(object value)
    {
        return Convert.ToString(value, CultureInfo.CurrentCulture);
    }

    private static string GetHashFieldHtml(HtmlHelper htmlHelper, string name, string value)
    {
        return htmlHelper.Hidden(SecuredValueFieldNameComputer.GetSecuredValueFieldName(name),
                                 SecuredValueHashComputer.GetHash(value));
    }
}

The HTML helper uses a class called SecuredValueHashComputer to compute the SHA1 hash. I’ve written it so that you can plug in any hash computer that you want (MD5, or say SHA512 for the really paranoid):

public static class SecuredValueHashComputer
{
    public static string Secret { get; set; }
    public static IHashComputer HashComputer { get; set; }

    static SecuredValueHashComputer()
    {
        Secret = "zomg!";
        HashComputer = new SHA1HashComputer();
    }

    public static string GetHash(string value)
    {
        return HashComputer.GetBase64HashString(value, Secret);
    }
}

In an ideal world, you’d load the value for “Secret” from your Web.config (preferably from an encrypted section) and use an IoC container to instantiate the IHashComputer.

Finally, validate the data like so:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int productId, string productName, string save, FormCollection formValues)
{
    if (save == "with")
    {
        SecuredValueValidator.ValidateValue(formValues, "productId");
    }

    ViewData["message"] = string.Format("Product ID {0} was saved!", productId);

    return View();
}

The complete source code is available at http://blog.slatner.com/downloads/SecuredFormExample.zip.

Wednesday, January 20, 2010 12:18:10 AM (Eastern Standard Time, UTC-05:00) ( The Geek )

Fought for an hour tonight to get syntax highlighting working in my preferred dasBlog theme. Didn't happen. Finally switched themes and everything worked right.

My thanks to Alex Gorbatchev for such an awesome tool.

# Wednesday, November 11, 2009
Wednesday, November 11, 2009 11:56:07 AM (Eastern Standard Time, UTC-05:00) ( The Geek )

Ever since I heard about the concept of "code kata", I've been practicing them every day.

If you hadn't heard, code kata are lot like those in martial arts. They are an exercise wherein you make the same decisions over and over again so that you are more likely to make those same decisions again when under stress. Since TDD is a somewhat rigid process where the same rules are followed over and over again it lends itself to this concept of "kata".

There are a couple of kata that I do. First, the "calculator kata" (thanks Andrew Woodward), where you create a class with a method that sums all of that numbers in a comma delimited string.

Second, and more fun, is a kata where you write a method to return a list of all of a number's prime factors. I first learned about this kata from Uncle Bob Martin. A few days ago he mentioned on Twitter that he was trying to get a screencast of a "flawless" version of this kata. After about 30 attempts, I did not achieve "flawless", but I think I achieved "pretty good".

This first video shows the primary kata exercise. Using TDD, I steadily create a method called Generate that lists the prime factors for an input integer. I also use Resharper and its templating and refactoring features to make this process easier. As an aside, if you are not presently using something like Resharper or CodeRush to help you as you code, you are definitely doing things the hard way.

In the video, I try to rigidly adhere to the TDD method:

  1. Write a test first
  2. Watch it fail
  3. Write just enough code to make it pass
  4. Verify the test passes
  5. Refactor

On that note, I know it annoys people to no end when I hard-code return values when I know I'll be eliminating that code very shortly. But it's neat to watch how the algorithm transforms over the course of the kata, and you wouldn't see it if you didn't follow the steps rigidly.

This second video is not part of the kata, but it's meant to show two things:

  • Refactoring the code and using your existing tests to validate that you haven't broken anything. I call this the "real coder" refactoring since it replaces the easy-to-read while loops with not-so-easy-to-read for loops.
  • The use of MbUnit's "Row" tests that we can use the same test code to validate multiple inputs to the validator.
# Friday, August 22, 2008
Friday, August 22, 2008 2:58:10 PM (Eastern Daylight Time, UTC-04:00) ( The Jester )
# Sunday, August 17, 2008
Sunday, August 17, 2008 12:15:50 AM (Eastern Daylight Time, UTC-04:00) ( )

I took my daughter out on a play date today. Really, this is the first time in 18 months that I've had her all to myself and been completely responsible for her out of the house for more than an hour or two.

Needless to say, I wanted it to go well. Needless for Murphy to say, things didn't go as planned.

The play date host had recently purchased a new pair of shoes. Large, white shoes. They were sitting in the middle of the living room floor. My daughter, who is not yet very coordinated, went careening through the house at full tilt, tripped over the shoes, went airborne, and smashed her face into the wall of the living room.

You can always tell the severity of a child's injury by the type of crying that commences afterward. In this case, my daughter didn't move for a full five seconds, and then commenced to wail at the top of her lungs. She still didn't move. She just lay there with her face pressed against the wall.

I ran over to her and picked her up, whereupon blood began running from her nose all over our host's new white shoes and his carpet. I was completely paralyzed with indecision for a moment. But the smartass side of me surveyed the situation and I said "Wow! She fought the wall and the wall won!"

# Friday, August 01, 2008
Friday, August 01, 2008 9:39:33 PM (Eastern Daylight Time, UTC-04:00) ( )

Well, it looks like Waiter Rant has finally hit the shelves. I've been waiting for this book for a long time.

I've been following the adventures of The Waiter almost since his blog began. It's one of my favorite reads.

I'm kind of annoyed that the press has done their sleuthing and determined that Waiter's restaurant, "The Bistro" is actually Lanterna Tuscan Bistro in Nyack. I'm annoyed because I figured it out two years ago (in January 2006), but I kept my mouth shut because I knew Waiter didn't want it revealed.

In case you were wondering how you could have figured it out yourself, here's the long list of clues that Waiter dropped over the years:

  • New York metro area
  • Italian Bistro
  • Owner with a stereotypical, Italian-sounding name ("Fluvio")
  • Owner offers occasional cooking classes
  • Restaurant offers take-out
  • Restaurant has a web site
  • Take-out menu is posted online
  • Very close to a Starbucks (I know, they're everywhere, but you'd be surprised how many possibilities this eliminates)
  • Close proximity to an Irish pub where you can get your Bushmills, neat.

All those clues made me 90% sure the restaurant had to be Lanterna. However, the final clue for me was when Waiter posted that "The Bistro" had "river views". As you can see from this map, Lanterna is right on a big 'ol river.