Protecting Applications against CSRF attacks

Briefly, what is CSRF?

CSRF stands for cross-site-request-forgery. It is an exploit of a website where an attacker constructs a request and has a victim execute it on the attacker’s behalf. In the past few years, a flurry of major CSRF attacks has thrust this type of exploit into the limelight yet many applications still do not protect against it.

In this post, I won’t go into how to defend against CSRF attacks, but instead review several solutions I’ve come across and provide some of my own opinions for them. For a better description of the CSRF exploit and how to prevent it, here are some really good articles for you to read:

Custom Solutions

With CSRF attacks in mind, it actually takes little additional development cost to integrate a CSRF defenses into a new project. One of the simplest ways to prevent most CSRF related exploits is to append and validate a security token to every request made to your application.

At the basic level, all CSRF libraries must accomplish the following 3 actions:

  1. Generate a token (per session or request) and store it in the session.
  2. On each request, validate the token sent by the browser against the one store in the session. (probably
    implemented as a filter or interceptor)
  3. Handle user specified unguarded or landing pages.

In addition, each form on all your pages will be responsible for sending the token on submission.


Not tied to any existing CSRF library conventions or limitations. Many CSRF libraries currently available restrict the application to conventions that the application must follow. For example, some libraries restrict applications to only POST requests. This may or may not be acceptable to your client. In addition, many libraries may have crippling limitations that prevent you from using 3rd party solutions “out of the box”.

Many frameworks support the token synchronization pattern built in to prevent double submission of forms. Though it
does not provide 100% protection from CSRF attacks, it can be used as the basis to protecting your application against CSRF attacks.


Increased development costs – Regardless of the approach, defending against CSRF attacks do increase cost of the application and developing a custom solution is typically the highest cost. That being said, the cost of retrofitting an existing application to guard against CSRF exploits is far more costly. The costs of dealing with a security breach can be significantly higher.

Non-global Solutions – Many custom CSRF solutions are “exclusive” in the sense, developers choose when to add CSRF protection to specific requests. “inclusive” solutions protect all URLs by default and developers are able to explicitly state unguarded pages. Developers tend to code pages as unprotected and them protect them later. This is highly error prone in “inclusive” solutions and can leave large portions of the application unprotected if they forget to protect them.

Missed Vulnerabilities – With a custom solution, you greatest asset (and weakness) of your CSRF defense is your team
of developers. As with other open-source libraries, open-source CSRF libraries benefit from a large community
continuously providing feedback, updating the source, and thus making the library more effective.

3rd Party Libraries

In the Java world, I’ve worked with OWSAP’s CSRF Guard library. So this will be the bases of my review on “3rd party libraries”


Provides adequate out of the box protection against CSRF guard attacks. It is a well-established library with ‘some’ community support.

Require minimal configuration to get started.

Once installed, all URLs are protected by default. Developers must specify unprotected URLs.


By using a 3rd party library, you are tied into their conventions and limitations.

  • CSRF Guard’s configuration file for defining new landing page and unguarded pages requires the context-root as part of the URL. Pattern matching for unguarded URLs is extremely limited.
  • When going to the new token landing page, CSRF Guard changes the title of the browser to “new token landing page”. Not only does this expose the underlying security library, it can be a total showstopper to the client.
  • Verbose logging is on by default.


In conclusion, CSRF Gurad provides adequate CSRF protection but there are some limitations that make it hard to work with. Custom solutions are…custom. You have to build and maintain it. Custom solutions give you the flexibility to be as tight or loose as you need but with this flexibility comes with the risk of exposing too many CSRF vulnerabilities by accident. So there you have it, as I become more exposed to additional CSRF libraries, I will continue to update this post.

Grails: First Project

Groovy and Grails has been much talked about in the last couple of years and though I’ve fooled around with small sample projects I never really had the chance to do anything more. Recently, a client approved to use Grails on a new J2EE web application and this will be my first time using it on a large complex system.

There are many postings that talk about the general positives of the framework, but in this article, I want to focus on what worked and didn’t in my project and in particular, what didn’t work. My hope is after you read this article, my insights on using Grails for the first time will help you make the right technological decisions for your project.


I am no Grails expert.

The team started up with Grails very quickly. As new members joined the team, the overall ramp up time was, as advertised by Grails, very quick and pain free. As you all many know, ramp up and installation of traditional J2EE applications can be extremely painful and take a lot of time, so the ease of ramping up new members was a great relief.

The transition between traditional J2EE to Grails was easy. I would attribute this to the “Convention over Configuration” paradigm that Grails (and Rails) use. By understanding the convention and looking at samples and existing code, developers were able to focus on implementing business logic rather then figuring out how XML configurations and flows work.


  • Easily change the domain model without having complex SQL migration scripts.
    With a domain model actively changing thoughout early development,
    incorporating the changes in short time would not have been possible.
  • Most of the advantages as advertised by Grails worked for us.
    Such as: clear built-in separation of environments, GROM, automatic binding, etc
    See the additional resources for a other postings on the advantages of Grails.
  • Active Groovy and Grails community. Even for a new framework, there is substantial
    knowledge on the internet and questions are quickly answered by the community.
  • The small things: Groovy syntax, smoother development, integrated environment.
    All that dynamic synamic syntax and sugar code.


  • The installation of the plugin in directories outside the project and
    overall in-house plugin setup via the IDE added much confusion during the
    periods of active development of those plugins.
  • Though Springsource’s STS Eclipse integration with Grails is pretty adequate,
    there are some annoying gotcha’s that keep creeping up, especially dealing with
    the installation of in-house plugins.
  • Some developers can to revert back to standard Java techniques when exposed to
    difficult situations. For this reason, I found code reviews very important.
    Detected in reviews, the more experienced reviewer can often pass knowledge on
    how to solve a particular problem the Grails way.
  • Though novice developers can quickly become significant contributors, without
    a solid knowledge in Spring or Hibernate, it is often left up to the more senior
    members to deal with strange Hibernate errors.
  • We are developing the application using the built-in Grails development
    (Tomcat and Java DB) environment. However, the test and production
    environments are using a WebSphere server and Oracle database. Though development
    though Grails is faster, we have seen a number of gotcha’s
    during our switch over to the WebSphere and Oracle database.
  • These compatibility issues do not produce meaningful Exceptions messages and
    usually require a trial-and-error approach to figure out the problem. Examples
    are restricted Oracle keywords used as properties on domain objects and issues when
    Controllers and Domains share the same name as certain WebSphere classes.
  • It remains to be seen how well the client’s IT teams will adapt to
    this new technology.

In conclusion, I would recommend Grails as a framework going forward. Much of Grails’s advertised benefits are true and work. The big question remains is how organizations who are used to traditional J2EE frameworks such as Struts and Spring can adapt to using dynamic language frameworks such as Groovy.

As development continues, I will update this blog entry.

Additional Resources

Here are some additional resources to help you decide if Grails is right for you.


In my spare time, one of the things I do is practice Kendo. Kendo is a Japanese martial art that uses sword-fighting based on traditional samurai swordsmanship. You can find a more information here: Kendo

I’ve been practicing it for 3 years now and I absolutely love it. I also practiced Karate when I was younger – for 10 years, and if I had to choose which I would continue, it would be Kendo hands down. To be fair, Karate and kendo are drastically different sports and to compare them is not fair.

I find kendo to be more physically demanding then karate. Many of the kendo drills focus on increasing stamina and you are always pushed to your limit. I also feel that kendo is more full-contact then karate. karate focuses on kata and other solo practice and even though there is a sparing component, contact is kept minimal to prevent injuries. In kendo, even with strict rules, there is enough freedom so the feeling of competitiveness is not lost.

Though karate is more popular in North America, this popularity has come with an unfortunate cost as the perception of it has been polluted by corporations whose sole goal is to make money instead of teaching the true values of the martial art. This has led to the manifestation of the ‘black-belt’ culture. Many people join clubs with the sole goal of achieving a black belt and bragging about it to their friends. Of course, this leads to many corporations simply handing out black belts as there is no real single international organization to maintain standards.

Most clubs you see on see being advertised on tv are only there to make a quick buck. Much of them fall under two categories: clubs that cater only to children (rather, to their parents) or black-belt mills. In karate, individual clubs have different standards for skills associated to a belt (or rank) thus many clubs arbitrary give out black-belts to unqualified students so they will continue paying their monthly fees. If you intend to start practicing karate, it is best to do some research to find a proper club and receive proper karate training.

There is nothing really ‘wrong’ per se about karate clubs that focus only on children. Children will benefit from the exercise and confidence building that is taught, but, the ‘belts’ or ranks issued by these clubs are often not respected by more serious karate clubs. In addition, many of these clubs do not have much karate development for young-adults/adults. Once your child reaches a certain age, they need to go looking for another club with a better adult focus.

Kendo has better international organization, to the extent that all clubs are a member of one organization, the International Kendo Federation (though IKF’s country specific affiliates such as the Canadian Kendo Federation or Kendo America). If you are in Canada, and your club is not a member of the Canadian Kendo Federation, then you should start looking for a club recognized by the federation.

Joining a ‘legit’ kendo club ensures your instructors are held to a certain standard and that you will be getting proper training. It also means that you can participate in officially sanctioned tournaments.

Though kendo has ‘ranks’, it does not have this ‘black-belt’ culture that has almost ruined karate. Gradings, events in which individuals may try and achieve a higher rank are sanctioned by the federation and they determine if an individual is awarded or not (as opposed to individual clubs issuing ranks). The goal is to try and maintain a standard level of skill associated to a rank across the sport. This lack of a standard has always bothered me about karate (that one club’s black belt can be dramatically different than another clubs’).

Proper clubs also teach philosophical and spiritual aspects of their sport as all Japanese martial arts teach more than just fighting. They also teach the proper etiquette, respect and Japanese culture. This is often lost in black-belt mills.

Though I currently enjoy kendo more, I don’t regret the 10 years I practiced karate. Karate is still a good martial art and there are many reasons why you should practice it. Even with all the negatives surrounding karate at this time, with a little research you can easily find a very good club in almost all major cities.


These Things Annoy Me

(And probably annoy you too)

In this post I’m just listing out some CSS gripes I’ve seen and their annoyance based on my scale here:

Slightly Annoyed


Really Pissed

<%= image_tag "articles/badcss/level.png" %>

Example 1

Please Don’t Do This:

		<div style="color:red;">
			You have not entered a name.
		<div style="color:gray;font-size:12px">
			Name: <input type="text" size="20" name="name"/>
		<div style="color:gray;font-size:12px">
			Address: <input type="text" size="20" name="addr"/>

because that makes me have to do this:

		<div class="error">
			You have not entered a name.
		<div class="labelInput">
			Name: <input type="text" size="20" name="name"/>
		<div class="labelInput">
			Address: <input type="text" size="20" name="addr"/>


	.error {
	.labelInput {

Example 2

Please Don’t Describe What the CSS is Doing

		.highlight-red {
		.left-align-input {

Example 3

Please Don’t Add Default Styles to Elements

		.error {
		table {
		p {
		articleContent {

because that makes me do:

		.error {
		table {
		p {
		articleContent {

or add my own css to P and Table elements I do not want your crappy style applied to.

Example 4

Stay back! I don’t want to catch your divities.

		<div id="out-wrapper-div">
			<div id="inner-wrapper-div">
				<div class="inner-wrapper-input">
					<span class="input-span-wrapper"><input type="text" name="name"/></span>
		<div id="out-wrapper-div">
			<div id="inner-wrapper-div">
				<div class="inner-wrapper-input">
					<span class="input-span-wrapper"><input type="text" name="addr"/></span>

Example 5

Important! Don’t abuse !important

There has been much discussion on when is the right time to use !important, so and there are valid reasons to use it. Do not abuse such power.

		p {
			margin-right:20px !important;
			font-color:red !important;
			font-size:6px !important;
			padding-left:0px !important;
			margin:0px !important;


Example 6

You can actually add arbitrary text to HTML using CSS. No matter how experienced you are, there will be times where you forget this and spend needless time digging around trying to figure out how this magical text appears only to find out it was produced by CSS.

Doing this like:

		#copyright:after { content: "Copyright 2011 John Smith"; }
		#homeLink:after { content: "Home";}

makes it really hard to find out which JSP / GSP / RHTML / ETC ‘view’ is rendering it which means I now have to go digging around your javascript and CSS files for content that has been added by CSS.

Example 7

Group related styles

		table {
		.error {
		tr {
		#navbar {
		th {
		.hello {
		td {

My Bonsai Tree

The area around my desk has always been lacking of any foliage. I’ve tried to put plants around it, but they keep dying as if planted on some cursed land. The logical reasoning is that they died primarily because I keep forgetting to water them but also the lighting conditions were not suitable.

As a Christmas gift this year I received a new plant, a bonsai tree. It’s not the first time I’ve received a bonsai tree as a gift but the previous one died…and it died quick. I watered it but it kept shedding needles and making a mess all over the place. Eventually it stopped shading (which was good), but then it turned brown and died (which was bad).

For those who don’t know, bonsai is a Japanese art form using miniature trees grown in containers . In English, the term bonsai routinely refers to the growing and shaping of any tree in a conditioner and does not need to follow any traditional Japanese bonsai techniques. If you go to a exotic plant store, you will see both traditional bonsai and non-traditional miniatures(using exotic tropical tree species).

It takes years of careful shaping and pruning to “train” a tree to become a “bonsai”. Not only do the leaves have to be pruned but so do the roots. Copper or steel wires are often used to help shape the trunk. In traditional bonsai, the art is in making the tree look like a miniature version of a real tree you would find in nature. This includes the weathered/aged look of the bark, the shape of the trunk after many decades of harsh weather, and the size of the foliage.

Not all bonsai trees are small. Bonsai’s can actually range in size from the very small (in contains only a few inches in diameter) to very large (over 80 inches). Some of the larger bonsais are actually more than 6 feet tall. Being trees, bonsais can live for a very long time, with the oldest trees being over 500 years old!

It turns out that many species of trees used for bonsai are for temperate climates and are unable to survive indoors for long periods of time. They are actually meant to be placed in pots outdoors. This recent bonsai tree I received is supposed to be cultivated for indoor conditions. It “should” survive in room temperature and indoor humidity conditions all year long but giving the bonsai enough light will still be a problem.

So here’s to hoping this new bonsai tree survives the year!

Why I love Angry Birds

For a while now, Angry Birds has been one of the top selling games on iTunes. There’ve been many articles why this game has been such a success, in particular this great breakdown , but I thought I would share the reasons why I like this game so much.

The reasons why I like Angry Birds

Even though you still need your other hand to hold the iPhone, you can play the game fully with one hand. This is particularly handy when you are on the subway or bus. One hand is firmly holding the iPhone and the other hand can easily reach a pole or wall if you suddenly become unstable. In games that require two hands, both hands are positioned for the game rather than holding the iPhone. If the bus suddenly hits a bumpy stretch, you have to stop playing, reposition one hand to hold the phone more firmly.

Angry Birds allow users to easily decide if they want to leisurely play though the levels or challenge themselves by trying to obtain 3 stars (or feathers). I usually unlock all the levels then go back to obtain 3 stars.

There are many articles analyzing the UI design. I agree with most of them. 🙂

Nothing is more satisfying then throwing items into blocks and watching them smash.

I really love the intuitive game play and controls. The slingshot, aiming, and power are all very intuitive in their design so anyone can understand how to use them and improve on getting better. The concrete, wood, and ice blocks are all obvious for users to understand that some are stronger them others. The helmet is a great way to introduce “stronger” enemies without complicating the game with more characters.

When birds are introduced to the user for the first time, they are not forced to read the manual. Instead, the game provides a short introduction video and starts users off with easy levels to learn the characteristics of the new bird.

Unlike time killer games that have no long-term goal – and simply send the user back to “level 1” when restarted, Angry Birds challenges users to keep playing to achieve a long-term goal. This goal could be unlocking all levels or obtaining 3 stars, but it keeps users to continue playing.

This is the perfect game for playing on the subway or bus. It doesn’t require uses to pause if interrupted, levels can easily be restarted, and as started before, only requires fingers from one hand to play. It can be closed and restarted at the very point the user left the game.

And that is why I like Angry Birds.

What is Photodynamic Therapy?

I was once a researcher at Princess Margret Hospital (part of
University Health Network) and participated in a research group which
involved photodynamic therapy to treat cancer. I just wanted to share
a tid-bit on what we did there and what came out of it.

What is Photodynamic Therapy?

You can read a detailed description here
, but in a nutshell, it
is a form of cancer treatment which involves injecting a tumor with a
drug that is activated by light. The drug can injected or taken orally
and the light can come from external or internal (via fiber optic
cables) sources.

The Problem

After injecting the drug into the tumor, it does not stay within
the bounds of the tumor and is absorbed by the surrounding
tissue. In prevent damage to the surrounding tissue, the key
is to only “activate” the drug that resides within the tumor. Light is
emitted from the light source in a radial pattern and the “intensity”
of the light dimishes as you travel further from the source. The loss
of “intensity” occurs in a pradicitable manner and thus given a light
source, tissue properties, and distance, one can measure the light and
thus “strength” of the drug at any given position.

Because light is emitted radially outwards like a sphere, it is
difficult to achieve the correct light intensity in irregular shaped
tumors. In particular, it is very difficult to achieve good solutions
for tumors with sharp edges (think about a box full of balls, there is
always some amount of empty space). The key is to try and achieve the
correct dosage within the tumor tissue and no drug activation outside.

Modeling the Problem

Before starting, we had to model the
problem. We used Matlab (with embedded Java) to model the problem in a
3D environment. For our test tumor, we decided to use the sine
function with each point rotated around the axis creating a 3D object.
Within the test space, we picked N number of points (inside and
outside the tumor) for which we computed the expected and actual
dosages. These would be our testing points.

The Computational Problem

Here in lies the computation problem. We have several light
sources and testing points within the tumor. The goal is to set the
intensity of the sources such that we get the correct activation level
of the drug at all of our testing points.

Simulated Annealing

This problem is complex…it is not possible to generate all
possible solutions and choose the best case. However , one could
generate a initial solution and keep tweaking values. Each time we
teak a value, we compare its outcome (cost) with the current outcome
and take the better solution. This will eventually lead to a solution
in winch tweaking of the sources leads to no more better solutions.
This is called a local minimum and unfortunately, finding a local
minimum does not guarantee it is the overall best solution (or global

To get around the problem of becoming stuck at local minimums,
we decided to go down the route of using probabilistic algorithms to
determine a “good” solution and in particular, decided to use
Simulated Annealing(SA).

In SA, we start off at some initial solution and teak several
light sources as before but at each step, when determining to accept a
particular solution, we allow for a probability to accept a worse
solution. This allows us to “jump” past local minimums.
Mathematically, this can allow the algorithm to eventually find the
global minimum if we run the program for a very long time.

The Cost Function

For each solution generated, we have to evaluate the quality of
the solution. This is done via the cost function. For our problem, we
looked at each testing point and compared the drug activation at that
point with the required amount. We then took the difference and
applied some multiplier. The multiplier was used to emphasize how
important it was for a testing point to be close to it’s required
dosage. For example, if tumor existed near a vital organ, the
multiplier on points within the organ would have extremely high

In the end, it was determined that SA had a difficult time generating “good” solutions.
If often found solutions that could not be easily manufactured in a optic fiber. We also
found that letting the algorithmic run for a long time did not generate better solutions.
That being said, there was a lot discovered. Researchers learned what factors affected the
algorithm, and what worked and what didn’t. It was also a great learning experience for me
since it was my first time participating in a research group.

You can see the full results from the published paper here:

A. Rendon, J. Okawa, R. Weersink, J.C. Beck and Lothar Lilge, Conformal light delivery using tailored cylindrical diffusers,
Optical Methods for Tumor Treatment and Detection: Mechanisms and Techniques in Photodynamic Therapy XVI, 2007.

Hello world!

I finally got around to building my second iteration of my website. Though my first site served me well, I wanted a new site that would allow me to fool around with the latest and greatest libraries around. I also wanted a site layout in which I could present my opinions better.

Welcome to my general “tech” blog. This is where you will find any work or technology related ramblings. You can find my general topic or ‘fun’ posts here.

My current site is still using Ruby On Rails, but I had originally built it out of Groovy on Grails. I decided I wanted to keep my current server, so ported all the code over the Rails. That in itself was a interesting project even though the application is small. I also want to experiment with different technologies, mainly, using rails and javascript frameworks.

I hope to be constantly making upgrades in the near feature.

Favorite movie genre: Contagious Diseases

People often ask me what my favorite type of movies are, and by far, my favorite genre is horror. Specifically within horror, my favorite topics are about virus outbreaks. I prefer the recent movies rather then the classics because I find the classics tend to be corny and the special effects just don’t cut it.

In addition, I prefer darker themed movies with a serious plot rather than movies such as Dawn of the Dead or Zombieland where the entire story is about people running around shooting and hacking at anything that moves. I’m not a huge fan of comical zombie movies either.

I’ve decided to keep a ongoing list of my favorite outbreak movies here on this post. As I see movies I like, I will add it to this list. In many zombie movies, the zombification of humans are caused by a viral outbreak so you will see a lot of zombie movies in this list as well.

Outbreak (1995) – A “modern classic”. The film focuses on an outbreak of a fictional Ebola-like virus and how far the military and civilian agencies might go to contain the spread.
28 Days Later (2002) A zombie horror film directed by Danny Boyle. The plot depicts the breakdown of society following the accidental release of a highly contagious “rage” virus.
28 Weeks Later (2005) A sequel to 28 Days Later. Over the course of 28 weeks following the original outbreak, the infected have apparently all died, primarily of starvation, and Britain has been declared relatively safe. One day a person who is immune (but still infected and thus a carrier) is found and all goes wrong afterwords. The opening scenes of the film which shows the heavily fortified US Army safe zone is well done.
Crazies (2010) A small town’s water supply is infected with a biological weapon and now the Army must try and stop its spread. The movie is about how a doctor and her family try and evade both the Army and the infected. The scene of the Army medical camp and quarantine facility was my favorite part in the whole film.
Rec (2007) A Spanish horror film about a young TV reporter and her cameraman who cover the night shift at the local fire station. They tag along during a call to an apartment building where they find a woman in a crazed state. Soon after, the building is quarantined by the police and the residence soon find out that a virulent disease is infecting people, causing them to turn into bloodthirsty savages. This film was re-made in the US retitled, Quarantine.
Rec 2 (2009) A sequel to Rec (2007), a doctor leads a swat team into the apartment to obtain a blood sample from an infected girl but are attacked by the infected. It turns out this is not just a biological disaster but something else much more evil.
Mutants (2009) In this French film, a young couple, Marco and Sonia, have survived the initial outbreak of a deadly virus that turns people into rampaging mutants. But on their travels, Sonia decides to help a disabled child who happens to be infected and ends up infecting Marco. Sonia decides not to leave Marco, but try and help even though she knows he will end up like all the other mutants. The film’s effects were simply amazing considering it’s low budge but the storyline, specifically the choices Sonia makes I feel are so unrealistic and and against any common sense, it really destroys the movie.
Carriers (2009) This is a story about 4 American friends who are traveling across a a dead American landscape. One day, the come across an infected child and her father. They eventually help them out, but in return are infected. Though some scenes are pretty cool, the storyline and acting is so-so at best. This is more inline with a teen-horror flick with little serious plot or character development.
Thaw (2009) An Arctic expedition uncovers a deadly prehistoric parasite released by the melting ice caps. The CG parasites look terrible and the so is the ending. This little known movie surprisingly has Val Kilmer playing one of the Arctic researchers.
Doomsday (2009) After a deadly virus spreads across Britain, and Scotland is left quarantined. People in the quarantined zone are left to die, but some are immune to the virus and survive. After several decades, the virus re-emerged on the other side of the quarantine zone and the government decides to send a military team into the quarantined zone to retrieve blood samples of the survivors. As the team travels across Scotland, they are shocked to see what has become of the survivors.
Right At Your Door (2006) A dirty bomb goes off in Los Angeles and everyone is told to stay indoors and avoid contact with those infected. This little known movie turned out pretty good and the ending has a nice twist that I didn’t see coming.
Contagion follows the progress of a virus as it spreads across the world. It focuses on a team of medical researchers from the CDC as they race to find a cure. Though I found the movie to be interesting, it lacked any excitement or twist that I was craving for. The ending was predictable and un-interesting. The movie also had two subplots involving an annoying blogger (Jude Law) and a CDC medical researcher that is held hostage in a remote Chinese village (Marion Cotillard) which did not add any relevance to the main storyline.