A Brief Introduction About Sql Injection in PHP and MYSQL
1. SQL Injection:
There are two types of SQL Injections :
1- Plain SQL Injection: The web page accepts data from a client and executes SQL
queries without first validating the client’s input. The attacker is then free to extract,
modify, add, or delete content from the database.
Hackers typically test for SQL injection vulnerabilities by sending the application
input that would cause the server to generate an invalid SQL query. If the server
then returns an error message to the client, the attacker will attempt to revers e-
engineer portions of the original SQL query using information gained from these
error messages. The typical administrative safeguard is simply to prohibit the display
of database server error messages.
2- Blind SQL Injection:
Consider the following SQL query in PHP:
$result=mysql_query('SELECT * FROM users WHERE
username="'.$_GET['username'].'"') ;
But what would happen if $_GET['username'] was the following:
" OR 1=1 OR username=”
The corresponding statement will be like this:
SELECT * FROM users WHERE username = "" OR 1=1 OR username = ""
This selects all rows from the users table.
Solution:
Never trust user provided data, process this data only after validation; as a rule, t his
is done by pattern matching:
if (preg_match("/^w{8,20}$/", $_GET['username'], $matches))
$result = mysql_query("SELECT * FROM users WHERE
username=$matches[0] ");
else
echo "username not accepted";
Every parameter of every script on the server should always be checked.
2. If attacker wants to Login without entering password:
Username: osama’ --
SELECT * FROM members WHERE username = 'osama'--' AND password = 'password'
In this way, attacker may execute any SQL command. If he enter a password as
follow ing:
osama’; DELETE FROM users;
and PHP code was:
$name = $_POST[„password‟];
mysql_query(“SELECT * FROM users WHERE name=‟ {$name}‟”);
then he can delete all users from users table !!!
Fortunately, if you use MySQL, the mysql_que ry() function does not permit query
stacking, or executing multiple queries in a single function call. If you try to stack
queries, the call fails. Unlike SQLite and PostgreSQL.
In PHP, there is many different ways to avoid such injections:
Using magic_quotes_gpc() function which escapes all ' (single-quote), "
(double quote), (backslash) and NULL's with a backslash automatically.
Although it escape undesirable characters, it is not good to rely on this feature:
Warning
This feature has been DEPRECATED as of PHP 5.3.0
and REMOVED as of PHP 6.0.0. Relying on this feature is highly
discouraged.
3. Using customized escape mechanisms: mysql_real_escape _string() Which
escapes special characters in a string for use in a SQL statement.
if (get_magic_quotes_gpc()) {
$name = stripslashes($name);
}
$name = mysql_real_escape_string($name);
mysql_query(“SELECT * FROM users WHERE name=‟ {$name}‟”);
Note: mysql_real_escape_string() does not escape % and _. These are wildcards in
MySQL if combined with LIKE, GRANT, or REVOKE.
Using addslashes() function which quote string with slashes
$str = "Is your name O'reilly?";
// Outputs: Is your name O'reilly?
echo addslashes($str);
Or you can combine addslashes() w ith ma gic_quotes_gpc () :
$sub = addcslashes(mysql_real_escape_string(“%something_”),
“%_”);
// $sub == %something_
mysql_query(“SELECT * FROM messages WHERE subject LIKE
„{$sub}%‟”);
Using urlencode() :This function is convenient when encoding a string to be
used in a query part of a URL, as a convenient way to pass variables to the
next page.
$url = urlencode('?page=10');
// Outputs: %3Fpage%3D10
echo $url;
4. Gene ral advise about Security:
Never connect to the database as a superuser or as the database owner. Use
always customized users w ith very limited privileges
Check if the given input has the expected data type.
If the application waits for numerical input, consider verifying data with
is_nume ric(), or silently change its type using settype(), or use its numeric
representation by sprintf()
Quote each non numeric user supplied value that is passed to the database
with the database-specific string escape function (e.g.
mysql_real_escape_string(), sqlite _escape_string(), etc.). If a
database-specific string escape mechanism is not available, the
addslashes() and str_replace() functions may be useful (depending on
database type).
Additionally, attacker may not reply on SQL Injection only, he may ask a millions of
request to the server, which cause down to the server or stop responding.
Extra danger will exists if site allow visitors to upload files, then user can upload a
script that execute some commands, and request this command from browser.
Admin should set folder permissions in safe way to prevent some one from Directory
Traversal.