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

Chapter-3 Web Security

The document discusses web security, focusing on the OWASP Top 10 web security flaws, particularly SQL Injection attacks. It provides tutorials on SQL commands, how web applications interact with databases, and various SQL injection techniques, including blind SQL injection. Additionally, it outlines countermeasures such as filtering, encoding data, and using prepared statements to mitigate SQL injection vulnerabilities.

Uploaded by

magarsaaaddaamuu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Chapter-3 Web Security

The document discusses web security, focusing on the OWASP Top 10 web security flaws, particularly SQL Injection attacks. It provides tutorials on SQL commands, how web applications interact with databases, and various SQL injection techniques, including blind SQL injection. Additionally, it outlines countermeasures such as filtering, encoding data, and using prepared statements to mitigate SQL injection vulnerabilities.

Uploaded by

magarsaaaddaamuu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

12/22/2023

Chapter-3

Web Security

OWASP TOP 10 Web security flaws

1
12/22/2023

OWASP TOP 10 Web security flaws

SQL Injection Attack

2
12/22/2023

Brief Tutorial of SQL


• Log in to MySQL:

• Create a Database: Inside MySQL, we can create multiple databases.


• “SHOW DATABSES” command can be used to list existing databases.
• We will create a new database called dbtest:

SQL Tutorial: Create a Table


• A relational database organizes its data using tables
• Let us create a table called employee with seven attributes (i.e. columns) for the
database “dbtest”

• We need to let the system know


which database to use as there
may be multiple databases

• After a table is created, we can use


describe to display the structure
of the table

3
12/22/2023

SQL Tutorial: Insert a Row


• We can use the INSERT INTO statement to insert a new record into a
table :

• Here, we insert a record into the “employee” table

SQL Tutorial: SELECT Statement


• The SELECT statement is the most common operation on databases
• It retrieves information from a database
Asks the database
for all its records,
including all the
columns

Asks the database


only for Name, EID
and Salary columns

4
12/22/2023

SQL Tutorial: WHERE Clause


• It is uncommon for a SQL query to retrieve all records in a database.
• WHERE clause is used to set conditions for several types of SQL statements
including SELECT, UPDATE, DELETE etc.

• The above SQL statement only reflects the rows for which the predicate in the
WHERE clause is TRUE.
• The predicate is a logical expression; multiple predicates can be combined using
keywords AND and OR.

SQL Tutorial: WHERE Clause


• The first query returns a record that has EID5001 in EID field
• The second query returns the records that satisfy either EID=‘EID5001’ or
Name=‘David’

5
12/22/2023

SQL Tutorial: WHERE Clause


• If the condition is always True, then all the rows are affected by the SQL
statement

• This 1=1 predicate looks quite useless in real queries, but it will become
useful in SQL Injection attacks

SQL Tutorial: UPDATE Statement

• We can use the UPDATE Statement to modify an existing record

6
12/22/2023

SQL Tutorial: Comments


MySQL supports three comment styles
• Text from the # character to the end of line is treated as a comment
• Text from the “--” to the end of line is treated as a comment.
• Similar to C language, text between /* and */ is treated as a comment

Interacting with Database in Web Application


• A typical web application consists of three major components:

• If this channel is not implemented properly, malicious users can attack the
database
• SQL Injection attacks

7
12/22/2023

Getting Data from User


• Once the submit button is clicked, an HTTP request will be sent out with the
data attached

• The HTML source of the above form is given below:

• HTTP GET Request generated is:

Getting Data from User


HTTP GET requests: data (foo and bar) are attached in the URL

HTTP POST requests: data (foo and bar) are placed inside the data field of
the HTTP request

8
12/22/2023

Getting Data from User


• Once this request reached the target PHP script the parameters inside the
HTTP request will be saved to an array $_GET or $_POST

 The following example shows a PHP script getting data from a GET request

How Web Applications Interact with Database


Step1 - Connecting to MySQL Database
• PHP program connects to the database server before conducting query on database

9
12/22/2023

How Web Applications Interact with Database


Step 2 - Construct the query string and sending it to the database for execution

The channel between


user and database
creates a new attack
surface for the database

Launching SQL Injection Attacks


• Everything provided by user will become part of the SQL statement
• Is it possible for a user to change the meaning of the SQL statement?

• Assume that a user inputs a random string in the password entry and types
‘EID5002’ #’ in the eid entry. The SQL statement will become the following

10
12/22/2023

Launching SQL Injection Attacks


• Everything from the # sign to the end of line is considered as comment
• The SQL statement will be equivalent to the following:

• This is security breach


• Getting all the records from the database without knowing all the EID’s
• Need to create a predicate for WHERE clause so that it is true for all records

Modify Database
• Consider the form created for changing passwords

• An HTTP POST request will be sent to the server-side script which uses an
UPDATE statement

11
12/22/2023

Modify Database - Example


• Let us assume that Alice (EID5000) is not satisfied with the salary she gets. She
would like to increase her own salary using the SQL injection vulnerability.
• She would type her own EID and old password. The following will be typed into the
“New Password” box :

• The SQL statement will now look as follows

Modify Database - Example


• What if Alice doesn’t like Bob and would like to reduce Bob’s salary to 0, but
she only knows Bob’s EID (eid5001), not his password. How can she execute
the attack?

12
12/22/2023

Multiple SQL Statements


• To append a new SQL statement “DROP DATABASE dbtest” to the existing
SQL statement to delete the entire dbtest database

• The resulting SQL statement is equivalent to the following

• The above attack doesn’t work against MySQL, because in PHP’s mysqli
extension, the mysqli::query() API doesn’t allow multiple queries to run in
the database server

Blind SQL Injection Attack


• Common way to check for a SQL Injection vulnerability
• Adding a single quote (') in a field

• If you use a single quote in a field that is passed directly to an SQL


statement, the database server will report an error
• An attacker is certain that the field is vulnerable to SQL Injection attacks

• The error could look similar to the following (from Microsoft SQL Server):
Microsoft SQL Native Client error '80040e14'

Unclosed quotation mark after the character string ''.

/target.asp, line 9

13
12/22/2023

Blind SQL Injection Attack


• Web server administrators can suppress detailed error messages.
• This is a flawed solution because it does not address the underlying problem

• The SQL interpreter can still parse user input as part of an SQL query

• Attackers still know if the input is being interpreted as an SQL statement.


• Without the error message

• This is how the Blind SQL Injection technique come into play (sometimes
called Inferential SQL Injection). There are two variants
• Content-based Blind SQL Injection

• Time-based Blind SQL Injection

Blind SQL Injection Attack


Content-based Blind SQL Injection
• The attacker makes different SQL queries that ask the database TRUE
or FALSE questions
• Analyze differences in responses between TRUE and FALSE statements

• Information is inferred by asking true/false questions


– if answer is true the site typically continues normally
– if false the reply is different (although not descriptive)

14
12/22/2023

Blind SQL Injection Attack


Content-based Blind SQL Injection
Example
• This is an example of a web page of an online shop, which displays
items that are for sale
• The following link will display details about item 34, which are retrieved from
a database
http://www.shop.com/item.php?id=34
• The SQL statement used for this request is:
SELECT column_1, column_2 FROM table_name WHERE id = 34

Blind SQL Injection Attack

Content-based Blind SQL Injection


• The attacker may manipulate the request to:
http://www.shop.local/item.php?id=34 and1=2

• The SQL statement changes to:


SELECT column_1, column_2 FROM table_name WHERE ID = 34 and 1=2
SELECT name, description, price FROM Store_table WHERE ID = 34 and 1=2

• This will cause the query to return FALSE and no items are displayed in
the list.

15
12/22/2023

Blind SQL Injection Attack


Content-based Blind SQL Injection
• The attacker then proceeds to change the request to:

http://www.shop.com/item.php?id=34 and 1=1

• And the SQL statement changes to:


SELECT column_1, column_2 FROM table_name WHERE ID = 34 and 1=1
SELECT name, description, price FROM Store_table WHERE ID = 34 and 1=1

• This returns TRUE, and the details of item with ID 34 are shown.
This is a clear indication that the page is vulnerable

Blind SQL Injection Attack


Time-based Blind SQL Injection
• The attacker makes the database perform a time-intensive operation
oIf the web site does not return a response immediately, the web application is
vulnerable to Blind SQL Injection
oTime – taking operation such as BENCHMARK()
o select IF(expression, true, false)
o

• Attacker would issue the following request:


http://www.shop.com/item.php?id=34 and if(1=1, sleep(10), false)

16
12/22/2023

Multiple SQL Statements


• The code below tries to execute two SQL statements using the $mysqli->query()
API

• When we run the code, we get the following error message:

• If we do want to run multiple SQL statements, we can use $mysqli -> multi_query()
[not recommended]

SQL Injection
Countermeasures

17
12/22/2023

The Underlying Issue

This one string combines the code and the data

When the boundary between code and data blurs,


we open ourselves up to vulnerabilities

Countermeasures: Filtering and Encoding Data


• Before mixing user-provided data with code, inspect the data
• Filter out any character that may be interpreted as code

• Special characters are commonly used in SQL Injection attacks


• Encoding a special character
• Tells parser to treat the encoded character as data, not as code

18
12/22/2023

Countermeasures: Filtering and Encoding Data


• PHP’s mysqli extension has a built-in method called mysqli::real_escape_string()
• Used to encode the characters that have special meanings in SQL

c
c

Prepared Statement
• Fundament cause of SQL injection: mixing data and code
• Fundament solution: separate data and code - Decouple the code and the data
• Main Idea: Sending code and data in separate channels to the database server
o This way the database server knows not to retrieve any code from the data channel
• Prepared Statement
o Using prepared statements, we send an SQL statement template to the database, with
certain values called parameters left unspecified
o The database parses, compiles and performs query optimization on the SQL statement
template and stores the result without executing it
o We later bind data to the prepared statement

19
12/22/2023

Prepared Statement
The vulnerable version: code
and data are mixed together

• Lines 1 and 2 : Preparing SQL


statement
Using prepared statements • Line 3 : Binding Data
• Line 4, 5 and 6 : Execution and
Retrieving results

Send code

Send data

Start execution

Why Are Prepared Statements Secure?


• Trusted code is sent via a code channel
• Untrusted user-provided data is sent via data channel
• Database clearly knows the boundary between code and data
• Attacker can hide code in data, but the data will never be treated as code, so
it will never be attacked

20
12/22/2023

Mitigation
Limit privileges; reduces power of exploitation
• Can limit commands and/or tables a user can access
• Allow SELECT queries on Orders_Table but not on Creditcards_Table

Encrypt sensitive data stored in the database


• May not need to encrypt Orders_Table
• But certainly encrypt Creditcards_Table

Group Lab Assignment – SQL Injection

• Test all SQL injection attacks we have seen in the lecture

21
12/22/2023

CSRF and XSS

Web basics: HTTP cookies

22
12/22/2023

How is state managed in HTTP sessions

Separate page

How is state managed in HTTP sessions

HTTP is stateless
• The server does not hold any information on previous requests
• The problem: a client has to access various pages before completing a
specific task and the client state should be kept along all those pages

How does the server know if two requests come from the same browser?

Example: the server doesn’t require a user to log at each HTTP request

23
12/22/2023

How is state managed in HTTP sessions


Solution
• Insert some token into the page when it is requested and get that
token passed back with the next request
oThe server sends the state to the client
oClient returns the state in subsequent responses
Two main approaches
• hidden fields
• cookies

Hidden Fields
Example
• The web server can send a hidden HTML form field along with a unique session
ID as follows:
<input type="hidden“ name="sessionid" value="12345">

• When the form is submitted, the specified name and value are automatically
included in the GET or POST data

24
12/22/2023

Hidden Fields

Hidden Fields

25
12/22/2023

Hidden Fields
• Disadvantage of this approach
o It requires careful and tedious programming effort, as all the pages
have to be dynamically generated to include this hidden field
o Session ends as soon as the browser is closed

• Advantage of this approach


o All browser supports HTML forms

Statefulness with Cookies


• A cookie is a small piece of information that a server sends to a browser
and stored inside the browser

• Server maintains trusted state


o Server indexes/denotes state with a cookie
o Sends cookie to the client, which stores it
o Client returns it with subsequent queries to that same server

26
12/22/2023

Cookies
• A cookie has a name and a value

Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>


Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly

Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict


Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax

• Multiple attributes are also possible, for example:

Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure;


HttpOnly

Statefulness with Cookies

27
12/22/2023

Cookies
• A cookie has a name and a value, and other attribute such as domain and
path, expiration date, version number, and comments

Statefulness with Cookies


Set-Cookie: <cookie-name>=<cookie-value>
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number>
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly

Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict


Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax

// Multiple attributes are also possible, for example:


Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure;
HttpOnly

28
12/22/2023

Cookies
• A cookie has a name and a value, and other attribute such as domain and
path, expiration date, version number, and comments

Cookies
• Request with cookies

29
12/22/2023

Why use cookies?


• Session identifier
• After a user has authenticated, subsequent actions provide a cookie

• So the user does not have to authenticate each time

Tracking users
• Advertisers want to know your behavior
• Ideally build a profile across different websites
• Visit the Apple Store, then see iPad ads on Amazon?

How can site B know what you did on site A?

Why use cookies?


Tracking users
• Option 1: B maintains a DB, indexed by your IP address

• Problem: IP address change

• Option 2: B maintains a DB indexed by a cookie

• “Third-party cookie” Commonly used by large ad networks

30
12/22/2023

Cross Site Request Forgery


(CSRF)

Cross-Site Requests
● When a page from a website sends an HTTP
request back to the website, it is called same-
site request

● If a request is sent to a different website, it is


called cross-site request because where the
page comes from and where the request
goes are different

● Example: A webpage (not Facebook) can


include a Facebook link, so when users click
on the link, HTTP request is sent to Facebook.

31
12/22/2023

Cross-Site Requests
● When a request is sent to example.com from a page coming from
example.com, the browser attaches all the cookies belonging to example.com
● Now, when a request is sent to example.com from another site (different from
example.com), the browser will attach the cookies too
● Because of above behaviour of the browsers, the server cannot distinguish between
the same-site and cross-site requests
o It is possible for third-party websites to forge requests that are exactly the same as
the same-site requests
o This is called Cross-Site Request Forgery (CSRF)

CSRF Attack - Example


● Consider an online banking web application www.bank.com which allows
users to transfer money from their accounts to other people’s accounts
● A user is logged in into the web application and has a session cookie which
uniquely identifies the authenticated user
● HTTP request to transfer $500 from his/her account to account 3220:
http://www.bank.com/transfer.php?to=3220&amount=500
● In order to perform the attack, the attacker needs to send out the forged
request from the victim’s machine so that the browsers will attach the
victim’s session cookies with the requests

32
12/22/2023

CSRF Attacks - Example


● Alice wishes to transfer $100 to Bob using the bank.com web application
This money transfer operation reduces to a request like:
GET http://bank.com/transfer.do?acct=BOB&amount=100
HTTP/1.1
● The bank.com server is vulnerable to CSRF: the attacker can generate a valid
malicious request for Alice to execute!!
● The attack comprises the following steps:
1. Eve crafts the following URL
http://bank.com/transfer.do?acct=Eve&amount=100000
2. When Alice visits Eve’s website she tricks Alice’s browser into accessing
this URL

CSRF Attack on GET Requests - Basic Idea

33
12/22/2023

CSRF Attack on GET Requests - Basic Idea


● The attacker can place the piece of code (to trigger GET request) in the
form of HTML tags like img and iframe to the URL specified in src attribute
○ The img tag will trigger an HTTP GET request. When browsers render a web page
and sees an img tag, it sends an HTTP GET request to the URL specified in the src
attribute

Cross-Site Requests Forgery (CSRF)

Main steps of attack:


● The attacker crafts a webpage that can forge a cross-site request to be sent to
the targeted website
● The attacker needs to attract the victim user to visit the malicious website
● The victim is logged into the targeted website

34
12/22/2023

CSRF Attacks on HTTP POST Services


Constructing a POST Request Using JavaScript

● POST requests can be generated using HTML forms. The above form
has two text fields and a Submit button.
● When the user clicks on the Submit button, POST request will be sent
out to the URL specified in the action field with to and amount fields
included in the body.
● Attacker’s job is to click on the button without the help from the user

CSRF Attacks on HTTP POST Services


Line ①: Creates a form
dynamically; request type is
set to “POST”
Line ②: The fields in the
form are “hidden”. Hence,
after the form is constructed,
it is added to the current
web page.
Line ③: Submits the form
Line ④: The JavaScript function “forge_post()” will automatically.
be invoked automatically once the page is loaded.

35
12/22/2023

Countermeasures: CSRF

Fundamental Causes of CSRF


● The server cannot distinguish whether a request is cross-site or same-site
○ Same-site request: coming from the server’s own page. Trusted
○ Cross-site request: coming from other site’s pages. Not Trusted
○ We cannot treat these two types of requests the same
● Does the browser know the difference?
○ The browser knows from which page a request is generated
● How to help server?
○ Referer header (browser’s help)
○ Same-site cookie (browser’s help)
○ Secret token (the server helps itself to defend against CSRF)

36
12/22/2023

Countermeasures: Referer Header


● HTTP header field identifying the address of the web page from
where the request is generated - Referer
o A server can check whether the request is originated from its own pages
or not
o The browser will set the REFERER field to the page that hosted a
clicked link

Countermeasures: Referer Header

37
12/22/2023

Countermeasures: Same-Site Cookies


● A special type of cookie in browsers like Chrome and Opera, which
provide a special attribute to cookies called SameSite.
● This attribute is set by the servers and it tells the browsers whether a
cookie should be attached to a cross-site request or not.
● Cookies with this attribute are always sent along with same-site
requests, but whether they are sent along with cross-site depends on
the value of this attribute
● Values
● Strict (Not sent along with cross-site requests)
● Lax (Sent with cross-site requests)

Countermeasures: Secret Token


● The server embeds a random secret value inside each web page
o Can use a hidden form field, custom HTTP header, or encode it directly in
the URL
● The server checks this value to see whether a request is cross-site or not
● Pages from a different origin will not be able to access the secret value
○ This is guaranteed by browsers (the same origin policy)
● The secret is randomly generated and is different for different users. So,
there is no way for attackers to guess or find out this secret
● Can be same as session id sent in cookie

38
12/22/2023

CSRF Attacks - Summary


● Target: User who has an account on a vulnerable server
● Attack goal: make requests to the server via the user’s browser that
look to the server like the user intended to make them
● Attacker tools: ability to get the user to “click a link” crafted by the
attacker that goes to the vulnerable site
● Key tricks:
○ Requests to the web server have predictable structure
○ Use of something like <img src=…> to force the victim to send it

Cross-Site Scripting Attack


(XSS)

39
12/22/2023

The Cross-Site Scripting Attack


● In XSS, an attacker injects his/her
malicious code to the victim’s
browser via the target website
● When code comes from a website,
it is considered as trusted with
respect to the website, So it can
o Access and change the content on
the pages
o Read cookies belonging to the
website
● Code can do whatever the user can do
inside the session o Sending out requests on behalf of
the user

The Cross-Site Scripting Attack

The goal of an attacker is to slip code into the browser under the guise of
conforming to the same-origin policy: - Subverting the SOP
● Site evil.com provides a malicious script
● Attacker tricks the vulnerable server (bank.com) to send attacker’s script to the
user’s browser!
● Victim’s browser believes that the script’s origin is bank.com... because it does!
● Malicious script runs with bank.com’s access privileges
o Code can do whatever the user can do inside the session

40
12/22/2023

Types of XSS Attacks


● XSS attacks can generally be categorized into two categories:
stored and reflected
o Persistent (Stored) XSS Attack

○ Non-persistent (Reflected) XSS Attack

Persistent (Stored) XSS Attack


● Attackers directly send their data to
a target website/server which
stores the data in a persistent
storage
● If the input is not sanitized properly
by the website, it is sent to other
users’ browsers and gets executed
by the browsers
o Browsers consider it like any other
code coming from the website

41
12/22/2023

Persistent (Stored) XSS Attack


● The injected script is permanently stored on the target servers in a
database in form of a message forum, visitor log, comment field, etc.
○ The victim then retrieves the malicious script from the server when it requests
the stored information

Persistent (Stored) XSS Attack

42
12/22/2023

Persistent (Stored) XSS Attack


The MySpace Worm or Samy worm
● Samy embedded Javascript program in his MySpace page (via stored XSS)
○ MySpace servers attempted to filter it, but failed
● Users who visited his page ran the program, which
○ made them friends with Samy;
○ displayed “but most of all, Samy is my hero” on their profile;
○ installed the program in their profile, so a new user who viewed profile got
infected
● From 73 friends to 1,000,000 friends in 20 hours
○ Took down MySpace for a weekend

Persistent (Stored) XSS - Summary


● Target: user with Javascript-enabled browser who visits user-
influenced content page on a vulnerable web service
● Attack goal: run script in user’s browser with the same access as
provided to the server’s regular scripts (i.e., subvert the Same
Origin Policy)
● Attacker tools: ability to leave content on the web server
(e.g., via an ordinary browser).
● Key trick: Server fails to ensure that content uploaded to page does
not contain embedded scripts

43
12/22/2023

Non-persistent (Reflected) XSS Attack


If a website with a reflective behaviour
takes user inputs, then :
o Attackers can put JavaScript code
in the input, so when the input is
reflected back, the JavaScript code
will be injected into the web page
from the website

Non-persistent (Reflected) XSS Attack


● Reflected attacks are those where the injected script is
reflected off the web server – Echoed Input
○ An error message, search result, or any other response that includes
some or all of the input sent to the server as part of the request
● Attacker gets you to send the bank.com server a URL that
includes some JavaScript code
○ bank.com echoes the script back to you in its response
○ Your browser executes the script in the response within the same origin
as bank.com

44
12/22/2023

Non-persistent (Reflected) XSS Attack


Echoed input
● The key to the reflected XSS attack is to find instances where a good web
server will echo the user input back in the HTML response

Non-persistent (Reflected) XSS Attack


● Assume a vulnerable service on website :
http://www.example.com/search?input=word, where word is provided by
the users
● Now the attacker sends the following URL to the victim and tricks him to
click the link:
http://www.example.com/search?input=<script>alert(“attack”);</script>
● Once the victim clicks on this link, an HTTP GET request will be sent to the
www.example.com web server, which returns a page containing the
search result, with the original input in the page
o The input here is a JavaScript code which runs and gives a pop-up message on the
victim’s browser

45
12/22/2023

Non-persistent (Reflected) XSS Attack


Exploiting echoed input

Browser would execute


this within victim.com’s
origin

Non-persistent (Reflected) XSS Attack

46
12/22/2023

Non-persistent (Reflected) XSS - Summary


● Target: User with Javascript-enabled browser who uses a
vulnerable web service that includes parts of URLs it receives in the
web page output it generates
● Attack goal: run script in user’s browser with the same access as
provided to the server’s regular scripts (i.e., subvert the Same
Origin Policy)
● Attacker tools: get user to click on a specially-crafted URL
● Key trick: Server does not ensure that it’s output does not contain
foreign, embedded scripts

Damage Caused by XSS


● Spoofing requests: The injected JavaScript code can send HTTP
requests to the server on behalf of the user
● Stealing information: The injected JavaScript code can also steal
victim’s private data including the session cookies, personal data
displayed on the web page, data stored locally by the web application
● Web defacing: JavaScript code can use DOM APIs to access the DOM
nodes inside the hosting page. Therefore, the injected JavaScript code
can make arbitrary changes to the page.
○ Example: JavaScript code can change a news article page to something fake or
change some pictures on the page

47
12/22/2023

Countermeasures - XSS

Countermeasures: Filter/Escape
● Typical defense is sanitizing: remove all executable portions of
user-provided content that will appear in HTML pages
○ E.g., look for <script>...</script> or
<javascript>...</javascript> from provided content and
remove it
○ So, if I fill in the “name” field for Facebook as
<script>alert(0)</script> and the script tags removed
● Often done on blogs, e.g., WordPress
https://wordpress.org/plugins/html-purified/

48
12/22/2023

Countermeasures: Filter/Escape
● It is difficult to implement as there are many ways to embed code
other than <script> tag
o lots of ways to introduce Javascript; e.g., CSS tags and XML-encoded data:
<div style="background-image:
url(javascript:alert(’JavaScript’))">...</div>

<XML ID=I><X><C><![CDATA[<IMG SRC="javas]]><!


[CDATA[script:alert(’XSS’);">]]>

● Use of open-source libraries that can filter out JavaScript code


o Example : jsoup - Java HTML Parser

Countermeasures: The Encoding Approach


● Replaces HTML markups with alternate representations
● If data containing JavaScript code is encoded before being sent to the
browsers, the embedded JavaScript code will be displayed by
browsers, not executed
o Converts <script> alert(‘XSS’)</script> to
&lt;script&gt;alert(‘XSS’)

49
12/22/2023

XSS vs. CSRF


Do not confuse the two:
● CSRF attacks exploit the trust the legitimate website has in data
sent from the client browser
○ So the attacker tries to control what the client browser sends to the
website
● XSS attacks exploit the trust a client browser has in data sent
from the legitimate website
○ So the attacker tries to control what the website sends to the client
browser

A01: Broken Access Control


● Broken Access Control (also known as Broken Authorization) is now the
number one vulnerability - OWASP Top 10
○ Moving up from the fifth position – Most serious web application security risk

50
12/22/2023

Broken Access Control


● RFC 4949, Internet Security Glossary,
defines access control as:
“A process by which use of system resources is
regulated according to a security policy and is
permitted only by authorized entities (users,
programs, processes, or other systems)
according to that policy”

● In the context of web applications, access


control is dependent on
○ Authentication
○ Session management

Broken Access Control


Authentication
● The process of validating the identity of the user – Method of proving
the identity
● Identifies the user and confirms that the user is who they say they are

51
12/22/2023

Broken Access Control


Authentication
● Authentication usually involves a two-step process

○ Entering public information (a username, employee number, account number, or


department ID), and then - Identification step

○ Entering private information (a static password, smart token, cognitive


password, one-time password, or PIN) – Authentication step

Broken Access Control


Authentication
● Three basic factors to authenticate an identity
○ Something you know (knowledge-based authentication)
■ Password, PIN
○ Something you have (Ownership-based Authentication)
■ key, swipe card, access card
○ Something you are (Biometric authentication)
■ Retina scan

● A more reliable authentication process would require two or all of these three factors
such as something you know with something you have
■ This form is known as the two-factor or multilevel authentication

52
12/22/2023

Broken Access Control


Session Management
● HTTP stateless but state needed => sessions
○ E.g., shopping cart in online shopping application
○ Basic idea:
■ User authenticates himself (login page)
■ A session starts
■ Server stores user info and state of the session in a table

Broken Access Control


Session Management
● A session token is normally composed of a string of variable width

● Identifies which subsequent HTTP requests are being made by each user

53
12/22/2023

Broken Access Control


Session Management
● Ways to include ID in request:
○ Cookies
■ Created by Set-Cookie field in the HTTP the response header
■ Small pieces of data stored in the browser;
● Name (content of the cookie)

● Expiration date/time

● Path and domain – browser sends cookie to URLs from the domain
+ within the path

● Secure – cookie sent only over HTTPS (not HTTP)

Broken Access Control


Session Management
● Ways to include ID in request:
○ Hidden field in a form
<input type=“hidden” name=“user” value=“ddee4454xerAFW45ex”>

○ In the URL
http://example.com/restricted.html?session_id=ddee4454xerAFW45ex

○ In the body of the http request

54
12/22/2023

Broken Access Control


Session Management
● Sessions are implemented by most current server side scripting
languages to track state
○ PHP, JSP, ASP.NET,…

● They are well tested so using the API defined in the language is
recommended
○ In PHP: session_start(), session_destroy()

Broken Access Control


Access Control or Authorization
● Determines whether the user is allowed to carry out the action that they are
attempting to perform

● The process of determining what that person is allowed to do, or what they
have access to
○ For example, an application may have separate roles for regular users and
administrators

55
12/22/2023

Broken Access Control


Access Control or Authorization

Broken Access Control


● Three different types of access control:
○ Vertical Access Control is used to restrict access to functions not
available for other users in the organization.
○ Different types of users have access to different application functions
○ For example, an administrator might be able to modify or delete any
user's account, while an ordinary user has no access to these actions.

56
12/22/2023

Broken Access Control


● Three different types of access control:
○ Horizontal Access Controls are mechanisms that restrict access to resources to
specific users
○ Different users have access to a subset of resources of the same type
○ For example, a banking application will allow a user to view transactions and make
payments from their own accounts, but not the accounts of any other user

Broken Access Control


● Three different types of access control:
○ Context-dependent access controls restrict access to functionality and resources
based upon the state of the application or the user's interaction with it
○ Prevent a user performing actions in the wrong order.
○ For example, a retail website might prevent users from modifying the contents of
their shopping cart after they have made payment

57
12/22/2023

Broken Access Control


Broken Access Control
● Refers to a vulnerability or flaw in web application security where the
application’s access control mechanisms are not properly implemented
○ Vulnerabilities arise when users can act outside of their intended permissions
● This leads to sensitive information disclosure, unauthorized access to restricted
resources and modification or destruction of data.

● When the access control of an application is broken


○ A regular user may be able to access functionality that is meant to be reserved for
administrators, or perhaps they can access data that does not belong to them.

Broken Access Control Vulnerabilities


● This vulnerability can occur in various forms, such as
○ Bypassing authentication by manipulating URL or HTTP parameters
○ Inadequate session management, leading to session hijacking
○ Using forced browsing to access restricted resources
○ Lack of access control checks on APIs

58
12/22/2023

Broken Access Control Vulnerabilities


Bypassing authentication by manipulating URL or HTTP parameters
● Arises where user-controller parameter values are used to access resources
or functions directly
● The application uses a parameter in the URL, such as a session ID, or item ID
○ If the parameter can be easily manipulated, an attacker could change the parameter in
the URL to access restricted pages without logging in

● Insecure direct object references (IDORs) - Occur if an application uses user-


supplied input to access objects directly and an attacker can modify the input
to obtain unauthorized access

Broken Access Control Vulnerabilities


Bypassing authentication by manipulating URL or HTTP parameters
● For instance,
http://example.com/restricted.html?session_id=abc123

● An attacker could change the session_id parameter in the URL to


http://example.com/restricted.html?session_id=def456 to bypass authentication and
access the restricted page.

59
12/22/2023

Broken Access Control Vulnerabilities


Inadequate Session Management
● If the application does not use secure session IDs and does not properly expire or
invalidate sessions after a certain amount of time or after a user logs out
○ An attacker could potentially steal the session ID and use it to hijack the user’s session

● The session token could be compromised in different ways:

○ Predictable session token

○ Session Sniffing

○ Client-side attacks (XSS, malicious JavaScript Codes, Trojans, etc.)

Broken Access Control Vulnerabilities


Inadequate Session Management
● If the application does not use secure session IDs and does not properly expire or
invalidate sessions after a certain amount of time or after a user logs out
○ An attacker could potentially steal the session ID and use it to hijack the user’s session

● For instance, consider a web application where users log in and are given a session
ID that is stored in a cookie
○ If the session ID is easily predictable or the cookie is not properly secured, an attacker
could steal the session ID and use it to access the user’s account without logging in

○ If the session ID is not invalidated after a user logs out, an attacker could potentially
reuse the session ID to continue accessing the user’s account even after the user has
logged out

60
12/22/2023

Broken Access Control Vulnerabilities


Inadequate Session Management
● Session hijacking: attacker discovers an
open session ID and sends commands to
that session
○ Session Sniffing
■ The attacker uses a sniffer to capture a valid
token session called “Session ID”

■ Then they use the valid token session to gain


unauthorized access to the Web Server.

Broken Access Control Vulnerabilities


Inadequate Session Management
● Session hijacking: attacker discovers an open
session ID and sends commands to that session
○ Cross Site Scripting
<SCRIPT>

alert(document.cookie);

</SCRIPT>

61
12/22/2023

Broken Access Control Vulnerabilities


Inadequate Session Management
● Session hijacking: attacker discovers an open session ID and sends
commands to that session
● To prevent Session hijacking, IDs have to be:

○ Unpredictable – to avoid attackers from guessing it and doing session hijacking

○ Have a defined expiration time – to mitigate session hijacking

○ Invalidate after log out

Broken Access Control Vulnerabilities


Forced browsing to access restricted resources
● When a user is able to access restricted pages or resources by simply changing
the URL or using direct links
● For instance, consider a web application with a page for administrators only,
accessible at http://example.com/admin.html
○ If the application does not properly check for user permissions before displaying the
page
■ A user could access the page by simply navigating to the URL, even if they are not an
administrator

62
12/22/2023

Broken Access Control Vulnerabilities


Forced browsing to access restricted resources
● Authentication protects most web applications – only users with sufficient
rights can access specific areas and pages after providing valid credentials
○ Forced browsing attempts to bypass these controls by directly requesting access to areas
beyond their access level or to authenticated areas of the application without providing
valid credentials
○ Improper configuration of permissions on these pages leaves them vulnerable to
unauthorized users and forceful browsing attacks.

Examples of Broken Access Controls


Vertical privilege escalation
● Occurs when an attacker gains access to privileged functionality that they are not
permitted to access
● Arises when an application does not enforce any protection for sensitive
functionality
● For example, a user might be able to access the administrative functions by
browsing to the relevant admin URL

63
12/22/2023

Examples of Broken Access Controls


Vertical privilege escalation
For example – Unprotected admin functionality
● If a non-administrative user can gain access to an admin page where they can
delete user accounts

Examples of Broken Access Controls


Horizontal Privilege Escalation
● Occurs if a user is able to gain access to resources belonging to another
user, instead of their own resources of that type.
○ For example, if an employee can access the records of other employees as well as
their own, then this is horizontal privilege escalation

64
12/22/2023

Examples of Broken Access Controls


Horizontal Privilege Escalation
● Insecure direct object references (IDORs) are a subcategory of access
control vulnerabilities
● Occur if an application uses user-supplied input to access objects directly
and an attacker can modify the input to obtain unauthorized access

Examples of Broken Access Controls


Access Control Vulnerabilities in Multi-Step Processes
● These type of vulnerabilities occur when access control rules are implemented
on some of the steps, but ignored on others.
○ Imagine a website where access controls are correctly applied to the first and second
steps, but not to the third step.
○ The website assumes that a user will only reach step 3 if they have already completed
the first steps, which are properly controlled.
○ An attacker can gain unauthorized access to the function by skipping the first two steps
and directly submitting the request for the third step with the required parameters.

65
12/22/2023

Examples of Broken Access Controls


Access Control Vulnerabilities in Multi-Step Processes
● These type of vulnerabilities occur when access control rules are implemented
on some of the steps, but ignored on others.

How to Prevent Access Control Vulnerabilities


● A number of application frameworks

● Unfortunately, frameworks do not yet have the capability of automatically


implementing permissions structures
● Permissions structures still need to be implemented by the developer
○ Because every application has specific, custom requirements

● In most cases, the reason that access control is broken is simply because it
has not been implemented
○ The mitigation is to implement it!

66
12/22/2023

How to Prevent Access Control Vulnerabilities


● Example: Get student grade without
access control
● The getGrade() function contains
no access control restrictions
● As a result, anyone who can send
requests to the web server is able to
get anyone's grade

How to Prevent Access Control Vulnerabilities


● Example: Get student grade with
access control
● the getCurrentUser()return
the details of the currently
authenticated user.
○ If the user's ID is not the same as
the ID they are requesting, then it
will return an "Access Denied"
message instead of the grade
details

67
12/22/2023

How to Prevent Access Control Vulnerabilities


● Example: Update student grade
without access control
● The updateGrade() function
contains no access control
restrictions
● As a result, anyone who can send
requests to the web server is able to
update grades

How to Prevent Access Control Vulnerabilities


● Example: Update student grade with
access control
● Only teachers to be able to upgrade
the grades, but not students
○ Need to implement role-based
permissions

● The code will return an "Access


Denied" message unless the user's
role is set to "teacher".

68
12/22/2023

How to Prevent Access Control Vulnerabilities


Where is the Vulnerability?

Answer: No verification is performed on line 8 to see if the order has been


made by the currently logged-in user

How to Prevent Access Control Vulnerabilities


● Access control vulnerabilities can be prevented by applying the following
principles:
○ Unless a resource is intended to be publicly accessible, deny access by default
■ At the code level, make it mandatory for developers to declare the access that is allowed for
each resource, and deny access by default.

○ Thoroughly audit and test access controls to ensure they work as designed

69
12/22/2023

A02: Cryptographic Failures


● Previously known as “Sensitive Data Exposure”
● Occur when sensitive data is insufficiently protected and therefore leaked
or exposed to unauthorized audiences
● Most common problems:
○ Sensitive data not encrypted
○ Use of known weak algorithms (MD5, RC3, RC4,…, SHA-1)
○ Hard-coding keys and storing keys in unprotected stores

● Protection:
○ Do the contrary…

A04: Insecure Design


● Secure design is a culture and methodology that constantly evaluates threats and
ensures that code is robustly designed and tested to prevent known attack
methods
● Threat modeling should be integrated

● In user story development determine the correct flow and failure states, ensure
they are well understood and agreed upon by responsible and impacted parties
● Analyze assumptions and conditions for expected and failure flows, ensure they
are still accurate and desirable
● Secure design is neither an add-on nor a tool that you can add to software

70
12/22/2023

A04: Insecure Design


Insecure design Vs Insecure implementation
● Design flaws and implementation defects and have different root causes and
remediation
● A secure design can still have implementation defects leading to vulnerabilities
that may be exploited
● An insecure design cannot be fixed by a perfect implementation

A05: Security Misconfiguration


● More examples
○ Default account isn’t changed; attacker can use it to login
○ Patch of an open source webapp not installed (e.g., phpmyadmin, Joomla,
WordPress, their plugins...)
○ Insecure default configurations
○ Incomplete configurations

● Protection: automated scanners


○ Useful tools for detecting missing patches, misconfigurations, use of default
accounts, unnecessary services, etc.

71

You might also like