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

May 24, 2007
@ 03:19 PM

Waiter Rant has been out of commission for several days now.

For anyone wondering what happened, the good folks at SoundQue -- who host his site -- have confirmed that the WordPress software Waiter uses was hacked.

I suspected a hacker when, on the first day I began to get suspicious, I looked at the HTML source and saw that there was a hidden <iframe> tag that was downloading content from http://www.allddos.biz. None of that sounded good to me.

In any event, I'm assured that Waiter will be back on the air in a couple of days.


 
Categories: Everything Else | The Geek

Came to the computer, needing to print. Hit print button. No joy. Look at the display. No display. No flashy little lights on the console. All symptoms point to loss of power.

Can't be loss of power. Printer's had power non-stop for almost 2 years. It's even on the UPS.

Look around the room. Computer on. Lights on. House has power. But printer acts like it has no power.

But it can't be power loss. Printer's had power non-stop for almost 2 years.

Scratch head. Apply Occam's razor. Simplest answer is that printer has no power. Sigh. It's pointless and time wasting, but try anyway. Check power connector on back of printer. It's snug. Follow cable. Follow cable over bookcase. Follow cable under chair cushion. Finally get to wall.

Fuck. Printer not on UPS. Printer not plugged in. Wife unplugged printer to charge cell phone. Why cellphone charger needs uninterruptable power? Question for another day.

Sigh. "That's why we ask stupid troubleshooting questions."

Dammit.


 
Categories: The Geek

January 30, 2007
@ 12:46 PM

The folks over at Drivl have a very funny blog about what code doesn't do. As opposed to what movies tell us it does

Check it out.

Oh, and while we're dispelling code and coder stereotypes, I'll toss in my two cents: real programmers abhor animation of any kind. Yes, games are animated. And graphics designers and movie makers need to deal with animation. But we do not build our tools to contain needless, stupid animation. Mostly, we just want to get our work done and animation just slows us down. So when you see a movie guy click a button, or press a key, and a remarkably complex piece of animation plays to indicate that work is being done...yeah, that's bullshit.


 
Categories: The Geek | The Jester

January 17, 2007
@ 02:53 PM

Mike from Barely Legal has a new blog called In It But Not Of It.

Today, he writes a post that only a man could write. It's about the death of a dear piece of consumer electronics.

I say it's a Post Only a Man Could Write because, really, women don't anthropomorphize things the way us men do. If a woman's favorite hairdryer breaks, she might be sad about it, but you'll never hear her say something like "Oh, Doris! <sob!> You were so good to me!"

But when my 1980 Honda Accord died, I said "Goodbye, Hubert!" and gave a little sniff when the tow truck hauled him away.


 
Categories: The Geek