About SQL Injection
The preliminary defenses:
- Option # 1: Use of Prepared Statements (parameterized queries)
The use of Prepared Statements with variable link (parameterized queries) is how all developers should be taught to write database queries. They are simple to write, and easier to understand than dynamic queries. Parameterized queries force the developer to first define all the SQL code, and then pass each parameter to the query later. This encoding style allows the database to distinguish code and data, regardless of what the user input is provides.
Prepared Statements ensure that an attacker is not able to change the intent of a query, even if the SQL commands are inserted by an attacker. In the example , if an attacker tries to enter the tone userid "or" 1, the parameterized query 1 '=' would not be vulnerable and instead search for a username that literally accompanies all the string 'or' 1 '=' 1.
Specific recommendations for each language:
- Java EE - use Preparedstatement() with bind variables
- .NET - use parameterized queries like Sqlcommand() or Oledbcommand() with bind variables
- PHP - use PDO with strongly typed parameterized queries
(using bindParam())
- Hibernate - use createQuery() with bind variables
(called named Parameters in Hibernate) Sqlite - use sqlite3_prepare()
to create a statement Object
There are other ways/complements to prevent SQL Injection, Prepared Statements is one of the main ones.
I saw that you are interested in knowing about other vulnerabilities, including other variants of SQL attack like blind sql Injection.
I don’t know if you know this, but there is a community organization that has a focus on security, especially the web and they make a top 10 of the main web vulnerabilities, outside that it has several other security related contents, even facing PHP.
Complementing: In addition, validate the inputs and outputs of your application, leaving the use of necessary characters.
OWASP
TOP 10 - 2013
SQL Injection
Reinforcement to you know this site, mainly to learn about the other ways to prevent an SQL attack, content was taken from there.
In the title you mention SQL Injection, but in the end you talk about any type of attack. This code solves SQL Injection, but does not solve, for example, XSS injections. In this case you would need to filter the same values.
– bfavaretto
So @bfavaretto, after you talked about XSS, I researched it, one of the information I had, is that with the TAGS:
strip_tags, addslashes e htmlspecialchars
can solve this problem. Is it fact or not, what is the best way to avoid XSS with php? another question is, which global variables should I use to avoid this: ex: GET, POST, SESSION, COOKIE, SERVER ... because from what I read and from what I know, the user agent ($_SERVER), I can modify this header easily, and generally send it directly to the database... it is possible to modify the global variable of the IP as well?– abcd