Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following line of code have the SQL injection vulnerability, where id is an

ID: 3808139 • Letter: T

Question

The following line of code have the SQL injection vulnerability, where id is an input.

String query = "select name from students where id = " + id + ";";

a) Show an exploitation that always makes a true condition of the query.

b) If id is of type integer, discuss two security methods to prevent the injection.

c) If id is of type char, they query string will be the following. Show an exploitaiton that always makes a true condition of the query.

String query = "select name from students where id = '" + id + '";";

Explanation / Answer

String query = "select name from students where id = " + id + ";";

If we put id variable value as "1 or 1=1", then whole query becomes,
select name from students where id = 1 or 1=1;
Here 1=1 is always true, and hence can exploit the functionality.

In case of character key,
String query = "select name from students where id = '" + id + "';";

making id variable as a' or 'a'='a
It will make the whole query as:
select name from students where id = 'a' or 'a'='a';
Hence always true.


To avoid this scenrio, you should always sanitize the inputs from the user, whether they are in expected format or not. Like, For an id field, it should only have numerical characters or alphanumeric, but no puncuation mark or quotes is required. You can sanity check these before executing the query.

Second approach is of parameterized query. Based on what programming language you are using, each language provide parameterized sql query which is of format:

"UPDATE cakes SET price = ? WHERE cake = ?"

and these ? marks are replaced at runtime by sql engine using your inputs.