Is there some way to inject SQL even if the ' character is deleted?
Yes, there is. An excerpt from Wikipedia
"SELECT * FROM data WHERE id = " + a_variable + ";"
It is clear from this statement that the author intended a_variable to be a number correlating to the "id" field. However, if it is in fact a string then the end user may manipulate the statement as they choose, thereby bypassing the need for escape characters. For example, setting a_variable to
1;DROP TABLE users
will drop (delete) the "users" table from the database, since the SQL would be rendered as follows:
SELECT * FROM DATA WHERE id=1;DROP TABLE users;
SQL injection is not a simple attack to fight. I would do very careful research if I were you.
Classic ASP SQL Injection Protection
Stored Procedures and/or prepared statements:
https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?
Catching SQL Injection and other Malicious Web Requests
With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway.
Here's a link to the technique in Access:
http://www.asp101.com/samples/storedqueries.asp
Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic. Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code. Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place.
In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target:
Conn.Execute("EXEC usp_ImOnlySafeIfYouCallMeRight '" + param1 + "', '" + param2 + "'") ;
Remember that your database needs to defend its own perimeter, and if various logins have rights to INSERT/UPDATE/DELETE
in tables, any code in those applications (or compromised applications) can be a potential problem. If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior. (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.)
How do you prevent SQL injection in LAMP applications?
as @Rob Walker states, parameterized queries are your best bet. If you're using the latest and greatest PHP, I'd highly recommend taking a look at PDO (PHP Data Objects). This is a native database abstraction library that has support for a wide range of databases (including MySQL of course) as well as prepared statements with named parameters.
How can I prevent SQL injection in PHP?
The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
Using PDO (for any supported database driver):
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute([ 'name' => $name ]);
foreach ($stmt as $row) {
// Do something with $row
}Using MySQLi (for MySQL):
Since PHP 8.2+ we can make use of execute_query()
which prepares, binds parameters, and executes SQL statement in one method:
$result = $dbConnection->execute_query('SELECT * FROM employees WHERE name = ?', [$name]);
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
Up to PHP8.1:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare()
and pg_execute()
for PostgreSQL). PDO is the universal option.
Correctly setting up the connection
PDO
Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example, the error mode isn't strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the PDOException
.
What is mandatory, however, is the first setAttribute()
line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset
in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.
Mysqli
For mysqli we have to follow the same routine:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset
Explanation
The SQL statement you pass to prepare
is parsed and compiled by the database server. By specifying parameters (either a ?
or a named parameter like :name
in the example above) you tell the database engine where you want to filter on. Then when you call execute
, the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.
Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name
variable contains 'Sarah'; DELETE FROM employees
the result would simply be a search for the string "'Sarah'; DELETE FROM employees"
, and you will not end up with an empty table.
Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute([ 'column' => $unsafeValue ]);
Can prepared statements be used for dynamic queries?
While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.
// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
$dir = 'ASC';
}
What HTTP code should be sent in response to a suspected malicious request
I would think 403 Forbidden
means that the resource shouldn't be accessed.
I'd thus use 400 Bad Request
instead. After all, the user is allowed to the page so long as they're making a legitimate request.
Is sql injection and cross-site scripting still a thing?
I'll tell a story.
My mother used to volunteer with a group to go to the local college campus to help students register to vote (in the US, people can vote at age 18, but they aren't registered by default, they have to fill out a form). She and her group would set up a table in the quad with a supply of forms and guide the students to fill it out and mail it in.
After years of doing this, one of the other women in the group said, "We've been coming onto campus to help these kids register for TEN YEARS! When are they going to be able to do it on their own?"
My mom and the others looked at her and said slowly, "There is a new set of students turning 18 years old every year."
The same thing is true for defense against SQL injection and Cross-Site Scripting. There are new programmers entering the profession every year.
In fact, studies show that the number of software developers doubles every five years, which means at any given time, 50% of software developers are what I would consider "junior developers" with less than five years of experience. By the time those people have become senior developers, there's again just as many younger developers who have entered the profession after them.
All of them need to be trained to understand SQL injection and Cross-Site Scripting defense before they should be allowed to put their code on a live server.
One at a time.
Every year.
SQL injection and Cross-Site scripting will continue to be a thing as long as there are software developers.
I also can reference the SQLi Hall-of-Shame, a web page that references news stories about data breaches perpetrated by exploiting SQL injection vulnerabilities. The seem to be multiple such stories every month, and these are just the break-ins that made the news. It's undoubtedly the tip of the iceberg.
Related Topics
SQL Statements with Equals VS In
How to Change the Primary Key to Be Non-Clustered
SQL Server: Any Equivalent of Strpos()
Left Inner Join VS. Left Outer Join - Why Does the Outer Take Longer
Insert Record to SQL Table with Identity Column
Make H2 Treat Quoted Name and Unquoted Name as the Same
How to Open Bcp Host Data-File
How to Execute a Stored Procedure Over a Set Without Using a Cursor
Select Records in on Table Based on Conditions from Another Table
Deferrable Check Constraint in Postgresql
How to Expand a "Condensed" Postgresql Row into Separate Columns
How to Match Multiple Column in a Table with SQLite Fts3
SQL Group by Day, Show Orders for Each Day
Getting a Dynamically-Generated Pivot-Table into a Temp Table
How Does Order by Clause Works If Two Values Are Equal
Find Top 10 Latest Record for Each Buyer_Id for Yesterday's Date