Search
Close this search box.

A Quick Way to Stop SQL Injections

Facebook
Twitter
LinkedIn

There are many coding best practices to adhere to. These practices usually have to do with code optimization, but there are coding practices specifically focused on making the application safer. One such example is use of a parameterized query, a query in which placeholders are used for parameters and the parameter values are supplied at time of execution. This safely eliminates the threat of an SQL Injection.

SQL Injections are attacks vector that use code vulnerabilities to “inject” malicious statements that compromise the integrity of SQL (Structured Query Language) databases. By exploiting these flaws, hackers can bypass application or server authentication/authorization measures, view private data stored on the target server, alter existing data, and cause other forms of discord at their leisure. Recent victims of such attacks include Time Warner Cable and the United Nations tourism website. Fortunately, this attack vector is reasonably easy to mitigate. An example is shown below.

This query is susceptible to SQL Injection:

var query = “Select * From tblEmployee Where EmployeeId = “ + input;

If this code snippet was attached to an input and the attacker were to input something like “10 or 1=1” into the search bar of the vulnerable web app, that input would inject into the query for the return data. Instead of getting nothing in return, the attacker would be met with a display of the entire contents of tblEmployee, since “Where 1=1” is always true.

The better practice is using a parameterized query.

using (var con = new SqlClient.SqlConnection(connectionString))

using (var cmd = new SqlClient.SqlCommand())

{

con.Open();

cmd.Connection = con;

cmd.CommandType = CommandType.Text;

cmd.CommandText = “Select * From tblEmployee Where Employee = @Employee”;

cmd.Parameters.Add(“@Employee”, someone);

}

As query parameters are passed separately, parameter values cannot modify the query string.

If you, your organization or company, or someone you know would be interested in learning more about or need help with protecting against SQL Injections, please do not hesitate to reach out to Mission Multiplier Consulting. We can always be reached at info@missionmultiplier.com.

From the Archives: This post was originally published in April 2016. Minor edits and updates have been applied.

Share This:
Start minimizing your company's cyber risk
Fill out the form to get in touch with us.