Archive for the ‘Uncategorized’ Category

Verifying Anti-Forgery Token for Form POST only

Sunday, February 7th, 2010

As many of you know, the ASP.NET MVC Anti-Forgery token helps thwart Cross Site Request Forgery attacks. Any site that uses authenticated sessions (99% of web apps) should use similar mechanisms so these attacks cannot occur.

Very often, I would write GET and POST actions in the same method. This allows fall through to that same code we used for GET request if POST validation fails, ensuring consistency.

public ActionResult EditPerson(Person person)
{
	if (Request.HttpMethod == "POST" && ModelState.IsValid)
	{
		// do edit person...

		return RedirectToAction("Index");
	}

	// do get person

	return View(person);
}

If I use that sort of paradigm, then the [VerifyAntiForgeryToken] attribute would block both GET and POST requests when the token is not supplied. I want the token to be only verified when I POST. Since ASP.NET MVC is extensible, the normal way to go about that would be modify the behaviour of [VerifyAntiForgeryToken] by subclassing. Unfortuantely, VerifyAntiForgeryTokenAttribute is sealed which means it can’t be inherited from. Luckily, borrowing from the same trick that Http*Base classes use to combat sealed Http* classes, we can just create a new attribute that wraps the old attribute, implementing the same members and proxying the calls back to the wrapped base class. That’s exactly what I did and it works quite well. The result is [ValidateAntiForgeryTokenOnPost] which will only verify the form anti-forgery token on a POST request:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ValidateAntiForgeryTokenOnPostAttribute : FilterAttribute, IAuthorizationFilter
{
	private ValidateAntiForgeryTokenAttribute _wrapped;
	public ValidateAntiForgeryTokenOnPostAttribute()
	{
		_wrapped = new ValidateAntiForgeryTokenAttribute();
	}

	public string Salt { get { return _wrapped.Salt; } set { _wrapped.Salt = value; } }

	public void OnAuthorization(AuthorizationContext filterContext)
	{
		if (filterContext.HttpContext.Request.HttpMethod == "POST")
		{
			_wrapped.OnAuthorization(filterContext);
		}
	}
}

This will teach those sealed classes!

iptsafe – iptables with dead man’s switch

Monday, December 28th, 2009

When dealing with iptables remotely, you can easily set a firewall rule which would lock yourself out of machine. After that, the only way to unlock yourself is to physically go the machine and unset the firewall rules it through the terminal. If this was a VPS or dedicated server, chances are you can’t physically access the machine and have to contact the service provider to reset the firewall rules.

This is an instance where a dead man’s switch would help. The theory goes that if an operator is detected incapacitated, then an certain action will occur. In our case, the action is to undo our firewall changes. How does it know we are incapacitated? Well if we don’t report back in a certain amount of time, then we’re probably dead. A long time application of this is actually found when you try to change your monitor’s resolution, it ask you if you want to keep it. If it gets no response, it’ll revert back automatically.

Do you want to keep these settings

The iptsafe script works on the same principle. It is a wrapper around the iptables command. It takes the same command parameters as iptables, with the exception that if you only specify one parameter, then it’ll assume it is an iptables-save’d file and use it on iptables-restore. Once iptsafe is run, it’ll first use iptables-save to store a copy of the current iptables state, then apply the changes you requested. After that, it prompts you to keep the changes, and if you don’t respond within 15 seconds, it’ll revert back to the original state.

Here’s iptsafe

Sample usage:
# iptsafe -A INPUT -i eth0 -p tcp -s 192.168.0.1 -j ACCEPT
or
# iptsafe my-saved-iptables

An intuitive Dictionary Model Binder for ASP.NET MVC

Thursday, December 24th, 2009

The other day I was working on an ASP.NET MVC website and came across a need to post an array from the browser into the web app. The framework comes with something called a Model Binder that automagically converts submitted form data into action parameters of the controller. For example, if we have form submitted data such as
person.FirstName=John&person.LastName=smith
for a theoretical model class ‘Person’, and

public ActionResult SavePerson(Person person)

as the action method signature, SavePerson will be executed with the parameter equivalent to

new Person() { FirstName = "John", LastName = "Smith" }

The default model binder is pretty powerful, using reflection to dig out and assign all the fields. It also supports arrays and dictionaries, but with big limitations. The array must start at 0 and be unbroken. That is understandable for arrays, but what if you had a dictionary? Surely it can start at any position? Not so. The dictionary has even more obscure requirements, with the need to specify explicit .Key and .Value parameters in your form submission. For example:
dict[0].Key=mykey&dict[0].Value=myvalue
This represented extra work to generate the form on the client side. I just want to input something more intuitive like:
dict[mykey]=myvalue
The ASP.NET MVC framework is highly extensible. It allows you to define your own custom model binder so that’s exactly what I did. Inheriting off DefaultModelBinder, I created DefaultDictionaryBinder that overrode the BindModel method and intercepts when a IDictionary<,> class is being bound.

The code is now up at github: DefaultDictionaryBinder.cs. Note that if you are using this on ASP.NET MVC 1, please define the macro ASPNETMVC1. If you are using it with MVC 2 or MVC 3, it should work as is.

To use, you have to override the default model binder. In global.asax.cs in Application_Start(), add the line:

ModelBinders.Binders.DefaultBinder = new DefaultDictionaryBinder();

The code is very flexible, only requiring the dictionary key to be of a basic type convertible from string, ie. Dictionary or Dictionary. The value can be any object that is able to be bound by the default model binder.
An example follows:
If your form input is
persons[3].FirstName=John&persons[3].LastName=Smith&persons[4].FirstName=Jane&persons[4].LastName=Doe&
and our action signature

public ActionResult SavePersons(Dictionary<int, Person> persons)

the persons parameter would be

new Dictionary<int, Person>() {
{ 3, new Person() {"John", "Smith"} },
{ 4, new Person() {"Jane", "Doe"} },
}

Simple and intuitive.

Download: DefaultDictionaryBinder.cs Simple Example Project (ASP.NET MVC 3 required)

Thinking about Geolocation APIs for Windows Mobile

Saturday, December 12th, 2009

Since owning a WinMo phone (or windows phone?), I’ve been thinking of developing some real applications on it. Currently, Geolocation is all the rage, allowing a application to respond different depending on your current location. This is done automatically via different mechanisms such as the most obvious and accurate one, GPS, and less reliable ones such as Cell Tower ID and nearby WIFI hotspot mac addresses.

So I set about searching for a Geo-Location API for windows mobile. Unfortunately, compared to Android and iPhone, the WinMo API is severely lacking in this regard. There seems to be some support in the next version of the .NET Compact Framework (4), but nothing in the current released APIs.

So I set about looking at third party APIs, most notably Google Gears. Google Gears is a framework that plugs into browsers, giving web pages expanded functionality such as offline storage. It also provides what appears to be, a comprehensive Location API, supporting gps, cell ID, and wifi for positioning and returning the Longitude/Latitude and street address. There are 2 gear plugins available for Windows Mobile, one for IE Mobile and one for Opera Mobile. The gears framework API seems to be available only to web browsers, thus web page developers, but not normal application developers.

So I set about seeing if I can access the google location web service directly. Helpfully, google posts the web service API specifications to build your own location API service provider. Unfortunately, it doesn’t tell you where the google service end point is. According to this page, google only allows interaction with the location service via Gears API. So it seems that even if you sniffed out the end point URL, you’ll be in violation of the google TOS to use the service.

But all is not lost – a workaround to all this, is to somehow embed Google Gears in your own application. Since google gears is open source software, BSD licensed, you can freely embed and distribute it along with your application. Searching the web, there seems to be very little information regarding embedding. Looking at the source, there are code relating to integrating with specific browsers. Ideally, we should link with a distributed google gears runtime by emulating an already defined browser interface. The NPAPI interface seems to be the most hopeful. I suspect Gears for Opera Mobile uses the NPAPI interface.

My aim is to provide a Windows Mobile .NET CF interface to the location api of google gears. If I am successful in that endeavour, there will a part two of this post. If not, I hope this post helps someone out there.

Quick tip: Why is my service binding to ipv6 localhost instead of ipv4?

Saturday, December 5th, 2009

So you just got a brand new VPS and installed a service, say PostgreSQL onto it. You then run your web application and found it complaining that it can’t connect to 127.0.0.1 on port 5432. Since you’re a seasoned administrator, you verify it by doing netstat -an. To your surprise, you find postgresql is binding to ::1:5432, the ipv6 localhost address. You curse the VPS provider for enabling and giving you an ipv6 network interface. You don’t even need ipv6 until 2050! But all is not lost. The reason why postgresql is binding to ::1:5432 is because it binds to localhost, which points to both ::1 (ipv6) and 127.0.0.1 (ipv4). The solution is simple. Open up /etc/hosts and find a line that says

::1             localhost

and comment it out. Restart postgresql or any other service and enjoy dotted-quad goodness again.

Javascript snippet to convert raw UTF8 to unicode

Saturday, October 3rd, 2009

For the I-don’t-a-sane-use-for-this department comes this piece of code which takes a stream of raw UTF-8 bytes, decodes it and fromCharCode it, rendering it in a unicode supported browser. A possible use would be if the web page character set is not UTF-8 and you want to display UTF-8. To use it, just put it in a script tag and call utf8decode(myrawutf8string). But seriously, all web pages should be UTF-8 by default nowadays. Here it is, in case anyone wants it:

function TryGetCharUTF8(c, intc, b, i, count)
		{
			/*
			 * 10000000 80
			 * 11000000 C0
			 * 11100000 E0
			 * 11110000 F0
			 * 11111000 F8
			 * 11111100 FC
			 *
			 * FEFF = 65279 = BOM
			 *
			 * string musicalbassclef = "" + (char)0xD834 + (char)0xDD1E; 119070 0x1D11E
			 */

			if ((b.charCodeAt(i) & 0x80) == 0)
			{
				intc = b.charCodeAt(i);
			}
			else
			{
				if ((b.charCodeAt(i) & 0xE0) == 0xC0)
				{
					//if (i+1 >= count) return false;
					intc = ((b.charCodeAt(i) & 0x1F) << 6) | ((b.charCodeAt(i + 1) & 0x3F));

					i += 1;
				}
				else if ((b.charCodeAt(i) & 0xF0) == 0xE0)
				{
					// 3 bytes Covers the rest of the BMP
					//if (i+2 >= count) return false;
					intc = ((b.charCodeAt(i) & 0xF) << 12) | ((b.charCodeAt(i + 1) & 0x3F) << 6) | ((b.charCodeAt(i + 2) & 0x3F));
					alert(b.charCodeAt(i) + ' '+b.charCodeAt(i + 1) +' '+b.charCodeAt(i + 2));
					i += 2;
				}
				else if ((b.charCodeAt(i) & 0xF8) == 0xF0)
				{
					intc = ((b.charCodeAt(i) & 0x7) << 18) | ((b.charCodeAt(i + 1) & 0x3F) << 12) | ((b.charCodeAt(i + 2) & 0x3F) << 6) | ((b.charCodeAt(i + 3) & 0x3F));

					i += 1;
				}
				else
					return false;
			}
window.utf8_out_intc = intc;
window.utf8_out_i = i;
			return true;
		}

function utf8decode(s) {
	var ss = "";
	for(utf8_out_i = 0; utf8_out_i < s.length; utf8_out_i++) {
		TryGetCharUTF8(window.utf8_out_c, window.utf8_out_intc, s, window.utf8_out_i, s.length);
		ss += String.fromCharCode(window.utf8_out_intc);
	}
	return ss;
}

Quick Tip: The platform “Windows Mobile 6 Professional SDK (ARMV4I)” is not defined within Visual Studio.

Sunday, September 6th, 2009

If you are setting up Qt Visual Studio Addin in Vista and get this message when trying to add the Qt folder (in Qt Options > Qt Versions):
The platform “Windows Mobile 6 Professional SDK (ARMV4I)” is not defined within Visual Studio. Make sure you have installed the required SDK.
-or-
The platform “Windows Mobile 5.0 Pocket PC SDK (ARMV4I)” is not defined within Visual Studio. Make sure you have installed the required SDK.

You need to make sure you have Visual Studio running in Administrator mode. You also need to be in Administrator mode when creating your WinCE project.

You can also type in the command line: checksdk -list to check that you have the correct Windows CE SDK installed.

Getting the intersection points of two [path] geometries in WPF

Friday, August 28th, 2009

While working on an app that utilises geometries in WPF, I needed a way to get the intersection points of the lines of two arbitrary geometries. A google search didn’t yield any useful hints except a post suggesting to use mathematics. That would be ideal for very simple geometries like lines, but with complex geometries, it becomes tiresome real quick. The framework doesn’t seem to have any built in functions that calculate that, so it’s time for some hack and slash.

After a few days of thinking, I came up with a simple, yet effective (but not the most efficient solution). For those who just want the intersection between two geometries, there is the CombinedGeometry geometry class which takes input in the form of two geometries. Setting the GeometryCombineMode to Intersect gives a geometry which is the intersection of the two. At the otherside of the WPF realm, we have Geometry.GetWidenedPathGeometry(). This method basically converts/strokes path lines to an approximate geometry. Combining these two concepts, we can produce an intersection from two widened path geometries (the two paths which we want the intersection of).

public static Point[] GetIntersectionPoints(Geometry g1, Geometry g2)
{
Geometry og1 = g1.GetWidenedPathGeometry(new Pen(Brushes.Black, 1.0));
Geometry og2 = g2.GetWidenedPathGeometry(new Pen(Brushes.Black, 1.0));

CombinedGeometry cg = new CombinedGeometry(GeometryCombineMode.Intersect, og1, og2);

PathGeometry pg = cg.GetFlattenedPathGeometry();
Point[] result = new Point[pg.Figures.Count];
for (int i = 0; i < pg.Figures.Count; i++)
{
Rect fig = new PathGeometry(new PathFigure[] { pg.Figures[i] }).Bounds;
result[i] = new Point(fig.Left + fig.Width / 2.0, fig.Top + fig.Height / 2.0);
}
return result;
}

The function will return an array of zero or more points of intersection. To test it

sg1 = StreamGeometry.Parse("M0,0 L100,100");
sg2 = StreamGeometry.Parse("M0,100 L100,0");
Point[] pts = GetIntersectionPoints(sg1, sg2);
// pts[0] is {50,50}

Hope this helps someone.

The curious case of WindowsFormsParkingWindow

Monday, July 27th, 2009

I was debugging a problem the other day involving WebKit.NET, a webkit wrapper control for winforms. When the webkit control was hosted inside winforms, it had a strange problem of always thinking that it is out of focus. This had the effect of drawing all selections as grayed out.

Everything I threw at it (WM_SETFOCUS, WM_ACTIVATE) seemed to be going into a void, so it was time to break into the source and figure out what exactly was wrong. After a few breakpoints and step overs, I found that the WebKit control searches for the parent window and listens to its messages by subclassing the window. It listens for WM_NCACTIVATE event and then determines whether it has focus or not.

This was working exactly as expected on a normal non-winforms window, so what was different? Debugging the code, I found that it got the root parent window as WindowsFormsParkingWindow. Why is it returning that as the parent window and not the actual parent window I’m not entirely sure. Maybe it’s some special super root window like the Application window in Delphi? It wasn’t shown in Spy++ either. Then again what’s a WindowsFormsParkingWindow? It’s something that I ought to google. Unfortunately google wasn’t very forth coming. Puzzled, I devised a hack by simply temporarily unassigning the immediate parent window of the webkit control WS_CHILD, simply because the webkit find ancestry detection algorithm stops when it encounters a non-child. After the setHostWindow() call, I make the parent window WS_CHILD again. That seemed to work but something lingered in the back of my mind telling that there is a better solution.

The next day as I was about to post a solution on the mailing list describing my solution, just when I was about to talk about this weird WindowsFormsParkingWindow, something in my mind clicked. Suddenly it all seemed to make sense. There was a reason WindowsFormsParkingWindow wasn’t in the tree ancestry when I looked at Spy++. There’s also a reason for the name. It turns out that on creation, all controls get put into WindowsFormsParkingWindow. It just so happens the setHostWindow call was made in the constructor when the parent control was still parked. The solution seemed obvious now. The setHostWindow should be called after the parent is correctly set, ie on the Load event. So, another case closed.

Compiling WebKit/Cairo on Windows with Visual C++ Express

Sunday, July 26th, 2009

Just for interest, I decided to build webkit on Windows. This supposed to be a painless task but unfortunately, anything that involves build scripts creates drama. The instructions on compiling are a bit scant, giving the impression that it’s super easy. Maybe it is and I’m just a bit dumb, but anyways after a few hours battling with it I finally got it working. Don’t bother trying with Visual Studio 2008 as you might as well jump off a cliff from compilation errors – Get the Visual C++ Express 2005 edition and SP1 patch. Here are the steps from scratch:

Go to http://nightly.webkit.org/ and get the source tar.bz2.

Extract it somewhere (WinRAR is a good tool for this). This somewhere will now be referred to as {EXTRACTED}.

For compiling on windows, you need windows Download the WebKitSupportLibrary.zip then copy this zip file on the root of your extracted webkit folder. Don’t extract it. This zip gives you unicode/uchar.h or pthread.h which would otherwise be reported missing.

So what’s the difference between webkit/cairo and regular webkit? The regular webkit depends on proprietary Apple libraries such as CoreGraphics. The webkit/cairo build substitutes that dependency with the free Cairo 2D graphics library. The library has a clean C API and contains very compehensive drawing routines. It also sports multiple output backends allowing you to create PDFs or SVGs.

Webkit/cairo has more dependencies on open source libraries such as curl. You either build them or get the pre-built ones some nice folks have put online – Get it here and extract it to a place like {EXTRACTED}\requirements.

Now you have to install Cygwin as noted here on point number 3. The important point I want to highlight is due to some assumptions made in the VS project files, the directory HAS to be: at c:\cygwin (or $(SYSTEMROOT)\cygwin). For Vista, you need to perform additional minor gymnastics which I’m not going to outline here. Read it on the previous link.

You also need to get the Quick Time SDK. Annoyingly, to download quicktime SDK you need to register a Apple Developer Connection (ADC) account. After entering details of your daily life, you’re grant access to the file. Good thing was that you don’t need quick time or itunes installed. You should probably keep the default install directory as well.

Next is setting two environment variables. This involves going into the System Properties in your Control Panel. You can just put add it under the User variables:

  • WEBKITLIBRARIESDIR – point it to your {EXTRACTED}\WebKit\WebKitLibraries\win
  • WEBKITOUTPUTDIR – point it somewhere like c:\webkitdist (create this directory as well)

You will now need to add some VC++ paths. Open C++ Express and go to Tools > Options > Projects > VC++ Directories

On the top drop down, select show directories for include files and add

  • {EXTRACTED}\requirements\include
  • {EXTRACTED}\requirements\include\cairo
  • {EXTRACTED}\requirements\include\curl
  • {EXTRACTED}\requirements\include\libpng13

then select show directories for library files and add

  • {EXTRACTED}\requirements\lib

Lastly in the Executables files section add

  • C:\cygwin\bin – Put this just above $(PATH) but after all the other directories. This is important as if you put it on top, cygwin’s link.exe will conflict with MSVC’s, and you need to put it above $(PATH) or the PATH directories that have similarly named binaries to cygwin’s will conflict.

You will also need to get the Platform SDK as noted in the build instructions if you don’t have it already. Any recent version of the SDK should be alright. Add the executable, include and lib directories to the VC++ directories like the above, described here. The instructions about vcprops editing aren’t really important.

For the include path, you also need to add the mfc includes or the compiler will complain about missing winres.h

Due to some bootstrapping scripts, the first time you compile you can’t do it through the Visual C++ IDE. You will need to compile it via the command line in cygwin. Open the cygwin shell and change directory to {EXTRACTED} ie cd c:/webkit/

Then run:

WebkitTools/Scripts/update-webkit

After it completes, you can start building

WebkitTools/Scripts/build-webkit --wincairo --debug

Remove the –debug flag if you want to compile for Release. Note: Previously the wincairo flag was cairo-win32.

After the first successful build, you can now open {EXTRACTED}\WebKit\win\WebKit.vcproj in Visual Studio. Make sure the build profile is set to Debug_Cairo, set it. You can choose Release_Cairo as well if you so wish. Finally, winlauncher is the test browser you use to try out your new build, so set that as your active project. Don’t forget to copy all the requirements dlls (ie cairo.dll) into the dist\bin folder where winlauncher.exe is or else it’ll complain about missing DLLs.