Web Security
Web Security
CS364
Web Security Part 1
Prepared by
Niva Naik
TA- SVNIT
1
Contents (As per Syllabus)
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
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…
19
Software Security during SDLC
External Review
3. Penetration Testing
20
Web Browser and Network
request
Browser Web
reply site
OS
Hardware Network
21
Background
• Many sensitive tasks are done through web
– Online banking, online shopping
– Database access
– System administration
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
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?
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
29
Big questions
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)
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
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
42
Same Original Policy: What it Controls
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)
45
Cross-Site Scripting (XSS)
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
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.
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>
55
How XSS can be performed?
(Reflected)
• Now enter the same payload in the key-in field
and click Submit.
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
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))
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
• 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 …
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:
✑ 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
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:
✑ 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
✑ 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’"
✑ 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 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
110
User Authentication
The process of verifying a claim that a system entity or
system resource has a certain attribute value.
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
► 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
121/2
►Countermeasure: none—admin users must be trusted!
Outsider attack: attacker gains unauthorised access to database
8
125
Session Hijacking
126
Spoofing V/S Hijacking
127
Spoofing V/S Hijacking
128
Steps of session hijacking
129
Types of hijacking
130
Session hijacking levels
131
Network layer
132
The 3-way handshake
133
Sequence number
135
TCP/IP hijacking
136
TCP/IP hijacking
137
Blind hijacking
138
Man in the middle attack
139
Application layer session hijacking
140
Tools for session hijacking
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?
144
What is file inclusion?
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
148
Local file inclusion
149
Local file inclusion
150
Local file inclusion
151
Example of local file inclusion
152
Example of local file inclusion
153
Example of local file inclusion
• http://victim.example/my_app/display.php?file=po
em.txt
154
Example of local file inclusion
155
Example of local file inclusion
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
160
Avoidance of local file inclusion
161
Remote file inclusion
162
Remote file inclusion
163
Remote file inclusion
164
Remote file inclusion
166
Example of remote file inclusion
• <?PHP
• $module = $_GET["module"];
• include $module;
• ?>
167
Example of remote file inclusion
• 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
• http://example.com/index.php?module=http://ser
ver2.example.com/welcome.php
169
Example of remote file inclusion
171
Prevention of remote file inclusion
172
Demonstration using 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
176
Demonstration
177
Demonstration
178
Authentication and
Session
management
Introduction
• 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