Don’t you dare to inject SQL !

Well, it’s just another post discussing sql injection but from defensive perspective. We all know how dangerous sql injection can be, so how do we prevent it from happening ?

There are multiple ways:-

1- Whitelisting

2- Stored Procedure (Not So Safe which we will look into in another post)

3- Prepared Statements / Paramterized queries

Before we proceed the source for entire application can be downloaded from here:-

Below is the code for vulnerable controller that handle user input passed from user.

As we can see that on line 55 model.Id is being passed directly to SQL statement without being sanitized / parameterized. This allows attacker to inject arbitrary SQL queries.

Let see this in action

Now if we try to inject any other query we have breakout of developer’s query context or use stacked query approach:-

We can clearly see that the application responded after 10 seconds which confirms that injection worked, time to extract data using our favorite tool (SQLMAP)

The Fix

Now to fix this issue we will implement third approach discussed in this post i.e parameterized query so basically what parameterized query does is that it ensure the data passed from user input do not break the actual query.

Now if we try to inject again it’s will fail