0% found this document useful (0 votes)
2 views

W11-Attacking Data Stores

The document discusses SQL injection attacks, including how they exploit vulnerabilities in web applications that use relational databases. It explains the differences between compiled and interpreted languages, the mechanics of SQL queries, and various methods for injecting malicious SQL code to bypass authentication or manipulate data. Additionally, it provides examples and steps for identifying and exploiting SQL injection vulnerabilities in applications.

Uploaded by

phantomsixth6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

W11-Attacking Data Stores

The document discusses SQL injection attacks, including how they exploit vulnerabilities in web applications that use relational databases. It explains the differences between compiled and interpreted languages, the mechanics of SQL queries, and various methods for injecting malicious SQL code to bypass authentication or manipulate data. Additionally, it provides examples and steps for identifying and exploiting SQL injection vulnerabilities in applications.

Uploaded by

phantomsixth6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Attacking Data Stores

ICT2214—Web Security
Compiled vs interpreted languages

Compiled languages:
Interpreted languages:
• Code is converted into machine instructions
• Their execution involves a runtime
before runtime
component that interprets the language’s
• At runtime, these instructions are executed
code and carries out the instructions
directly by the processor
• Vulnerable to code injection attacks
• Not vulnerable to code injection attacks that
• An attacker can supply a crafted input that
leverage the language’s grammar
produces a valid instruction within the
• However, they are vulnerable to injection of
language’s grammar
machine instructions
• Examples: PHP, SQL, Perl, etc.
• Examples: C/C++, Java, etc.

2
SQL injection attacks

Here, we will focus primarily on SQL injection attacks

• Most web applications leverage external relational database


systems (RDBMS) that store a multitude of data
• For example, user accounts, transactions, products, etc.
• Relational databases are queried via the Structured Query
Language (SQL)
• SQL injection attacks are still common among web applications
• If you are not familiar with SQL statements, you may find a nice
tutorial here: https://sqlzoo.net/

3
A simple example: bypassing a login

Many applications that implement a forms-based login function use a database to


store user credentials

For example, assume the credentials are stored in a table called users, with two
attributes (columns), namely username and password

A simple SQL query can then be used to validate each login attempt:

SELECT * FROM users WHERE username='peter' AND


password='michelle'

This query causes the database to check every row within the users table and
extract the record that matches the given credentials (if any)

4
A simple example: bypassing a login

If an attacker knows that the username of the administrator is admin, he can log in
as that user by supplying any password with the following username: admin' --

This causes the application to perform the following query:

SELECT * FROM users WHERE username='admin' --' AND


password='foo'

The –– indicates a comment sequence, which means that everything else in


the query after the -- will be ignored. So, the query below will be one that will
be executed. As can be seen, the password check will be missed:

SELECT * FROM users WHERE username='admin'


5
Steps for exploiting code injection vulnerabilities

1. Provide unexpected syntax that may cause problems within the context of the
particular interpreted language
2. Identify any anomalies in the application’s response that may indicate the presence of
a code injection vulnerability
3. If any error messages are received, examine these to obtain evidence about the
problem that occurred on the server
4. If necessary, systematically modify your initial input in relevant ways in an attempt
to confirm or disprove your tentative diagnosis of a vulnerability
5. Construct a proof-of-concept test that causes a safe command to be executed in
a verifiable way, to conclusively prove that an exploitable code injection flaw
exists
6. Exploit the vulnerability by leveraging the functionality of the target language
and component to achieve your objectives

6
Exploiting a basic vulnerability

Consider a web application for an HR department that stores information about


employees

The following query retrieves information about employees, based on their last
name and ID:

SELECT id, fname, lname, salary FROM employees WHERE


lname='King' AND id=100

This query was constructed by the programmer when the application was
created

The expressions King and 100 are supplied by the user via the web application

7
Exploiting a basic vulnerability

String data in SQL queries must be encapsulated within single quotation marks to
separate them from the rest of the query

Assume a user enters the following last name to query the database: O'Reilly

SELECT id, fname, lname, salary FROM employees WHERE


lname='O'Reilly' AND id=230

The database system determines that the last name is 'O' and then sees the
expression Reilly' which is not valid SQL syntax

The interpreter will output an error which is an indication that the application is
vulnerable to SQL injection

8
Exploiting a basic vulnerability

We can take advantage of this vulnerability to print the salaries of ALL employees
without knowing their names or IDs

Issue the following query for arbitrary ID and a name with the following format:
John' OR 1=1 --

SELECT id, fname, lname, salary FROM employees WHERE


lname='John' OR 1=1 --' AND id=100

Because of the OR operator, the WHERE clause matches every database record

Note that, instead of the double dash, you may use a hashtag (#) to mark the
beginning of a SQL comment: John' OR 1=1 #

9
Balancing the quotes

In the previous example, one purpose of the SQL comment (--) is to remove the
trailing quotation mark that would cause a syntax error

Of course, in our example, we also need the comment to remove the AND
operator

In some situations, an alternative way to handle the trailing quotation mark,


without using the comment symbol, is to “balance the quotes” as follows:

John' OR 'a'='a

SELECT id, fname, lname, salary FROM employees WHERE


lname='John' OR 'a'='a' AND id=100

10
INSERT statements

INSERT statements are used to create a new row of data within a table

Consider an application that allows users to self-register, specifying their own


username and password

The application then inserts the details into the users table as follows:

INSERT INTO users (username, password, id, privs) VALUES


('jdoe', 'secret', 2248, 1)

If the username or password field is vulnerable to SQL injection, an attacker can


insert arbitrary data into the table, including his own values for id and privs

11
INSERT statements

For the injection to be successful, the supplied data must contain the correct
number of data items of the correct types

For example, injecting into the username field, the attacker can supply the
following:

foo', 'bar', 9999, 0) --

This creates an account with an ID of 9999 and privs of 0

Assuming that the privs field is used to determine account privileges, this may
enable the attacker to create an administrative user

12
INSERT statements

If you do not know the number and/or type of attributes (columns), you may try
different queries until the operation is successful

foo') --
foo', 1) --
foo', 1, 1) --
foo', 1, 1, 1) --

Because most databases implicitly cast an integer to a string, an integer value


can be used at each position

If the value 1 is rejected, you can try the value 2000, which many databases also
implicitly cast to date-based data types

13
UPDATE statements

UPDATE statements are used to modify one or more existing rows of data within a
database table

It works much like an INSERT statement, except that it usually contains a WHERE
clause to tell the database which rows of the table to update

UPDATE users SET password='newsecret' WHERE user='marcus' AND


password='secret'

This query verifies whether the user’s existing password is correct and, if so,
updates it with the new value

You can update the password of the admin user by entering the following
username: admin' --
14
Finding SQL injection bugs

• When probing for SQL injection


• During application mapping, you should vulnerabilities, be sure to walk through to
identify instances where the application completion any multistage processes in
appears to access a back-end database which you submit crafted input
• In fact, any data item submitted to the server • Applications often gather a collection of data
may be passed to database functions across several requests, and they persist this
• This includes all URL parameters, cookies, to the database only after the complete set
items of POST data, and HTTP headers has been gathered
• All of the above need to be probed for SQL • You will miss many SQL injection
injection flaws vulnerabilities if you only submit crafted data
within each individual request

15
Injecting into string data

• If an error or other anomalous behavior was


• Submit a single quotation mark as the item of
observed, submit two single quotation marks
data you are targeting
together
• Observe whether an error occurs, or whether
• Databases use two single quotation marks
the result differs from the original in any
as an escape sequence to represent a literal
other way
single quote
• If a detailed database error message is
• If this input causes the error or anomalous
received, consult a SQL reference to
behavior to disappear, the application is
understand its meaning
probably vulnerable to SQL injection

16
Injecting into string data

• As a further verification that a bug is present,


you can use SQL concatenator characters to The following examples can be injected to
construct a string that is equivalent to some construct input that is equivalent to FOO in a
benign input vulnerable application:
• If the application handles your crafted input
in the same way as it does the • Oracle: '||'FOO
corresponding benign input, it is likely to be • MS-SQL: '+'FOO
vulnerable • MySQL: ' 'FOO (note the space between
• Each type of database uses different the two quotes)
methods for string concatenation

17
Injecting into string data

• One way of confirming that the application is


interacting with a back-end database is to • While looking for SQL injection using a single
submit the SQL wildcard character % in a quote, keep an eye out for any JavaScript
given parameter errors occurring when your browser
• For example, submitting this in a search field processes the returned page
often returns a large number of results, • It is fairly common for user-supplied input to
indicating that the input is being passed into be returned within JavaScript, and an
a SQL query unsanitized single quote will cause an error
• Of course, this does not necessarily indicate in the JavaScript interpreter
that the application is vulnerable — only that • The ability to inject arbitrary JavaScript into
you should probe further to identify any responses allows cross-site scripting attacks
actual flaws

18
Injecting into numeric data

• When user-supplied numeric data is incorporated into a SQL query,


the application may still handle this as string data by encapsulating
it within single quotation marks
• Therefore, you should always follow the steps described previously
for string data
• However, in most cases, numeric data is passed directly to the
database in numeric form and is not placed within single quotation
marks
• If none of the previous tests points toward the presence of a
vulnerability, you can take some other specific steps in relation to
numeric data (discussed next)

19
Injecting into numeric data

• This test is most reliable in cases where you


• Try supplying a simple mathematical have confirmed that the item being modified
expression that is equivalent to the original has a noticeable effect on the application’s
numeric value behavior
• For example, if the original value is 2, try • For example, if the application uses a
submitting 1+1 or 3-1 numeric PageID parameter to specify which
• If the application responds in the same way, content should be returned, substituting 1+1
it may be vulnerable for 2 with equivalent results is a good sign
that SQL injection is present

20
Injecting into numeric data

• If the first test is successful, you can obtain


further evidence of the vulnerability by using • The preceding test will not work if single
more complicated expressions that use SQL- quotes are being filtered
specific keywords and syntax • However, in this situation you can exploit the
• A good example of this is the ASCII fact that databases implicitly convert numeric
command, which returns the numeric ASCII data to string data where required
code of the supplied character • Therefore, because the ASCII value of the
• For example, because the ASCII value of Ais character 1 is 49, the following expression in
65, the following expression in SQL is SQL is also equivalent to 2: 51-ASCII(1)
equivalent to 2: 67-ASCII('A')

21
Common mistake

Certain characters have special meaning within HTTP requests and, if you want to
include them within your attack payloads, you must URL-encode them

& and = are used to join name/value pairs to create the query string and the block of
POST data. You should encode them using %26 and %3d, respectively

Literal spaces are not allowed in the query string. You should encode them using + or
%20

Because + is used to encode spaces, if you want to include an actual + in your string,
you must encode it using %2b. For example, 1+1 should be submitted as 1%2b1

The semicolon is used to separate cookie fields and should be encoded as %3b

22
Injecting into the query structure

• If user-supplied data is being inserted into the structure of the SQL


query itself, exploiting SQL injection simply involves directly
supplying valid SQL syntax
• No “escaping” is required to break out of any data context
• The most common injection point within the SQL query structure is
within an ORDER BY clause
• The ORDER BY keyword takes a column name or column number
and orders the result set according to the values in that column
• This functionality is frequently exposed to the user to allow sorting
of a table within the browser

23
Injecting into the query structure

SELECT author, title, year FROM books WHERE publisher = 'Wiley'


ORDER BY title ASC

If the column name title in the ORDER BY is specified by the user, it is not
necessary to use a single quote

Finding SQL injection in a column name can be difficult. If a value is supplied


that is not a valid column name, the query results in an error

This means that the response will be the same regardless of what the attacker
submits

However, this type of SQL injection is more difficult to defend against

24
Injecting into the query structure

• Make a note of any parameters that appear • If the number supplied is greater than the
to control the order or field types within the number of columns in the result set, the
results that the application returns query should fail
• Make a series of requests supplying a • In this situation, you can confirm that further
numeric value in the parameter value, SQL can be injected by checking whether the
starting with the number 1 and incrementing results order can be reversed, using the
it with each subsequent request following: 1 ASC -- or 1 DESC --
• If changing the number in the input affects • If supplying the number 1 causes a set of
the ordering of the results, the input is results with a column containing a 1 in every
probably being inserted into an ORDER BY row, the input is probably being inserted into
clause the name of a column in a SELECT clause

25
The UNION operator

• The UNION operator is used in SQL to combine the results of two or


more SELECT statements into a single result set
• In a SQL injection vulnerability, the UNION operator can be used to
perform a second, entirely separate query, and combine its results
with those of the first
• If the results of the query are returned to your browser, this
technique can be used to extract arbitrary data from the database
• UNION is supported by all major DBMS products
• It is the quickest way to retrieve arbitrary information from the
database in situations where query results are returned directly

26
The UNION operator

Let's consider the HR application again and how we can leverage the powerful
UNION operator to dump the password table

Consider the following query that is vulnerable to SQL injection:

SELECT fname, lname, salary FROM employees WHERE lname='King'

The UNION operator can be used to inject a second SELECT query and append its
results to those of the first. Just use the following search term for the last name:

King' UNION SELECT username,password,id FROM users --

27
Conditions for the UNION operator to succeed

• When the results of two queries are


combined using the UNION operator, the two
• To inject a second query that will return
result sets must have the same structure
interesting results, the attacker needs to
• They must contain the same number of
know the name of the database table that he
columns, which have the same or compatible
wants to target, and the names of its relevant
data types, appearing in the same order
columns
• Notice that the application may not display all
the columns returned by the database query

28
Identifying the number of columns

• You can exploit the fact that NULL can be • Your next task is to discover a column that
converted to any data type to systematically has a string data type so that you can use
inject queries with different numbers of this to extract arbitrary data
columns until your injected query is • You can do this by injecting a query
executed: containing NULLs, as you did previously, and
systematically replacing each NULL with 'a'
' UNION SELECT NULL --
' UNION SELECT NULL,NULL -- ' UNION SELECT 'a', NULL, NULL --
' UNION SELECT NULL,NULL,NULL -- ' UNION SELECT NULL, 'a', NULL --
... ' UNION SELECT NULL, NULL, 'a' --

Extract database version: ' UNION SELECT @@version, NULL, NULL --


29
Identifying the table and column names

We can do this by querying the metadata table information_schema.columns,


which contains details of all tables and column names within the database

Suppose that we have already performed the initial tests, and determined that
the query returns 3 columns and the first 2 contain string data

We can retrieve all the table/column names in the database with the following
search term:

John' UNION SELECT table_name, column_name, NULL FROM


information_schema.columns --

30
Extracting more information

Once we have the names of all tables and columns, we can focus on extracting
sensitive information by examining the listed names

For example, let's look at the dependents table and try to extract the dependent
names and the IDs of the corresponding employees:

John' UNION SELECT first_name, last_name, employee_id FROM


dependents --

Then, we can issue a query to get the names and IDs of all employees, and
combine the results to match employees/dependents

31
Column concatenation

When multiple columns are returned from a target table, these can be
concatenated into a single column

This makes retrieval more straightforward, because it requires identification of


only a single varchar (string) field in the original query

Concatenation is done as follows in different DBMSs:

Oracle: SELECT username||':'||password, NULL, NULL FROM users


MS-SQL: SELECT username+':'+password, NULL, NULL from users
MySQL: SELECT CONCAT(username,':',password), NULL, NULL from
users

32
Acknowledgements
This set of slides for AY24/25 Tri 2 was prepared/adapted from the hard work of previous
professors who taught this module, namely:
• Prof. Weihan
• Prof. Linda
• Prof. Liming
• Prof. Spiros

33
Web Applications |2024
Goh Weihan | January

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy