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.


 
Categories: The Geek

January 20, 2010
@ 12:18 AM

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.
 

Categories: The Geek

November 11, 2009
@ 11:56 AM

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.

 
Categories: The Geek

August 17, 2008
@ 12:15 AM

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!"


 
Categories:

August 1, 2008
@ 09:39 PM

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.


 
Categories:

July 20, 2008
@ 03:43 PM

I recently ate at at Cantina 1511 and was astonished at how yummy their margaritas were. They were honestly the best I've ever tasted.

First, there was not a ton of ice. They sell frozen margaritas, but the ones I had came straight out of a pitcher and were served on the rocks.

Second, it was obvious that it was made with fresh juices. Almost all the margaritas you'll ever have -- unless you're at one of my parties -- are made with mixes. The freshness of the stuff just made my day.

So, I set about figuring out how to duplicate this margarita. I wasn't quite able to duplicate the recipe, but what I ended up with was fan-fucking-tastic.

As the owner of Cantina 1511 will tell you, variations in the sweetness of the fruit play a huge part here, so your mileage may vary if you try this recipe.

Also, you can use any kind of tequila you want, but the Cabo Wabo Reposado I used just took the flavors to a completely new level.

Finally, an important note: though you have likely been led to believe that ripe limes are green and overripe limes are yellow. This is NOT TRUE. Ripe limes are yellow. Overripe limes are brown. Always get the ripest limes you can find.

Bryan's Fresh Juice Margaritas

Yield: About 8 margaritas, depending on the size of your glasses.

Ingredients

1 1/2 cups freshly squeezed lime juice
1/2 cup freshly squeezed orange juice
1 1/2 cups simple syrup
Cabo Wabo Reposado Tequila

Preparation

Strain the juices through a strainer into a pitcher. We don't want pulp in our margaritas. Gently stir in the simple syrup.

Optional: rim the margarita glass with kosher salt by rubbing a lime around the rim and dipping the rim in salt.

Pour the tequila into the bottom of the margarita glass. Margarita glasses have a small well at the bottom that blossoms up into a large mouth. I fill the bottom well in my glasses. Really, it depends on how much tequila you like and how fast you want to get smashed.

Add a handful of ice to the glass and pour juice mixture over the top until the glass is full.

Serve the result to a delighted audience.


 
Categories: The Chef

April 15, 2008
@ 09:39 PM

I just made this recipe up tonight. It makes up for the fact that my mahi-mahi was not fresh and was actually pretty gross. This slaw rocked my world when I bit into it:

Bryan's Pepper and Mango Slaw

Ingredients

1 mango, julienned
1 red bell pepper, julienned
1 yellow or orange bell pepper, julienned
1 granny smith apple, julienned
1/2 red onion, julienned
1 jalapeño pepper, minced
Red wine or apple cider vinegar
Salt and pepper to taste

Preparation

Put everything in a bowl and toss to combine everything evenly. Add salt and pepper, using a little more pepper than salt. You just need enough salt to give it a little oomph. Add a couple tablespoons of vinegar and toss again. Taste the slaw and add seasoning and vinegar until it's to your liking.


 
Categories: The Chef

December 5, 2007
@ 08:21 PM

My wife, bless her, usually handles all of the late-night baby issues. She is well within her rights to wake my lazy ass up and make me do it, but she either loves me or knows that it would be easier to just deal with it than to way me up. I'm not sure which.

As a result, I'm a little untrained on how to deal with 2:00am baby issues, which is how the following conversation came to take place:

Baby: Waaaaaaaaahhhhh!

Cecilia: Okay, Bryan, I'm completely exhausted so you are going to go give the baby her pacifier. You will not make eye contact. You will not speak. You will not make any noise at all. You will not engage the baby in anyway. You will simply grab the pacifier, insert it into her mouth, make sure she has a firm grasp on the stuffed elephant, tuck her in, and return to bed. Do you understand?

Me: Sir, yes sir!


 
Categories: The Jester