This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on http://www.jameschambers.com/.

Wednesday, May 19, 2010

Application Whitelisting as Malware Defence

I just finished reading an article on TechRepulic’s IT Security Blog which echoes my long-standing recommendation to maintain a “whitelist” for approved applications.

Michal Kassner, the author of the article, explains briefly the benifits that whitelisting could bring.  I want to talk a little more about an actual implementation.

The difference between approaches

Blacklisting and whitelisting are common in many IT scenarios. We use it for mail servers, server-to-server communication and even internet traffic in some proxy server implementations.

Blacklisting is definitely the more relaxed version of the two: either you or third-party you trust maintains a list of domains, hosts or addresses that are not trusted.  This list is usually tied to software of some kind that prevents users from accessing or receiving data or messages from entries on the list.

Whitelisting leans towards paranoia.  I’m not saying it’s necessarily bad, but it can certainly be restrictive.  Using the same approach of tying the list to software to protect users, only addresses on the list are allowed to be accessed or permitted into a system.

Depending on the level of security required there can be a mix of the two working together to protect users.

When to use which

We can’t just switch everything over to whitelists and expect the internet to hum along all tickity-boo (without problems).  Imagine your friend registers his own custom domain and sends you an email (from that domain) to check out his new site (on that domain).  First of all, you wouldn’t get the email.  Secondly, you couldn’t access the site.

So, generally speaking, we should use blacklists where we need wide unannounced access to resources that may be abused.  When and only if they are, the switch is thrown and the address is locked out.

Some examples of where using a blacklist can help a user without hindering their experience:

  • Email servers pumping out spam
  • Web servers serving malicious content

And, some examples of where you want ‘whitelist’ behaviour implemented for better security:

  • Servers that only expect connections from certain IP addresses
  • Configuration for your remote desktop
  • Secure VPN access points (when the access points are fixed, such as office-to-office)

Personally, here’s a few other ways that I use these kinds of lists:

  • RDP connections on my servers whitelist a central IP for access and by default block/ignore other connection attempts. These servers are on private IP addresses.  The central IP has external RDP sessions routed in on a specific port and the router is configured for only a handful of IP addresses.
  • My children have whitelist-only access to the internet.  At age 3 they each got an account on the computer.  My wife and I approve only websites that we preview (lego.com for example).  We have google.com on there as well, which allows them to search, but if they want to access a search result they need our approval.

How applications fit in the mix

I think it’s important to recognize that we can’t anticipate every need of users in the IT space.  The job descriptions of people who use computers has grown so diverse that you are equally likely to find a chef who uses a computer every day as you are a computer programmer.

So can you rely solely on the work of a handful of people to approve applications?  What if one evaluator thinks that an application is malicious because of how it tracks your usage, whereas another finds it useful because it alters the behaviour of the application?

Who comes up with the criteria for whitelisting?  Who approves applications?  Who blacklists them?

Does the issue need to be a dichotomy?

Some of the above questions, to me, suggest that there should be “greylists” as well.  Using heuristics to evaluate software, as submitted by developers, greylists would allow applications to have a level of trust associated with them.  These apps could be sandboxed to protect users, and OS-level alerts could monitor these applications for excessive or abusive behaviours.

A case for whitelisting applications

I have worked with a good number of people who see a screen saver they like, or backgrounds, or icons, or mouse pointers and more recently email graphics and templates, and download and install these…treasures.  I have also seen an entire network compromised in an afternoon with zero-day malware hidden in a toolbar install.

Corporate networks should be configured to prevent the unregulated installation of software. Even as a software developer who likes to download and try out apps all the time, I try to only do so in a sandbox (virtual machine) unless I trust the application provider.

Corporate machines do not need anything installed on them except the software that enables an employee to do their job.  Mechanics don’t get waterslides near their workstations, likewise, we don’t need users installing Sudoku Extreme.

For home users it’s a little more difficult to lock down computers and I don’t feel as though they should be.  I would, however, like to see the implementation of whitelist providers, coupled with a local service that I can maintain.  This service should allow me to say “these users accounts can install these applications that are suitable for kids”.  If it’s not on the list I can add it to the list (as an administrator on my machine).  I could equally say, “these users can use these whitelists, and these users can use these greylists”.

Take it even further, now, and implement a system whereby the operating system alerts me when I’m launching a greylisted application whose signature has changed (suggesting the possibility of malware).  Give me the option to restrict file or network access to greylisted applications, or limit their access based on user type.

In a corporate scenario, you could allow management-approved applications on the workstations, and greylisted apps on virtual machines (where users have them).

Making it work for users

Ultimately what we’re doing now is broken.  Chasing malware that can move around the globe in hours is nearly a lost cause.  We haven’t seen any big outbreaks lately – I credit smarter users and more responsible operating system behaviour – there could be one coming.

The implementation must not break anything we’re already able to do, and yet provide more security than we currently have.

That’s a tall order.

Tuesday, May 18, 2010

Blog FTP Troubles

I’m working through an issue with publishing images right now and hope to be back online to continue my jQuery series in the next few days…

Thanks for the continued questions and comments as I work through all kinds of scenarios with ASP.NET MVC 2 and jQuery.

Tuesday, May 4, 2010

ASP.NET MVC and jQuery Part 4 – Advanced Model Binding

This is the fourth post in a series about jQuery and ASP.NET MVC 2 in Visual Studio 2010.

image In my last post I covered the simple scenario of a Person object getting POSTed to an MVC controller using jQuery.  In this article, I’m going to look at three other, more complex examples of real-world model binding and where jQuery might fit in the mix.

The model binding scenarios I’ll cover are:

  • Sorting a list with jQuery UI support and submitting IDs to the controller for processing.
  • Using jQuery to augment the user experience on a list of checkboxes (supporting check all/none) and allowing MVC to handle the elegance on it’s own.
  • Give users the ability to build a list of items on a complex object, then submit that object to an MVC controller for processing.

The entire working solution is available for download at the end of the file.

Preface

In the first two examples here I have lists of data that are statically programmed into the page.  From my earlier posts in the series you can see how easy it is to generate partial views that would drive the UI elements from a database or other backend.  For brevity, I’m leaving those elements out of this example.

Sortable Lists

imageThe jQuery UI library provides the sortable() function which transforms the children of a selected element in the DOM to draggable, orderable items for the user to manipulate.

The sortable() extension also provides a mechanism for us to capture the order of the list via the toArray method.

Using the jQuery.ajax() method, we submit the results of the users’ efforts via post to a controller action.  For the purpose of this post, I’m not going to do any processing in the controller, but you can set breakpoints to see the data getting hydrated into the models.

Let’s start by setting up the controller action, which accepts a list of ints as a parameter to capture the order of the IDs.

image

Yes. It’s that simple.  Now, you’d likely want to do some processing, perhaps even save the order to a database, but this is all we need to catch the data jQuery.ajax() will throw at us.

The juicy bits in jQuery are as follows:

image

Note: In order to make the results of the array compatible with the binding mechanism in ASP.NET MVC (as at MVC 2.0) we need to use the ‘traditional’ setting in $.ajax().

There are a couple of interesting things to note here:

  • jQuery.ajax() by default makes requests to the current URL via get.  My controller action that accepts the List<int> is the same name as the basic view.  I change the type here to POST and the proper controller action is called.
  • The ‘toArray’ returns an array of the selected element IDs.
  • My unordered list contains list items with IDs that represent the unique items.  In this case, they are integers stored as strings (by nature of HTML).
  • The name of the list of IDs is passed in as the same name as the parameter in the controller action.
  • When submitted to the controller, the MVC framework finds the appropriate method, looks at the expected parameter type and sees the array sent by the client.  It then uses reflection and parsing (and maybe some voodoo) to coerce the values into the expected parameter type.

image

We can then use the list of IDs as required in the comfort of c#.

One of the interesting things that you can do, as the List<int> parameter is an IEnumerable, is that you can use LINQ to Objects on these guys without any effort.  Thanks MVC Framework!

Submitting Checkboxes

image How do you submit a list of the selected checkboxes back to an ASP.NET MVC controller action?  It’s all too simple.  In fact, the only reason I mention it here is to highlight some of the simplicity we inherit when we use the MVC Framework.

I actually laughed out loud when I figured this one out.  It’s that good (or, I’m that easily impressed).

For jQuery on this example, I’m only really going to use it to augment the user experience by providing a couple of buttons to check all or check none of the options.

We’ll use a standard HTML form and allow the user to select the items in a list they feel are appropriate.  The form will be submitted via POST to our controller action (named the same as the ActionResult for the original View) and our parameter will be automatically populated for us.

image

Some things to point out at this junction:

  • The values on the checkboxes here are the same strings that are displayed in the labels.
  • I have given all the checkboxes the same name. When submitted, MVC sees these as some kind of enumerable thing and will then try to bind based on that.
  • Optimus Prime is not a Jedi.
  • This the name used for the checkboxes is the same name as the parameter in the controller action.

Packing a Complex Model

image What about if you have a complex type with properties that can’t be expressed with simple HTML form fields? What if there are enumerable types as properties on the object? 

Man, am I glad you asked! The ASP.NET MVC Framework is pretty smart about taking items off the client Request and building up your objects for you in the hydration process.

Here is my Suitcase class, with a List<string> that will contain all of the things that someone wants to take along on their vacation.

image

So how do we get those items into the object?  The first step is to allow users to create them.  We do this with a simple textbox and a button, rigged up to some jQuery script as follows:

imageWhen the user enters an item and clicks ‘Add to suitcase’ (or hits enter) we grab a reference to the textbox.  Next, we use jQuery.append() to create a new LI element with the contents of the textbox.  Finally, we clear out the value and return focus to the input field.

When the user is finished loaded up their bags, we need to create a data map that will be submitted.  To simplify the process a little, we’ll first get that list of clothes together.

image

We first create an empty array.  Next we use jQuery.each() to loop through all the returned elements – the list of LI elements that the user has created – and add the text of those LIs to the array.

Next, we POST the data back to the server:

image

Here are some observations:

  • We’re POSTing and using the traditional setting so that the enumerated items are compatible with the current versions of jQuery and MVC.
  • The names of the properties in the Suitcase class are the names of the values we use in the data map submitted by jQuery.ajax().
  • As in the first example, jQuery.ajax() is posting to the default URL, which is the same URL as the view in this case.  In the controller we differentiate the action with the HttpPost attribute and, of course, the Suitcase parameter.

When the data is submitted we see this in the controller action breakpoint:

image

And the contents of the Suitcase.Clothes property:

image

Wrapping Up

There you have it: the basics of advanced…stuff. 

From here you should be able to work out most scenarios when building up objects in jQuery, submitting them to the controller and making a jazzier UI come together with jQuery UI while still using MVC in the backend.

Some things I’ve learned along the way:

  • Remember to watch the names of your variables in data maps! They have to match the parameters (or member properties) of the controller action.
  • If you’re having trouble getting things to submit and you’re not seeing any errors, try attaching FireBug in FireFox to the browsing session and see what’s happening to your requests/responses.
  • Make sure that you’re sending the values of the jQuery selections, and not the objects themselves if you’re having trouble binding.
    • Don’t send: $(“#my-textbox”)
    • Send: $(“#my-textbox”).val()

Resources

Tuesday, April 27, 2010

Resolving LINQ Error: Missing Query Pattern Implementation

There are a couple of errors that I have come up in working with LINQ and LINQ to SQL that have common roots.  There are a couple of easy fixes when you run into the following error:

Could not find an implementation of the query pattern for source type <SomeType>.

You will also receive some further information about the error, usually along the lines of one of the following:

  • 'Where' not found.
  • 'Select' not found.

Fix 1: LINQ Using Missing

This one is easy: just make sure you have the following using statement in your class file:

image

Fix 2: Got Members?

Use the correct member of the object you are performing a query on, and make sure you’re not intending to use a property of mehod of that type.

For Example, where _dc is a DataContext object for LINQ to SQL, I have absent-mindedly forgotten the table reference in the query:

image

The above should be written as follows to avoid the query pattern implementation error:

image

That one can be a little more tricky because – especially if you’re coding late – the compiler error doesn’t really lead you to a ‘I missed a property reference’ with that error.

Fix 3: Wrong Type

Make sure you are trying to query an object that works with LINQ.  Specifically, LINQ to objects will need to have an implementation of the IEnumerable interface in the object that it is trying to query.

If you run into something that is called GetNameList, but it returns a delimited string instead of (the expected) List<string>, you can still query it after you take a simple step and do the split:

image

…and those are the most common ways to solve issues around the missing implementation of the query pattern for ‘x’ problem.

Friday, April 23, 2010

ASP.NET MVC and jQuery Part 3 – Model Binding

This is the third post in a series about jQuery and ASP.NET MVC 2 in Visual Studio 2010.

100% of the developers I have talked to this morning are enjoying jQuery and how it makes ASP.NET MVC sites a treat to work on. Of course, the sample size was one (1) developer, and he’s writing this post. Just sayin’.

In this article I’m going to cover some of the model binding scenarios that work seamlessly with these two technologies, starting off with some background and a sample, then progressing to more complex concepts.

Model Binding Basics

Model binding occurs in the processing of a request in the MVC framework, after routing and the creation of the controller. After the controller comes out of the factory, reflection kicks in to match up the request from the routing engine (as a result of some client action) with any parameters in the HTTP request.

Said another way: form values and querystring parameters get automatically turned into .NET objects in the MVC framework. Cool.

To provide a simple overview of how model binding works, we’re going to set up a quick demonstration. Start up the IDE and create an ASP.NET MVC 2 Web Application. Delete the Index file (we’re going to create our own later). Here’s the steps we’re going to follow:

  • Create a new model called Person (and build our project)
  • Update our Controller to setup an “empty” person for our view
  • Create a strongly-typed view to create a person
  • Create an action method on our Home Controller to capture the ‘create’
  • Let the MVC framework do the rest

We’re not actually going to persist anything here, this is just a show-and-tell.

The simple parts

Navigate to your Models folder and right-click to Add –> Class called Person. Complete the class out as follows:

image

We need to build our project here (SHIFT + CTRL + b) for the IDE to be able to see our class in later steps. The type-awareness from reflection requires that our type exist in an assembly.

Pop over to Controllers –> HomeController and delete the ViewData assignment. We’re going to create a new Person here and return it with the view. Our action looks very simply like so:

image

image Right-click anywhere in the method and select Add View… from the context menu. We are adding a view named Index, setting it to be a strongly-typed view and setting the view content to Create. This will allow code generation to output the basics of the form we’re going to use.

Note that here, or anytime you try to add a view, that if your model hasn’t been updated by building your project your types won’t appear in the View Data Class drop-down. You can cancel, build, and re-open the dialog if that is the case.

The page that is generated is super handy as a starting point. Even if it doesn’t save me much time (after all the changes and deleting I do) for some reason it just makes me feel better that the computer had to do some work too.

Let’s clean it up a bit. Remove the validation controls, delete the DIV with the ‘back to list’ link in it and change the H2 to something more interesting.

Because I’m not going to be posting back to my Index action method, I need to also update the using statement to have to correct calls created for submitting the form:

Html.BeginForm("CreatePerson", "Home")

Finally, let’s add a bit of code with the corresponding method, CreatePerson, and a breakpoint in our Home controller:

image

The above doesn’t actually do anything (and won’t go anywhere past the breakpoint), but if you pause where I suggest and evaluate the Person object or the name that was assigned the string, you’ll see the values populated.

How did the Model Binding Work?

There are actually a ton of in-depth explanations out there, but here is the summary of what we’ve done and what the MVC framework does to support model binding:

  • We have a class with public properties
  • The template engine created a page for us with the HTML helper TextBoxFor
  • TextBoxFor uses the name of the public properties to generate a form input with the same name
  • The template creates a form to host those controls, which we directed to our controller and action
  • When written to the browser, the form action is set to “/Home/CreatePerson” using the POST verb
  • The MVC framework routes the form submission to the Home controller, then uses reflection to find the CreatePerson method
  • Because the method accepts a Person object as a parameter, the MVC framework evaluates the HTTP request (querystring parameters, form values) and then hydrates an object for us

Now, Let’s Make it Interesting

So far, this has just been a demonstration of simple model binding in the MVC framework. Let’s get jQuery involved.

  • Change the controller action to a partial view result
  • Create a partial view that reveals the created person
  • Add jQuery and jQuery UI to the Site.Master file
  • Remove the using statement from the Index page
  • Modify the input so it’s easier to select in jQuery
  • Add a DIV to store the results of the create
  • Add a calendar selector for the birthdate
  • Submit the form via jQuery when the user clicks the button
  • Clear the form when the partial view result comes back, and display the result

Let’s start by changing the method to only accept POSTs and simply returning the Person object we were passed in to the PartialView.

image

image Right-click anywhere on the method and select Add View… from the context menu.

This time we’ll create the view as a partial, it will be strongly-typed to Person again, but we’ll set the View Content to Details.

The tooling support for the MVC Framework in Visual Studio 2010 will then create the ASCX (server control) for us with all the fields displayed.

Delete the P tag at the end of the generated control with the ActionLinks in it, leaving only the control tag at the top and the FIELDSET control.

Next, pop into Views –> Shared –> Site.Master and add jQuery to the HEAD of the master page. Let’s also add jQuery UI at this time to open the doors to some other augmentations. For full functionality you’ll need the CSS and the images folder in your project as well, and the CSS linked in the HEAD of the master page.

In Index.aspx, remove the using statement so that the form is no longer generated. This is easy if you use Visual Studio 2010’s collapsible regions (you can collapse the FIELDSET tag to see the whole using construct).

Add an ID with a value of “create-person-button” to the submit button at the bottom of Index.aspx. Lastly, before we get scripting, add a DIV to display the partial view when the person is ‘created’. These last two bits should look like the following:

image

On to the script

jQuery gives us a way to easily make AJAX requests via POSTing to the server. We pass in a map of data that the server is expecting. The result can be passed to a function that evaluates the results.

With the inputs setup the way they are and our placeholder…uh…holding a place, we’re all set to execute our POST.

We’ll write a helper function that will process the results of the POST operation and, of course, a jQuery ‘document ready’ event handler to setup the calendar and trap the submit button click.

image

Most of the code should be easy enough to follow along. The one interesting bit is that the data map need not be constructed with proper case. That is, if your fieldname is FirstName you can use FiRsTnAmE as the name in the data map and that is okay.

Run the app and enjoy!

The jQuery UI datepicker in action:

image

The form cleared after submit and the results of the POST displayed:

image

Some Caveats

At this point we don’t have any validation in place, we’re not saving to a database of any kind and we’re hooped if there’s a server-side error.

Unfortunately the jQuery POST doesn’t play nicely with unhandled exceptions that are thrown on the server. $.post is shorthand for a sub-set of the functionality (with some presets) of $.ajax, and only maps a handler for the success event (not error events).

To see this in, well, inaction change your CreatePerson action to the following:

image

This will instruct the MVC framework to pass the person object through to a view named “foo”, which doesn’t exist. If you run the form at this point, and submit, you’ll see no errors (unless you attach a debugger, like FireBug, to the script).

More to Come

In my next article I’m going to look at more complex data scenarios, like selections from a list and posting arrays back to the controller. I’ll also integrate some other goodies, like jQuery UI’s autocomplete, to help users pick a color.

Resources

Wednesday, April 21, 2010

VS2010 Box Selection Trick – Copy and Paste-ery

Here’s a quick tip showing off one of the cool features of box selection in Visual Studio 2010.

This one deals with copy-and-paste.

A simple scenario

Perhaps you are trying to preload some data into a StringBuilder for testing something out. 

As a simple example, let's assume you have a text document with a list of 20 names that you want added to a StringBuilder.

  1. imageIn the method where you wish to build the list, type sb.AppendLine(""); where sb is the name of yourStringBuilder object.
  2. Quickly copy & paste this line 20 times to set up a receiving area for the names.
  3. Open the text file of names in Visual Studio 2010.  This is important because you want to leverage the smarts of the IDE when you copying the text.
  4. Rather than line-selecting the names, box select them with the mouse while holding the ALT key (it's okay if you capture whitespace when the names are longer than others).
  5. Copy the selection to the clipboard.
  6. Return to your method. Vertically box-select the space between the quotes, again by using the mouse to select while holding the ALT key. You get a thin line for a selection that is zero characters wide.
  7. Paste your selection.

Here’s an example of the result:

image

Cheers!

Friday, April 16, 2010

They Must Be Listening!

I recently posted on how obscure I thought it was to be putting files on the Windows 7 jump list for Visual Studio 2010.  After all, no one works on ‘files’, we work on Solutions, or at least Projects.

I actually counted the files I worked on yesterday: 44.  That would be one big (meaningless) jump list!

Jumping Reloaded

imageThankfully, Microsoft heard my pleas. 

Now, I can’t take all the credit – I was not the one who coded the changes – but I can at least take most of the credit.  I’m sure no one else in the world mentioned this!

I had to use my artistic abilities, once again, to make it clear how I felt about the way jump lists were implemented in the release version of Visual Studio 2010.

I will make signed copies available of both the “Bad” and “Good” artwork for a minimum contribution of $400 USD via PayPal.

;o)