![SQL INJECTION IN CMS](/sites/default/files/2024-05/0_ErN7MyOU7wjQLSgM.jpg)
Vulnerability Examples
SQL injection is an attack technique in which an attacker exploits security vulnerabilities to
inject and execute arbitrary SQL statements, thereby manipulating the database to perform
abnormal operations. There are attack types such as Error SQL Injection, Blind SQL
Injection, and Union based SQL Injection.
For example, in the code in the figure below, the $sv variable is declared using a single
quote (‘), but the $st variable is declared without a single quote (‘). Afterwards, the
constructed string is used as part of the SQL command through the sql_fetch() function.
![SQL](/sites/default/files/inline-images/image_1.png)
If you check the string configuration of the sql_fecth() function argument by inserting a random string into the st variable and the sv variable, the sv variable is recognized as a string by declaring it through a single quote, but the st variable is composed of a part of the SQL statement.
http://localhost/...(skip).../sqltest.php?st=test&sv=asdf
![SQL](/sites/default/files/inline-images/image_2.png)
Therefore, if the execution result of the st variable becomes true unconditionally, all values stored in the table can be output regardless of conditions. As a result of inserting, as shown in the figure below, if the result of the SQL statement entered is True, data is output, and if it is False, data is not output.
![SQL](/sites/default/files/inline-images/image_11.png)
How to Fix Vulnerabilities:
Use an account with minimal privileges when processing data through a DB connection in a web application.
Variables need to be declared and initialized so that they are not exploited in the script syntax
Do not dynamically generate and execute SQL queries in which external input values are inserted.
In addition, it is recommended to limit DB error messages, account separation, install web firewall, and use Prepared Statement (parameterized query)
When an SQL query statement needs to be dynamically generated using external input values, validation of the input values is performed.
- Filters not only special characters, but also spaces bypassing strings (URL encoding), reserved words, and function names
‘$function SQLI($str){
$str = preg_replace("/[\s\t\'\;\=]+/","", $str); return $str; // Remove spaces, tabs, and special characters
- Special characters: ; (semicolon) | (pipe), $ (dollar), () (parentheses), ` (back quarter), <, > (angle brackets), \ (backslash), \n (newline), LF, CR, etc.
- Bypass whitespace: (URL encoding): (), /**/, +, %09(\t), %0a(\n), %0b, %c, %0d(\r), %a0, %20 etc.
- Reserved words : UNION, GROUP BY, IF, COLUMN, END, INSTANCE etc.
- Function : DATABASE(), CONCAT(), COUNT(), LOWER() etc.
- Filter by categorizing/patterning input values regex with whitelist where possible
Note: When filtering special characters, be careful as it can be bypassed by replacing it with a space.