SQL Injection that Gets Around mysql_real_escape_string() Function
Last Updated :
08 Apr, 2024
SQL injection is a serious security vulnerability that occurs when an attacker can manipulate SQL queries executed in a database. In an attempt to prevent SQL injection, developers often use functions like mysql_real_escape_string() in PHP to escape special characters.
However, it's crucial to understand that reliance on this function alone may not provide foolproof protection. This guide demonstrates SQL injection scenarios that bypass mysql_real_escape_string() and explores the importance of adopting additional security measures.
What is mysql_real_escape_string() Function
mysql_real_escape_string() is a PHP function designed to escape special characters in a string before inserting them in MySQL queries, ensuring safe MySQL queries are run in the database. However, it may not protect all forms of SQL injection attacks. Attackers can leverage certain techniques to evade the effects of this function and execute malicious SQL statements.
Note: This extension was removed in PHP 7.0.0. Some better alternatives to this functions are: mysqli_real_escape_string() and PDO::quote().
Syntax
// Usage of mysql_real_escape_string()
$escaped_value = mysql_real_escape_string($user_input);
This function escapes special characters, making the input safe for inclusion in SQL queries.
Bypassing mysql_real_escape_string() with SQL Injection Example
Let's look at some examples and understand how SQL injection attacks bypass the mysql_real_escape_string() function.
Classic SQL Injection Example
Consider a login scenario where the application uses mysql_real_escape_string() to sanitize user input. The attacker provides a crafted input to bypass the function.
-- Create users Table
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)
);
-- Insert Sample Data
INSERT INTO users (username, password) VALUES
('john_doe', 'password123'),
('admin', 'adminpassword');
PHP Code Using mysql_real_escape_string()
<?php
// Assume the usage of mysql_real_escape_string()
$_POST['username'] = "admin' OR '1'='1'; -- ";
// Login Query Using mysql_real_escape_string()
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
// Execute the query and process the result
?>
Output:
The provided PHP code uses deprecated mysql_real_escape_string() for input sanitization and attempts to prevent SQL injection. However, it is vulnerable.
Injected SQL Query:
SELECT * FROM users WHERE username='admin' OR '1'='1'; -- ' AND password='';
The malicious input admin' OR '1'='1'; -- can manipulate the SQL query, potentially leading to unauthorized access as it injects a true condition.
The injected query allows unauthorized access by matching any password when the injected condition is true. This query always evaluates to true, allowing unauthorized access.
Using Prepared Statements for Secure Query Execution Example
To address SQL injection vulnerabilities effectively, developers should adopt prepared statements.
This example modifies the login query to use a prepared statement.
-- Create users Table
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)
);
-- Insert Sample Data
INSERT INTO users (username, password) VALUES
('john_doe', 'password123'),
('admin', 'adminpassword');
PHP Code Using Prepared Statements
-- PHP Code Using Prepared Statements
<?php
// Establish MySQL Connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Login Query Using Prepared Statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
// Set Values Safely
$username = $_POST['username'];
$password = $_POST['password'];
// Execute the Query
$stmt->execute();
$result = $stmt->get_result();
// Process the Result
while ($row = $result->fetch_assoc()) {
// Process the result
}
?>
Output:
This PHP code uses a prepared statement to securely retrieve user data from a MySQL database. It establishes a connection, prepares a SELECT query with placeholders, binds user inputs, executes the query, and processes the result. However, the result processing section is incomplete; it should include logic for handling successful or unsuccessful logins.
Conclusion
So, Overall, while mysql_real_escape_string() provides a basic level of protection, it is not foolproof against all SQL injection attacks. Developers must stay vigilant and adopt more robust measures, such as prepared statements, to ensure the security of their applications.
Utilizing the latest security practices and regularly updating code to address emerging threats is essential in the ongoing battle against SQL injection vulnerabilities.
Similar Reads
Functions in MySQL | Numeric, String and Date Time Functions in MySQL
In MySQL, functions play a crucial role in performing various operations on data, such as calculations, string manipulations, and date handling. These built-in functions simplify complex queries and data transformations, making it easier to manage and analyze data within a database. In this article,
4 min read
What are the Risks of using mysql_* Functions in PHP?
MySQL functions in PHP, often referred to as mysql_* functions, have been a popular choice for developers to interact with MySQL databases. Did you say "NOT ANYMORE!"? So now it's essential to weigh the pros and cons of mysql_* functions in PHP to determine whether they are a good or bad choice for
4 min read
Authentication Bypass using SQL Injection on Login Page
SQL injection is a technique used to exploit user data through web page inputs by injecting SQL commands as statements. Basically, these statements can be used to manipulate the applicationâs web server by malicious users. SQL injection is a code injection technique that might destroy your database.
3 min read
How a Connection String Injection Attack is Performed?
This attack can be used to manipulate the web application's access to a database using database connectivity objects. It is also the often overlooked method for attackers to avoid detection and bypass security controls designed for legitimate users. This type of hacking allows an attacker to bypass
6 min read
SUBSTRING_INDEX() function in MySQL
SUBSTRING_INDEX() function in MySQL is used to return a substring from a string before a specified number of occurrences of the delimiter. Syntax : SUBSTRING_INDEX( str, delim, count ) Parameter : This method accepts three-parameter as mentioned above and described below : str : The original string
2 min read
How to Insert Line Break in SQL Server String?
In SQL Server there are various datatypes like int, float, char, nchar, etc but especially while we are dealing with text in VARCHAR and NVARCHAR columns, we might run into situations where we need to make the text look cleaner by adding line breaks. This could be for better organization, and readab
4 min read
SUBSTRING() function in MySQL
SUBSTRING() : function in MySQL is used to derive substring from any given string .It extracts a string with a specified length, starting from a given location in an input string. The purpose of substring is to return a specific portion of the string. Syntax : SUBSTRING(string, start, length) OR SUB
2 min read
What is SQL Injection UNION Attacks?
An SQL injection attack is the execution of a malicious SQL query to alter data stored in a database or to access data without authentication or authorization. Websites or web applications using SQL databases are vulnerable to SQL injection attacks. The most common approach to launching an SQL injec
3 min read
Concatenation of strings in PL/SQL
Prerequisite - PL/SQL Introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given two strings and the task is to concatenate them a
1 min read
How to Insert a Line Break VARCHAR String in MySQL
When dealing with textual data in MySQL databases, maintaining proper formatting is important for readability and clarity. One common formatting requirement is to insert line breaks within VARCHAR and NVARCHAR strings. In this article, we will understand How to insert a line break in a MySQL VARCHAR
3 min read